@gjermundgaraba/clankerauth-dev 0.25.0 → 0.26.1
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/src-B4z2ekdT.mjs
DELETED
|
@@ -1,539 +0,0 @@
|
|
|
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-b-Y2GjU9.mjs";import{t as d}from"./compiled-query-C8AL3JwF.mjs";import{A as f,B as p,C as m,D as h,E as g,F as _,G as v,H as y,I as b,K as x,L as S,N as ee,P as C,R as te,S as ne,T as w,U as T,V as re,W as ie,_ as ae,a as oe,b as se,c as ce,d as le,f as ue,g as de,h as fe,i as pe,j as me,k as he,l as ge,m as _e,o as ve,p as ye,q as be,t as xe,u as Se,v as Ce,w as eee,x as we,y as Te,z as Ee}from"./get-id-field-CHlYHt3y.mjs";import{A as De,C as Oe,D as ke,E as Ae,F as je,I as Me,L as Ne,M as E,N as D,O as Pe,P as O,S as k,T as tee,_ as Fe,a as nee,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,i as He,j as Ue,k as We,l as Ge,m as Ke,n as qe,o as Je,p as Ye,r as Xe,s as Ze,t as Qe,u as $e,v as A,w as et,x as tt,y as nt}from"./schemas-CYWNDEcx.mjs";import{a as rt,c as ree,l as iee,o as aee,r as oee,s as see}from"./schema-check-6AE7KkNs.mjs";import{n as cee,r as lee}from"./factory-tEOeUNZI.mjs";import{n as uee}from"./access-CoaNEa0I.mjs";import*as it from"node:crypto";import{randomBytes as at,scrypt as ot}from"node:crypto";import*as st from"node:path";import ct,{dirname as lt,join as ut,resolve as dt}from"node:path";import*as ft from"node:url";import{fileURLToPath as pt}from"node:url";import mt,*as ht from"node:os";import*as gt from"node:child_process";import{Duplex as _t,PassThrough as vt,Readable as yt,pipeline as bt}from"node:stream";import{IncomingMessage as xt,createServer as dee}from"node:http";import{isIP as St}from"node:net";import*as Ct from"node:fs";import wt,{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 Tt from"node:zlib";import*as Et from"node:readline";import{DatabaseSync as gee}from"node:sqlite";import Dt from"node:fs/promises";import{lookup as _ee}from"node:dns/promises";const Ot=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},kt={pipe(){return Ot(this,arguments)}},At=/*#__PURE__*/ function(){function e(){}return e.prototype=kt,e}(),j=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},M=e=>e,jt=e=>()=>e,Mt=/*#__PURE__*/ jt(!0),Nt=/*#__PURE__*/ jt(!1),Pt=/*#__PURE__*/ jt(void 0),Ft=Pt;function It(e,...t){return Ot(e,t)}function Lt(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 Rt(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function zt(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 Bt=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},Vt=/*#__PURE__*/ new WeakSet,Ht=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Ut=0;const Wt=()=>{Ut++};function Gt(e){return typeof e==`string`}function Kt(e){return typeof e==`number`}function qt(e){return typeof e==`boolean`}function Jt(e){return typeof e==`symbol`}function Yt(e){return Gt(e)||Kt(e)||Jt(e)}function Xt(e){return typeof e==`function`}function Zt(e){return e===void 0}function Qt(e){return e!==void 0}function $t(e){return e!==null}function en(e){return e==null}function vee(e){return e!=null}function yee(e){return!1}function tn(e){return!0}function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e){return nn(e)}function an(e){return typeof e==`object`&&!!e||Xt(e)}const N=/*#__PURE__*/ j(2,(e,t)=>an(e)&&t in e),on=/*#__PURE__*/ j(2,(e,t)=>N(e,`_tag`)&&e._tag===t);function bee(e){return e instanceof Error}function xee(e){return N(e,Symbol.iterator)||Gt(e)}const sn=`~effect/Hash`,cn=e=>{switch(typeof e){case`number`:return mn(e);case`bigint`:return hn(e.toString(10));case`string`:return hn(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?hn(`Invalid Date`):hn(e.toISOString());if(e instanceof RegExp)return hn(e.toString());{if(Vt.has(e))return ln(e);let t=wn.get(e);if(t!==void 0)return t;if(Tn.has(e))return Wt(),hn(`[Circular]`);Tn.add(e);let n=Ut,r;try{r=`~effect/Hash`in e?e[sn]():typeof e==`function`?ln(e):e instanceof DataView?yn(Ht(e)):Array.isArray(e)||ArrayBuffer.isView(e)?yn(e):e instanceof Map?bn(e):e instanceof Set?Sn(e):_n(e)}finally{Tn.delete(e)}return n===Ut&&wn.set(e,r),r}}return fn(un(hn(String(e))))},ln=e=>(Cn.has(e)||Cn.set(e,fn(Math.random()*4294967296|0)),Cn.get(e)),un=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),dn=/*#__PURE__*/ j(2,(e,t)=>un(Math.imul(e,2654435761)+Math.imul(t,2246822507))),fn=e=>e&3221225471|e>>>1&1073741824,pn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),mn=e=>{let t=e|0;return t===e?fn(t):(pn.setFloat64(0,e===e?e:NaN),fn(dn(pn.getInt32(0),pn.getInt32(4))))},hn=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return fn(t)},gn=(e,t)=>{let n=12289;for(let r of t)n^=dn(cn(r),cn(e[r]));return fn(n)},_n=e=>gn(e,Bt(e)),vn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return fn(r)},yn=e=>{let t=6151;for(let n of e)t=dn(t,cn(n));return fn(t)},bn=/*#__PURE__*/ vn(/*#__PURE__*/ hn(`Map`),([e,t])=>dn(cn(e),cn(t))),xn=/*#__PURE__*/ hn(`Set`),Sn=/*#__PURE__*/ vn(xn,e=>dn(xn,cn(e))),Cn=/*#__PURE__*/ new WeakMap,wn=/*#__PURE__*/ new WeakMap,Tn=/*#__PURE__*/ new WeakSet,En=`~effect/Equal`;function Dn(){return arguments.length===1?e=>On(e,arguments[0]):On(arguments[0],arguments[1])}function On(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||Vt.has(e)||Vt.has(t)?!1:kn(e,t):!1}function kn(e,t){let n=jn.length;for(let r=n;r-->0;)if(jn[r]===e&&Mn[r]===t)return!0;if(n)return An(e,t);let r=Nn.get(e);r||Nn.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=An(e,t)),i}function An(e,t){jn.push(e),Mn.push(t);try{return Pn(e,t)}finally{jn.pop(),Mn.pop()}}const jn=[],Mn=[],Nn=/*#__PURE__*/ new WeakMap;function Pn(e,t){if(cn(e)!==cn(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=zn(e);if(n!==zn(t)||typeof e==`function`&&!n)return!1;if(n)return e[En](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Fn(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?In(Ht(e),Ht(t)):In(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Rn(e,t,See,Cee):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Rn(e,t,cn,On):Ln(e,t)}function Fn(e,t){for(let n=0;n<e.length;n++)if(!On(e[n],t[n]))return!1;return!0}function In(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 Ln(e,t){let n=Bt(e),r=Bt(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!On(e[i],t[i]))return!1;return!0}function Rn(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 See=e=>cn(e[0]),Cee=(e,t)=>On(e[0],t[0])&&On(e[1],t[1]),zn=e=>N(e,En),wee=()=>Dn,Bn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),Tee=e=>N(e,Bn);function Vn(e){return Tee(e)?Hn(e):e}function Hn(e){return e[Bn](globalThis[`~effect/Fiber/currentFiber`]?.context??Eee)}const Un=`~effect/Fiber/currentFiber`,Wn=/*#__PURE__*/ new Map,Eee={"~effect/Context":{},base:Wn,depth:0,mapUnsafe:Wn,pipe(){return Ot(this,arguments)}};function Gn(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 Dee;r.add(e);let l;if(Bn in e)l=c(Hn(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=Oee(e);else if(!t?.ignoreToString&&N(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=kee(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=>`${Kn(t)}:${c(Jn(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Kn(t)}: ${c(Jn(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 Dee=`[Circular]`;function Kn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function qn(e){return e.map(e=>`[${Kn(e)}]`).join(``)}function Oee(e){try{return e.toISOString()}catch{return`Invalid Date`}}function kee(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Jn(e,t){try{return e[t]}catch{return`[property access threw]`}}function Yn(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=N(r,Bn)?Vn(r):Vn(t);if(typeof i==`bigint`)return Gn(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),!Aee(a)||jee(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:Vn(n)}});return n.push(o),o},t?.space)??`null`}function Aee(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function jee(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 Xn=/*#__PURE__*/ Symbol.for(`nodejs.util.inspect.custom`),Zn=e=>{try{return e=Vn(e),N(e,`toJSON`)&&Xt(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(Zn):e}catch{return`[toJSON threw]`}},Mee=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Yn(e,{space:t}):Gn(e,{space:t})}catch{return String(e)}},Qn={toJSON(){return Zn(this)},[Xn](){return this.toJSON()},toString(){return Gn(this.toJSON())}};var $n=class{[Xn](){return this.toJSON()}toString(){return Gn(this.toJSON())}};const Nee=/*#__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})(),er=()=>Error.stackTraceLimit,tr=e=>{Nee&&(Error.stackTraceLimit=e)};var nr=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 rr=/*#__PURE__*/ (()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=er();if(r===0)return n[e];tr(2);let i=t[e](()=>/* @__PURE__ */ Error());return tr(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function ir(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function ar(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&ir(e,n,t[n])}const or=`~effect/Effect`,sr=`~effect/Exit`,cr={_A:M,_E:M,_R:M},lr=`${or}/identifier`,ur=`${or}/args`,dr=`${or}/evaluate`,fr=`${or}/successCont`,pr=`${or}/failureCont`,mr=`${or}/ensureCont`,hr=/*#__PURE__*/ Symbol.for(`effect/Effect/Yield`),gr={pipe(){return Ot(this,arguments)},toJSON(){return{...this}},toString(){return Gn(this.toJSON(),{ignoreToString:!0,space:2})},[Xn](){return this.toJSON()}},_r={[or]:cr,...gr,[Symbol.iterator](){return new nr(this)},toJSON(){return{_id:`Effect`,op:this[lr],...`~effect/Effect/args`in this?{args:this[ur]}:void 0}}},vr=e=>N(e,or),yr=e=>N(e,sr),br=`~effect/Cause`,xr=`~effect/Cause/Reason`,Sr=e=>N(e,br),Cr=e=>N(e,xr);var wr=class{constructor(e){this[br]=br,this.reasons=e}pipe(){return Ot(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${Gn(this.reasons)})`}[Xn](){return this.toJSON()}[En](e){return Sr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Dn(t,e.reasons[n]))}[sn](){return yn(this.reasons)}};const Tr=/*#__PURE__*/ new WeakMap;var Er=class{[xr];annotations;_tag;constructor(e,t,n){if(this[xr]=xr,this._tag=e,t!==Dr&&typeof n==`object`&&n&&t.size>0){let e=Tr.get(n);e&&(t=new Map([...e,...t])),Tr.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return Ot(this,arguments)}toString(){return Gn(this)}[Xn](){return this.toString()}};const Dr=/*#__PURE__*/ new Map;var Or=class extends Er{constructor(e,t=Dr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${Gn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[En](e){return Rr(e)&&Dn(this.error,e.error)&&Dn(this.annotations,e.annotations)}[sn](){return dn(hn(this._tag))(dn(cn(this.error))(cn(this.annotations)))}};const kr=e=>new wr(e),Ar=(e,t)=>{let n=/* @__PURE__ */ new Map,r=[];for(let i of e.concat(t)){let e=cn(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>Dn(e,i)))continue;else t.push(i);r.push(i)}return r},jr=/*#__PURE__*/ j(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new wr(Ar(e.reasons,t.reasons));return Dn(e,n)?e:n}),Mr=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)Br(e)&&!n.some(t=>Br(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new wr(n)},Nr=/*#__PURE__*/ new wr([]),Pr=e=>new wr([new Or(e)]);var Fr=class extends Er{constructor(e,t=Dr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${Gn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[En](e){return zr(e)&&Dn(this.defect,e.defect)&&Dn(this.annotations,e.annotations)}[sn](){return dn(hn(this._tag))(dn(cn(this.defect))(cn(this.annotations)))}};const Ir=e=>new wr([new Fr(e)]),Lr=/*#__PURE__*/ j(e=>Sr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new wr(e.reasons.map(e=>e.annotate(t,n)))),Rr=e=>e._tag===`Fail`,zr=e=>e._tag===`Die`,Br=e=>e._tag===`Interrupt`;function Pee(e){return Yr(`Effect.evaluate: Not implemented`)}const Vr=e=>({..._r,[lr]:e.op,[dr]:e[`~effect/Effect/evaluate`]??Pee,[fr]:e[fr],[pr]:e[pr],[mr]:e[mr]}),Hr=e=>{let t=Vr(e),n=function(e){this[ur]=e};return n.prototype=t,function(e){return new n(e)}},Ur=e=>{let t={[sr]:sr,_tag:e.op,get[e.prop](){return this[ur]},...Vr(e),toString(){return`${e.op}(${Gn(this[ur])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[ur]}},[En](e){return yr(e)&&e._tag===this._tag&&Dn(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[sn](){return dn(hn(e.op),cn(this[ur]))}},n=function(e){this[ur]=e};return n.prototype=t,function(e){return new n(e)}},Wr=/*#__PURE__*/ Ur({op:`Success`,prop:`value`,[dr](e){let t=e.getCont(fr);return t?t[fr](this[ur],e,this):e.yieldWith(this)}}),Gr={key:`effect/Cause/StackTrace`},Kr={key:`effect/Cause/InterruptorStackTrace`},qr=/*#__PURE__*/ Ur({op:`Failure`,prop:`cause`,[dr](e){let t=this[ur],n=!1;e.cache.stackFrame&&(t=Lr(t,{mapUnsafe:/* @__PURE__ */ new Map([[Gr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(pr),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=lr in r,r=e.getCont(pr);a&&(t=kr(t.reasons.filter(e=>e._tag!==`Fail`))),t=Mr(t,i),n=!0}return r?r[pr](t,e,n?void 0:this):e.yieldWith(n?qr(t):this)}}),Jr=e=>qr(Pr(e)),Yr=e=>qr(Ir(e)),Xr=/*#__PURE__*/ Hr({op:`WithFiber`,[dr](e){return this[ur](e)}}),Fee=/*#__PURE__*/ function(){class e extends globalThis.Error{}let t=/*#__PURE__*/ Vr({op:`YieldableError`,[dr](){return Jr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Zr=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Symbol.for(`effect/Data/Error/plainArgs`);return class extends Fee{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(ar(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),Qr=e=>{class t extends Zr{_tag=e}return t.prototype.name=e,t},Iee=e=>N(e,`~effect/Cause/NoSuchElementError`),$r=`~effect/Cause/Done`,Lee=e=>N(e,$r),ei={[$r]:$r,_tag:`Done`,value:void 0},ti=e=>e===void 0?ei:{[$r]:$r,_tag:`Done`,value:e},Ree=/*#__PURE__*/ Jr(ei),zee=e=>e===void 0?Ree:Jr(ti(e)),ni=e=>Vr({op:e.label,[dr]:e.evaluate}),ri=e=>(t,n)=>t===n||e(t,n),Bee=(e,t)=>e===t,ii=()=>Bee;function Vee(e){return ri((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 Hee(e){return ri((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 ai=`~effect/Option`,oi={[ai]:{_A:e=>e},...gr,[Symbol.iterator](){return new nr(this)}},Uee=/*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(oi),{_tag:`Some`,_op:`Some`,[En](e){return si(e)&&li(e)&&Dn(this.value,e.value)},[sn](){return dn(cn(this._tag))(cn(this.value))},toString(){return`some(${Gn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:Zn(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Wee=/*#__PURE__*/ cn(`None`),Gee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(oi),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[En](e){return si(e)&&ci(e)},[sn](){return Wee},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),si=e=>N(e,ai),ci=e=>e._tag===`None`,li=e=>e._tag===`Some`,Kee=/*#__PURE__*/ Object.create(Gee),ui=function(e){this.value=e};ui.prototype=Uee;const qee=e=>new ui(e),di=`~effect/Result`,fi={[di]:{
|
|
4
|
-
/* v8 ignore next 2 */
|
|
5
|
-
_A:e=>e,_E:e=>e},...gr,[Symbol.iterator](){return new nr(this)}},Jee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(fi),{_tag:`Success`,_op:`Success`,[En](e){return pi(e)&&hi(e)&&Dn(this.success,e.success)},[sn](){return dn(cn(this._tag))(cn(this.success))},toString(){return`success(${Gn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:Zn(this.success)}}}),Yee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(fi),{_tag:`Failure`,_op:`Failure`,[En](e){return pi(e)&&mi(e)&&Dn(this.failure,e.failure)},[sn](){return dn(cn(this._tag))(cn(this.failure))},toString(){return`failure(${Gn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:Zn(this.failure)}}}),pi=e=>N(e,di),mi=e=>e._tag===`Failure`,hi=e=>e._tag===`Success`,gi=function(e){this.failure=e};gi.prototype=Yee;const _i=e=>new gi(e),vi=function(e){this.success=e};vi.prototype=Jee;const yi=e=>new vi(e);function bi(e){return(t,n)=>t===n?0:e(t,n)}const xi=/*#__PURE__*/ bi((e,t)=>e<t?-1:1),Si=/*#__PURE__*/ bi((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),Ci=/*#__PURE__*/ j(2,(e,t)=>bi((n,r)=>e(t(n),t(r)))),wi=e=>j(2,(t,n)=>e(t,n)===-1),Ti=e=>j(2,(t,n)=>e(t,n)===1),Ei=e=>j(2,(t,n)=>e(t,n)!==1),Di=e=>j(2,(t,n)=>e(t,n)!==-1),Oi=()=>Kee,ki=qee,Ai=ci,ji=li,Mi=/*#__PURE__*/ j(2,(e,{onNone:t,onSome:n})=>Ai(e)?t():n(e.value)),Ni=/*#__PURE__*/ j(2,(e,t)=>Ai(e)?t():e.value),Pi=/*#__PURE__*/ j(2,(e,t)=>Ai(e)?t():e),Fi=e=>e==null?Oi():ki(e),Ii=e=>e===void 0?Oi():ki(e),Li=/*#__PURE__*/ Ni(Pt),Ri=e=>(...t)=>{try{return ki(e(...t))}catch{return Oi()}},zi=/*#__PURE__*/ j(2,(e,t)=>Ai(e)?Oi():ki(t(e.value))),Bi=/*#__PURE__*/ j(2,(e,t)=>Ai(e)?Oi():t(e.value)),Vi=/*#__PURE__*/ j(2,(e,t)=>Ai(e)?Oi():t(e.value)?ki(e.value):Oi()),Hi=`~effect/Context/Service`,P=function(){function e(){}let t=e;Object.setPrototypeOf(t,Ui);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Gi]=Gi,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Wi.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Ui={[Hi]:Hi,.../*#__PURE__*/ ni({label:`Service`,evaluate(e){return Wr(la(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return ra(this,e)},use(e){return Xr(t=>e(la(t.context,this)))},useSync(e){return Xr(t=>Wr(e(la(t.context,this))))}},Wi=/*#__PURE__*/ new Set,Gi=`~effect/Context/Reference`,Ki=`~effect/Context`,qi=(e,t,n,r)=>{let i=Object.create(Xee);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Ji=(e,t)=>{t&&(Ji(e,t.parent),e.set(t.key,t.value))},Yi=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Ji(t,e.overlay),e._flat=t},Xi=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),$i(n)},Zi=/*#__PURE__*/ Symbol(),Qi=(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)?Zi:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=8&&(n.base=Yi(n),n.overlay=void 0,n.depth=0),r)},$i=e=>qi(void 0,e,void 0,0),Xee={get mapUnsafe(){return Yi(this)},...gr,[Ki]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[En](e){if(!ea(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!Dn(r,n.get(e)))return!1;return!0},[sn](){return mn(this.mapUnsafe.size)}},Zee=(e,t)=>e.cacheRoot===t.cacheRoot,ea=e=>N(e,Ki),Qee=e=>N(e,Hi),ta=e=>!!e[Gi],na=()=>$ee,$ee=/*#__PURE__*/ $i(/*#__PURE__*/ new Map),ra=(e,t)=>$i(/* @__PURE__ */ new Map([[e.key,t]])),ia=/*#__PURE__*/ j(3,(e,t,n)=>ete(e,t.key,n)),ete=(e,t,n)=>{let r=e,i=Wi.has(t)?void 0:r.cacheRoot;if(r.depth>=8){let e=new Map(r._flat??r.base);return r._flat||Ji(e,r.overlay),e.set(t,n),qi(i,e,void 0,0)}return qi(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},aa=/*#__PURE__*/ j(3,(e,t,n)=>{let r=Qi(e,t.key);return r===Zi?ta(t)?da(t):n():r}),oa=/*#__PURE__*/ j(2,(e,t)=>sa(e,t.key)),sa=(e,t)=>{let n=Qi(e,t);return n===Zi?void 0:n},ca=/*#__PURE__*/ j(2,(e,t)=>{let n=Qi(e,t.key);if(n===Zi){if(ta(t))return da(t);throw tte(t)}return n}),la=ca,ua=`~effect/Context/defaultValue`,da=e=>ua in e?e[ua]:e[ua]=e.defaultValue(),tte=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},fa=/*#__PURE__*/ j(2,(e,t)=>{let n=Qi(e,t.key);return n===Zi?ta(t)?ki(da(t)):Oi():ki(n)}),pa=/*#__PURE__*/ j(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:Xi(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),nte=(...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 $i(t)},ma=(...e)=>t=>Xi(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),ha=P,ga=e=>e.length>0,_a=e=>e>0?Math.floor(e):0,va=yi,ya=_i,rte=e=>{if(Xt(e))try{return va(e())}catch(e){return ya(e)}try{return va(e.try())}catch(t){return ya(e.catch(t))}},ba=pi,xa=mi,Sa=hi,ite=/*#__PURE__*/ j(2,(e,t)=>xa(e)?ya(t(e.failure)):e),Ca=/*#__PURE__*/ j(2,(e,t)=>Sa(e)?va(t(e.success)):e),ate=/*#__PURE__*/ j(2,(e,{onFailure:t,onSuccess:n})=>xa(e)?t(e.failure):n(e.success)),ote=/*#__PURE__*/ (/* @__PURE__ */ j(2,(e,t)=>xa(e)?t(e.failure):e.success))(Pt),ste=Vee,cte=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},lte=()=>({}),ute=e=>Object.keys(e).length===0,dte=/*#__PURE__*/ j(2,(e,t)=>Object.hasOwn(e,t)),wa=/*#__PURE__*/ j(2,(e,t)=>{let n={...e};for(let r of Ta(e))ir(n,r,t(e[r],r));return n}),fte=/*#__PURE__*/ j(2,(e,t)=>{let n=lte();for(let r of Ta(e))t(e[r],r)&&ir(n,r,e[r]);return n}),Ta=e=>Object.keys(e),pte=/*#__PURE__*/ j(3,(e,t,n)=>({...e,[t]:n})),mte=e=>j(2,(t,n)=>{for(let r of Ta(t))if(!dte(n,r)||!e(t[r],n[r]))return!1;return!0}),hte=e=>{let t=mte(e);return(e,n)=>t(e,n)&&t(n,e)},Ea=globalThis.Array,Da=e=>Ea.isArray(e)?e:Ea.from(e),Oa=e=>Ea.isArray(e)?e:[e],ka=/*#__PURE__*/ j(2,(e,t)=>[...e,t]);Ea.isArray;const Aa=ga,ja=ga;function gte(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const _te=(e,t)=>Math.min(_a(e),t),vte=/*#__PURE__*/ j(2,(e,t)=>{let n=Da(e);return n.slice(0,_te(t,n.length))}),yte=e=>Ea.from(e).reverse(),bte=(e,t)=>{let n=cn(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(Dn(e,t))return!1;return r.push(t),!0},Ma=()=>[],Na=e=>[e],Pa=/*#__PURE__*/ j(2,(e,t)=>e.map(t)),xte=Hee,Ste=e=>{let t=Da(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)bte(n,e)&&r.push(e);return r},Fa=`~effect/Duration`,Ia=/*#__PURE__*/ BigInt(0),La=/*#__PURE__*/ BigInt(1),Cte=/*#__PURE__*/ BigInt(2),wte=/*#__PURE__*/ BigInt(10),Ra=/*#__PURE__*/ BigInt(24),za=/*#__PURE__*/ BigInt(60),Ba=/*#__PURE__*/ BigInt(1e3),Va=/*#__PURE__*/ BigInt(1e6),Ha=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Ua=e=>Number.isInteger(e)?BigInt(e)*Va:Ha(e*1e6),Wa=e=>Ya(Number.isFinite(e)?Ha(e):e),Ga=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=wte**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return Tte(r?-o:o,a)},Tte=(e,t)=>{let n=e<Ia?-e:e,r=n/t+(n%t*Cte>=t?La:Ia);return e<Ia?-r:r},Ete=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Ka=e=>{switch(typeof e){case`number`:return io(e);case`bigint`:return ro(e);case`string`:{if(e===`Infinity`)return to;if(e===`-Infinity`)return no;let t=Ete.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return ro(Ga(r,La));if(i===`micro`||i===`micros`)return ro(Ga(r,Ba));let a=Number(r);switch(i){case`milli`:case`millis`:return io(a);case`second`:case`seconds`:return ao(a);case`minute`:case`minutes`:return oo(a);case`hour`:case`hours`:return so(a);case`day`:case`days`:return co(a);case`week`:case`weeks`:return lo(a)}break}case`object`:{if(e===null)break;if(Fa in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Kt)?qa(e):Number.isNaN(e[0])||Number.isNaN(e[1])?eo:e[0]===-1/0||e[1]===-1/0?no:e[0]===1/0||e[1]===1/0?to:Wa(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?Ya(n):Wa(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0))}}return qa(e)},qa=e=>{throw Error(`Invalid Input: ${e}`)},Ja={_tag:`Millis`,millis:0},Dte={_tag:`Infinity`},Ote={_tag:`NegativeInfinity`},kte={[Fa]:Fa,[sn](){switch(this.value._tag){case`Millis`:return cn(Ua(this.value.millis));case`Nanos`:return cn(this.value.nanos);default:return _n(this.value)}},[En](e){return Ate(e)&&_o(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`}}},[Xn](){return this.toJSON()},pipe(){return Ot(this,arguments)}},Ya=e=>{let t=Object.create(kte);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Ja:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ua(e)}:e>0?Dte:Ote:e===Ia?Ja:{_tag:`Nanos`,nanos:e},t},Ate=e=>N(e,Fa),Xa=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,Za=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Ia;case`Infinity`:case`NegativeInfinity`:return!1}},Qa=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Ia;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},$a=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return to;case`Millis`:return e.value.millis<0?Ya(-e.value.millis):e;case`Nanos`:return e.value.nanos<Ia?Ya(-e.value.nanos):e}},eo=/*#__PURE__*/ Ya(0),to=/*#__PURE__*/ Ya(1/0),no=/*#__PURE__*/ Ya(-1/0),ro=e=>Ya(e),io=e=>Ya(e),ao=e=>Ya(e*1e3),oo=e=>Ya(e*6e4),so=e=>Ya(e*36e5),co=e=>Ya(e*864e5),lo=e=>Ya(e*6048e5),uo=e=>mo(Ka(e),{onMillis:M,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),fo=e=>mo(Ka(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),po=e=>{let t=Ka(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 Ua(t.value.millis)}},mo=/*#__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)()}}),ho=/*#__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(po(e),t.value.nanos):n.onNanos(e.value.nanos,po(t))),go=(e,t)=>ho(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),_o=/*#__PURE__*/ j(2,(e,t)=>go(e,t)),vo=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=po(e),n=t<Ia,r=n?-t:t,i=r/Va,a=i/Ba,o=a/za,s=o/za,c=s/Ra,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Ra),minutes:l*Number(o%za),seconds:l*Number(a%za),millis:l*Number(i%Ba),nanos:l*Number(r%Va)}},yo=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(Za(e))return`0`;if(Qa(e))return`-`+yo($a(e));let t=vo(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(` `)},bo=/*#__PURE__*/ ha(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new To}),xo=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},So=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},Co=e=>{try{return So(e)}catch{return xo(e)}};var wo=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}},To=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?xo:Co)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Eo(this.setImmediate)}},Eo=class{tasks=/*#__PURE__*/ new wo;running=void 0;setImmediate;constructor(e=Co){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 Do=/*#__PURE__*/ ha(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Oo=/*#__PURE__*/ ha(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),ko=class extends At{constructor(e){super(),e&&ar(this,e)}},Ao=e=>class extends ko{_tag=e},jo=()=>new Proxy({},{get(e,t,n){return t===`$is`?on:t===`$match`?Mo:e=>({...e,_tag:t})}});function Mo(){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 No=Zr,Po=Qr,Fo=`~effect/encoding/EncodingError`;var Io=class extends (/*#__PURE__*/ Po(`EncodingError`)){[Fo]=Fo};const Lo=e=>{switch(e){case 16:return Vo();case 32:return Ho();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Bo();return t}}},Ro=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),zo=()=>Math.random()*4294967296>>>0,Bo=()=>{let e=zo();return String.fromCharCode(Ro[e>>>28],Ro[e>>>24&15],Ro[e>>>20&15],Ro[e>>>16&15],Ro[e>>>12&15],Ro[e>>>8&15],Ro[e>>>4&15],Ro[e&15])},Vo=()=>{let e=zo(),t=zo();return String.fromCharCode(Ro[e>>>28],Ro[e>>>24&15],Ro[e>>>20&15],Ro[e>>>16&15],Ro[e>>>12&15],Ro[e>>>8&15],Ro[e>>>4&15],Ro[e&15],Ro[t>>>28],Ro[t>>>24&15],Ro[t>>>20&15],Ro[t>>>16&15],Ro[t>>>12&15],Ro[t>>>8&15],Ro[t>>>4&15],Ro[t&15])},Ho=()=>{let e=zo(),t=zo(),n=zo(),r=zo();return String.fromCharCode(Ro[e>>>28],Ro[e>>>24&15],Ro[e>>>20&15],Ro[e>>>16&15],Ro[e>>>12&15],Ro[e>>>8&15],Ro[e>>>4&15],Ro[e&15],Ro[t>>>28],Ro[t>>>24&15],Ro[t>>>20&15],Ro[t>>>16&15],Ro[t>>>12&15],Ro[t>>>8&15],Ro[t>>>4&15],Ro[t&15],Ro[n>>>28],Ro[n>>>24&15],Ro[n>>>20&15],Ro[n>>>16&15],Ro[n>>>12&15],Ro[n>>>8&15],Ro[n>>>4&15],Ro[n&15],Ro[r>>>28],Ro[r>>>24&15],Ro[r>>>20&15],Ro[r>>>16&15],Ro[r>>>12&15],Ro[r>>>8&15],Ro[r>>>4&15],Ro[r&15])},Uo=`effect/Tracer/ParentSpan`;var Wo=class extends (/*#__PURE__*/ P()(Uo,{fiberCached:!0})){};const Go=e=>e,Ko=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??na()}),qo=/*#__PURE__*/ ha(`effect/Tracer/DisablePropagation`,{defaultValue:Nt}),Jo=/*#__PURE__*/ ha(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Yo=/*#__PURE__*/ ha(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),Xo=`effect/Tracer`,Zo=/*#__PURE__*/ ha(Xo,{fiberCached:!0,defaultValue:()=>Qo}),Qo=/*#__PURE__*/ Go({span:e=>new $o(e)});var $o=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??=Li(this.parent)?.traceId??Lo(32)}get spanId(){return this._spanId??=Lo(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 es=/*#__PURE__*/ ha(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),ts=/*#__PURE__*/ ha(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Pt}),ns=/*#__PURE__*/ ha(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:Mt}),rs=/*#__PURE__*/ ha(`effect/References/TracerTimingEnabled`,{defaultValue:Mt}),is=/*#__PURE__*/ ha(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),as=/*#__PURE__*/ ha(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),os=/*#__PURE__*/ ha(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),ss=/*#__PURE__*/ ha(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),cs=/*#__PURE__*/ ha(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),ls=/*#__PURE__*/ ha(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),us=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=er();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};tr(3);let n=/* @__PURE__ */ Error();return tr(t),{...e,captureStackTrace:jte(()=>n.stack)}},ds=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}},jte=/*#__PURE__*/ ds(3);var fs=class extends Er{constructor(e,t=Dr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[En](e){return Br(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[sn](){return hn(`${this._tag}:${this.fiberId}`)}};const Mte=e=>new fs(e),ps=e=>new wr([new fs(e)]),Nte=e=>{let t=e.reasons.find(Rr);return t?va(t):ya(e)},ms=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return va(n.error)}return ya(e)},hs=e=>e.reasons.some(zr),Pte=e=>{let t=e.reasons.find(zr);return t?va(t.defect):ya(e)},gs=e=>e.reasons.some(Br),_s=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?va(t):ya(e)},Fte=e=>{let t=_s(e);return xa(t)?Ite:t.success},Ite=/*#__PURE__*/ new Set,Lte=e=>e.reasons.length>0&&e.reasons.every(Br),Rte=e=>$i(e.annotations),zte=/*#__PURE__*/ j(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>Rr(e)?(n=!0,new Or(t(e.error),e.annotations)):e);return n?kr(r):e}),vs=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},Bte=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=er();i!==0&&tr(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(ys(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=Wte(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(ys(i,r[0].annotations,t))}}finally{i!==0&&tr(i)}return n},ys=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Vte(e),{cause:e.cause?ys(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=Ute(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?bs(e,t):e}n?.includeCauseInStack&&(i.stack=Cs(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else{i=new globalThis.Error(e?r===`string`?e:Yn(e):`Unknown error: ${e}`);let n=`${i.name}: ${i.message}`;i.stack=t?bs(n,t):n}return i},Vte=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 Yn(e)},Hte=/\((.*)\)/g,Ute=(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?bs(a.join(`
|
|
10
|
-
`),n):a.join(`
|
|
11
|
-
`)},bs=(e,t)=>{let n=t?.get(Gr.key);return n&&(e=`${e}\n${xs(n)}`),e},Wte=(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(Kr.key);n.push(` at fiber (${t})`),r&&n.push(xs(r))}return n.join(`
|
|
12
|
-
`)},xs=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Hte),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
|
-
`)},Ss=e=>Bte(e).map(Cs).join(`
|
|
14
|
-
`),Cs=e=>e.cause?`${e.stack} {\n${ws(e.cause,` `)}\n}`:e.stack,ws=(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${ws(e.cause,`${t} `)}\n${t}}`),r},Ts=`~effect/Fiber`,Gte={_A:M,_E:M},Kte={id:0},Es=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Ds=()=>Es===void 0?void 0:new Es(`effect/Fiber`),Os=()=>globalThis[Un];var ks=class{constructor(e,t=!0){this.setContext(e),this.id=++Kte.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[Ts](){return Gte}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return la(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Ft):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=ps(e);this.cache.stackFrame&&(n=Lr(n,ra(Gr,this.cache.stackFrame))),t&&(n=Lr(n,t)),this._interruptedCause=this._interruptedCause?Mr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(Ls(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===hr){this._asyncContext=Ds();return}let n=As.interruptChildren&&As.interruptChildren(this);if(n!==void 0)return this.evaluate(pc(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=na()}runLoop(e){let t=globalThis[Un];globalThis[Un]=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=Ls(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=pc(Vs,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[dr](this),i===hr){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 hr}}catch(e){if(!N(i,`~effect/Effect/evaluate`))return Yr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=Yr(e)}}finally{this._running=n,globalThis[Un]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Jte;for(;;){let t=this._stack.pop();if(!t)return;let n=t[mr];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&Yte-1))return Wr(e);let t=this.getCont(fr);return t?t[fr](e,this):this.yieldWith(Wr(e))}yieldWith(e){return this._yielded=e,hr}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return Ot(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Zee(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=qte(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 qte=e=>{let t=sa(e,Xo);return{scheduler:la(e,bo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:la(e,ns),span:sa(e,Uo),logLevel:la(e,ss),minimumLogLevel:la(e,cs),stackFrame:la(e,ts),runtimeMetrics:sa(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:la(e,Do),preventYield:la(e,Oo)}},Jte={[fr](e,t){return Ls(t._interruptedCause)},[pr](e,t){return Ls(t._interruptedCause)}},Yte=32,As={interruptChildren:void 0},js=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(Kr.key,e.cache.stackFrame),$i(t)},Xte=e=>{if(e._children!==void 0&&e._children.size!==0)return Fs(e._children)},Zte=e=>{let t=e;return t._exit?Is(t._exit):qs(n=>t._exit?n(Is(t._exit)):zs(e.addObserver(e=>n(Is(e)))))},Ms=e=>qs(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(Is(r))}return a(),zs(()=>i?.())}),Ns=e=>{let t=e;return t._exit?t._exit:qs(n=>t._exit?n(t._exit):zs(e.addObserver(n)))},Ps=e=>Xr(t=>Qte(e,t.id)),Qte=/*#__PURE__*/ j(e=>N(e[0],Ts),(e,t,n)=>Xr(r=>{let i=js(r);return i=i&&n?pa(i,n):i??n,e.interruptUnsafe(t,i),dc(Zte(e))})),Fs=e=>Xr(t=>{let n=js(t),r=Ma();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return dc(Ms(r))}),Is=Wr,Ls=qr,Rs=Jr,zs=/*#__PURE__*/ Hr({op:`Sync`,[dr](e){let t=this[ur](),n=e.getCont(fr);return n?n[fr](t,e):e.yieldWith(Wr(t))}}),Bs=/*#__PURE__*/ Hr({op:`Suspend`,[dr](e){return this[ur]()}}),$te=/*#__PURE__*/ ate({onFailure:Rs,onSuccess:Is}),Vs=/*#__PURE__*/ (/* @__PURE__ */ Hr({op:`Yield`,[dr](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(yc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}}))(0),Hs=/*#__PURE__*/ Is(/*#__PURE__*/ Oi()),ene=e=>Bs(()=>Ls(e())),Us=e=>Yr(e),Ws=e=>Bs(()=>Rs(e())),Gs=/*#__PURE__*/ Is(void 0),tne=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new zu(e,`An error occurred in Effect.try`):e.catch;return Bs(()=>{try{return Is(t())}catch(e){return Rs(n(e))}})},nne=e=>Ks(function(t,n){e(n).then(e=>t(Is(e)),e=>t(Us(e)))},e.length!==0),rne=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new zu(e,`An error occurred in Effect.tryPromise`):e.catch;return Ks(function(e,r){let i=e=>Bs(()=>{try{return Rs(rr(()=>n(e)))}catch(e){return Us(e)}});try{t(r).then(t=>e(Is(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},ine=e=>Xr(t=>e(t.id)),Ks=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Vr({op:`Async`,[dr](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(ane(()=>(t=!0,r?.abort(),i??yc))),hr):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),ane=/*#__PURE__*/ Hr({op:`AsyncFinalizer`,[mr](e){e.interruptible&&(e.interruptible=!1,e._stack.push(Ol))},[pr](e,t){return gs(e)?pc(Kc(qr(e),this[ur]()),()=>Ls(e)):Ls(e)}}),qs=e=>Ks(e,e.length>=2),Js=/*#__PURE__*/ qs(Ft),one=(...e)=>{if(e.length===1){let t=e[0];return Bs(()=>ec(t()))}let[t,n]=e;return Bs(()=>ec(n.call(t.self)))},Ys=(e,...t)=>{let n=t.length===0?function(){return Bs(()=>ec(e.apply(this,arguments)))}:function(){let n=Bs(()=>ec(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Xs(e.length,n)},Xs=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Zs=/*#__PURE__*/ ds(2),sne=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=er(),i;return r!==0&&(tr(2),i=new globalThis.Error,tr(r)),e?(r,...a)=>Qs(t,r,i,a,e,n):Qs(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Qs=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Zs(()=>n.stack):Pt;return Xs(o.length,function(...t){let n=Bs(()=>{let e=o.apply(this,arguments);return vr(e)?e:ec(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!vr(n))return n;let l=er(),u;return l!==0&&(tr(2),u=new globalThis.Error,tr(l)),Sc(i?gu(e,a,e=>_u(n,e)):n,ts,t=>({name:e,stack:u?Zs(()=>u.stack):Pt,parent:{name:s,stack:c,parent:t}}))})},cne=(e,...t)=>Xs(e.length,t.length===0?function(){return $s(()=>e.apply(this,arguments))}:function(){let n=$s(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),$s=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return Is(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 Bs(()=>n?(n=!1,pc(r.value,e=>ec(t,e))):Bs(()=>ec(e())))}}}}catch(e){return Us(e)}},ec=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Vr({op:`Iterator`,[fr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return Is(r.value);if(!mc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[dr](e){return this[fr](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)}}(),tc=/*#__PURE__*/ j(2,(e,t)=>new rc(e,ic,Is(t))),nc=function(e){return e._stack.push(this),this[ur]},lne=/*#__PURE__*/ Vr({op:`OnSuccess`,[dr]:nc}),rc=function(e,t,n){this[ur]=e,this[fr]=t,this.payload=n};rc.prototype=lne;const ic=function(){return this.payload},ac=function(e,t){return t.succeedWith(this.payload)},oc=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ er();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return/* @__PURE__ */ Error()}};tr(1);let r=/*#__PURE__*/ n[t]();return tr(e),r.stack?.includes(`[as `+t+`]`)===!0})(),une=function(e,t){let n=this.payload;return t.succeedWith(oc?n(e):rr(()=>n(e)))},sc=function(e){let t=this.payload;return t(e)},dne=function(e){let t=this.payload;return new rc(t(e),ac,e)},fne=function(e){return new rc(this.payload,ac,e)},cc=e=>hc(e,ki),lc=/*#__PURE__*/ j(2,(e,t)=>new rc(e,vr(t)?ic:sc,t)),uc=/*#__PURE__*/ j(2,(e,t)=>new rc(e,vr(t)?fne:dne,t)),dc=e=>new rc(e,ic,yc),pne=(e,t)=>Xr(n=>{let r=/* @__PURE__ */ new Set;return pl(n,()=>r.size===0?void 0:Fs(r)),qs(i=>{let a=Da(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(Ls(kr(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=Gl(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),mne=(e,t)=>Xr(n=>{let r=/* @__PURE__ */ new Set;return pl(n,()=>r.size===0?void 0:Fs(r)),qs(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=Gl(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})})}})}),hne=/*#__PURE__*/ j(e=>vr(e[1]),(e,t,n)=>pne([e,t],n)),fc=/*#__PURE__*/ j(e=>vr(e[1]),(e,t,n)=>mne([e,t],n)),pc=/*#__PURE__*/ j(2,(e,t)=>new rc(e,sc,t)),gne=/*#__PURE__*/ j(2,(e,t)=>mc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):Pc(e,t)),mc=e=>e[sr]!==void 0,_ne=/*#__PURE__*/ j(2,(e,t)=>mc(e)?e._tag===`Success`?t(e.value):e:pc(e,t)),vne=e=>pc(e,M),hc=/*#__PURE__*/ j(2,(e,t)=>new rc(e,une,t)),yne=/*#__PURE__*/ j(2,(e,t)=>mc(e)?Tne(e,t):hc(e,t)),bne=/*#__PURE__*/ j(2,(e,t)=>mc(e)?Ene(e,t):Mc(e,t)),xne=/*#__PURE__*/ j(2,(e,t)=>mc(e)?Dne(e,t):Gne(e,t)),Sne=/*#__PURE__*/ j(2,(e,t)=>{if(mc(e)){if(e._tag===`Success`)return e;let n=ms(e.cause);return xa(n)?e:t(n.success)}return Ac(e,t)}),gc=e=>qr(ps(e)),_c=e=>e._tag===`Success`,Cne=e=>e._tag===`Failure`,wne=e=>e._tag===`Failure`?va(e.cause):ya(e),vc=e=>e._tag===`Failure`&&gs(e.cause),yc=/*#__PURE__*/ Wr(void 0),Tne=/*#__PURE__*/ j(2,(e,t)=>e._tag===`Success`?Wr(t(e.value)):e),Ene=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return e;let n=ms(e.cause);return xa(n)?e:Jr(t(n.success))}),Dne=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return Wr(t.onSuccess(e.value));let n=ms(e.cause);return xa(n)?e:Jr(t.onFailure(n.success))}),One=/*#__PURE__*/ j(2,(e,t)=>_c(e)?t:e),bc=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?yc:qr(kr(t))},kne=e=>e,Ane=e=>Xr(t=>Is(fa(t.context,e))),xc=/*#__PURE__*/ j(2,(e,t)=>Xr(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),pl(n,()=>{n.setContext(r)})),e})),Sc=/*#__PURE__*/ j(3,(e,t,n)=>xc(e,e=>{let r=ca(e,t),i=n(r);return r===i?e:ia(e,t,i)})),jne=()=>Mne,Mne=/*#__PURE__*/ Xr(e=>Is(e.context)),Cc=e=>Xr(t=>e(t.context)),Nne=/*#__PURE__*/ j(2,(e,t)=>xc(e,jt(t))),wc=/*#__PURE__*/ j(2,(e,t)=>mc(e)?e:xc(e,pa(t))),Tc=function(){return arguments.length===1?j(2,(e,t)=>Ec(e,arguments[0],t)):j(3,(e,t,n)=>Ec(e,t,n)).apply(this,arguments)},Ec=(e,t,n)=>xc(e,ia(t,n)),Pne=/*#__PURE__*/ j(2,(e,t)=>pc(t,t=>t?cc(e):Hs)),Fne=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>Il({while:Mt,body:jt(t?.disableYield?e:pc(e,e=>Vs)),step:Ft})),Dc=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,t.length===1?t:e=>t(e))),Ine=/*#__PURE__*/ Vr({op:`OnFailure`,[dr]:nc}),Oc=function(e,t){this[ur]=e,this[pr]=t};Oc.prototype=Ine;const Lne=/*#__PURE__*/ j(3,(e,t,n)=>Dc(e,e=>t(e)?n(e):Ls(e))),kc=/*#__PURE__*/ j(3,(e,t,n)=>Dc(e,e=>{let r=t(e);return xa(r)?Ls(r.failure):n(r.success,e)})),Ac=/*#__PURE__*/ j(2,(e,t)=>kc(e,ms,e=>t(e))),Rne=/*#__PURE__*/ j(2,(e,t)=>kc(e,Pte,t)),zne=/*#__PURE__*/ j(2,(e,t)=>Dc(e,e=>lc(t(e),Ls(e)))),Bne=/*#__PURE__*/ j(3,(e,t,n)=>Dc(e,e=>{let r=t(e);return xa(r)?Ls(e):lc(n(r.success,e),Ls(e))})),Vne=/*#__PURE__*/ j(2,(e,t)=>Bne(e,ms,e=>t(e))),jc=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n,r)=>Dc(e,e=>{let i=ms(e);return xa(i)?Ls(i.failure):t(i.success)?n(i.success):r?r(i.success):Ls(e)})),Hne=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n,r)=>Dc(e,e=>{let i=ms(e);if(xa(i))return Ls(i.failure);let a=t(i.success);return xa(a)?r?r(a.failure):Ls(e):n(a.success)})),Une=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>N(e,`_tag`)&&t.includes(e._tag):on(t);return jc(e,i,n,r)}),Wne=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n)=>{let r;return Hne(e,e=>(r??=Object.keys(t),N(e,`_tag`)&&Gt(e._tag)&&r.includes(e._tag)?va(e):ya(e)),e=>t[e._tag](e),n)}),Mc=/*#__PURE__*/ j(2,(e,t)=>Ac(e,e=>Ws(()=>t(e)))),Gne=/*#__PURE__*/ j(2,(e,t)=>Ic(e,{onFailure:e=>Ws(()=>t.onFailure(e)),onSuccess:e=>zs(()=>t.onSuccess(e))})),Kne=e=>Ac(e,Us),qne=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>{if(!t?.log)return Ic(e,{onFailure:e=>Gs,onSuccess:e=>Gs});let n=Yu(t.log===!0?void 0:t.log);return Pc(e,{onFailure(e){let r=Nte(e);return xa(r)?Ls(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Gs})}),Jne=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>{if(!t?.log)return Pc(e,{onFailure:e=>Gs,onSuccess:e=>Gs});let n=Yu(t.log===!0?void 0:t.log);return Pc(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>Gs})}),Yne=e=>Lc(e,{onFailure:Oi,onSuccess:ki}),Nc=e=>$ne(e,{onFailure:ya,onSuccess:va}),Pc=/*#__PURE__*/ j(2,(e,t)=>new Fc(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Xne=/*#__PURE__*/ Vr({op:`OnSuccessAndFailure`,[dr]:nc}),Fc=function(e,t,n){this[ur]=e,this[fr]=t,this[pr]=n};Fc.prototype=Xne;const Zne=function(e,t){let n=this.payload;return t.succeedWith(oc?n.onSuccess(e):rr(()=>n.onSuccess(e)))},Qne=/*#__PURE__*/ ((e,t)=>{let n=Vr({op:e,[dr]:nc,[fr]:Zne,[pr]:t}),r=function(e,t){this[ur]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=e.reasons.find(Rr);if(n===void 0)return Ls(e);let r=this.payload;return t.succeedWith(oc?r.onFailure(n.error):rr(()=>r.onFailure(n.error)))}),Ic=/*#__PURE__*/ j(2,(e,t)=>Pc(e,{onFailure:e=>{let n=e.reasons.find(Rr);return n?t.onFailure(n.error):Ls(e)},onSuccess:t.onSuccess})),Lc=/*#__PURE__*/ j(2,(e,t)=>new Qne(e,t)),$ne=/*#__PURE__*/ j(2,(e,t)=>{if(mc(e)){if(e._tag===`Success`)return Wr(t.onSuccess(e.value));let n=ms(e.cause);return xa(n)?e:Wr(t.onFailure(n.success))}return Lc(e,t)}),Rc=e=>mc(e)?Wr(e):ere(e),ere=/*#__PURE__*/ Hr({op:`Exit`,[dr](e){return e._stack.push(this),this[ur]},[fr](e,t,n){return t.succeedWith(n??Wr(e))},[pr](e,t,n){return t.succeedWith(n??qr(e))}}),tre=/*#__PURE__*/ j(2,(e,t)=>lc(Ou(t),e)),zc=/*#__PURE__*/ j(2,(e,t)=>pc(ire(e,t.duration),e=>Ai(e)?t.orElse():Is(e.value))),nre=e=>new ju(`Operation timed out after '${yo(e)}'`),rre=/*#__PURE__*/ j(2,(e,t)=>{let n=Ka(t);return zc(e,{duration:n,orElse:()=>Rs(nre(n))})}),ire=/*#__PURE__*/ j(2,(e,t)=>fc(cc(e),tc(Ou(t),Oi()))),Bc=`~effect/Scope`,Vc=`~effect/Scope/Closeable`,Hc=/*#__PURE__*/ P(`effect/Scope`),Uc=(e,t)=>Xr(n=>(jl(n),Wc(e,t)??Gs)),Wc=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&$c(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Gc(n.finalizer,t);let r=n.finalizers;return r.size===1?Gc(r.values().next().value,t):qc(e,r,t)},Gc=(e,t)=>{try{return e(t)}catch(e){return Yr(e)}},Kc=(e,t)=>_c(e)?t:Dc(t,t=>Ls(jr(e.cause,t))),qc=/*#__PURE__*/ Ys(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Os();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*Rc(Gc(s,n))):i.push(Gl(o,Gc(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Ms(i)),yield*bc(r)}),Jc=(e,t)=>zs(()=>Yc(e,t)),Yc=(e,t)=>{let n=tl(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Qc(e,n,e=>Uc(n,e)),n)},Xc=(e,t)=>Bs(()=>e.state._tag===`Closed`?t(e.state.exit):(Qc(e,{},t),Gs)),Zc=(e,t)=>Xc(e,jt(t)),Qc=(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)}},$c=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=nl:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=nl))},el=e=>tl(e,void 0),tl=(e=`sequential`,t)=>({[Vc]:Vc,[Bc]:Bc,strategy:e,parent:t,state:nl}),nl={_tag:`Empty`},rl=e=>zs(()=>el(e)),il=Hc,al=/*#__PURE__*/ Tc(Hc),ol=e=>Xr(t=>{let n=t.context,r=el();return t.setContext(ia(t.context,Hc,r)),pl(t,e=>(t.setContext(n),Wc(r,e))),e}),sl=/*#__PURE__*/ j(2,(e,t)=>ml(al(e,t),e=>Bs(()=>Wc(t,e)??Gs))),cl=e=>Bs(()=>{let t=el();return ml(e(t),e=>Bs(()=>Wc(t,e)??Gs))}),ll=(e,t,n)=>Cc(r=>Pl(i=>pc(il,a=>uc(n?.interruptible?i(e):e,e=>Xc(a,n=>wc(t(e,n),r)))))),ul=e=>pc(il,t=>Cc(n=>Xc(t,t=>wc(e(t),n)))),dl=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Vr({op:`OnExit`,[dr](e){return e._stack.push(this),this.effect},[mr](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(Ol),e.interruptible=!1)},[fr](e,t,n){n??=Wr(e);let r;try{r=this.onExit(n)}catch(e){r=Yr(e)}return r?pc(r,e=>n):n},[pr](e,t,n){n??=qr(e);let r;try{r=this.onExit(n)}catch(e){r=Yr(e)}return r?pc(Kc(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),fl=(e,t,n)=>new dl(e,t,n),pl=(e,t)=>{e._stack.push(new dl(void 0,t,void 0))},ml=/*#__PURE__*/ j(2,fl),hl=/*#__PURE__*/ j(2,(e,t)=>ml(e,e=>t)),gl=/*#__PURE__*/ j(3,(e,t,n)=>ml(e,e=>{let r=t(e);return xa(r)?Gs:n(r.success,e)})),_l=/*#__PURE__*/ j(2,(e,t)=>gl(e,wne,t)),vl=/*#__PURE__*/ j(3,(e,t,n)=>ml(e,e=>{if(e._tag!==`Failure`)return Gs;let r=t(e.cause);return xa(r)?Gs:n(r.success,e.cause)})),yl=/*#__PURE__*/ j(2,(e,t)=>vl(_s,t)(e)),bl=/*#__PURE__*/ j(2,(e,t)=>zs(()=>Sl(e,typeof t==`function`?e=>uo(Ka(t(e))):jt(uo(Ka(t)))))),xl=/*#__PURE__*/ jt(1/0),Sl=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,pl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,Ps(t.fiber)}),Ns(t.fiber));return[Xr(o=>{if(i!==void 0)return o===i.fiber?Ns(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(xu).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(xu),c={fiber:new ks(o.context),awaiters:0};i=c;let l=a(o,c);return c.fiber.evaluate(fl(e,e=>{if(i!==c||(i=void 0,vc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),zs(()=>{r=void 0})]},Cl=/*#__PURE__*/ j(2,(e,t)=>hc(bl(e,t),e=>e[0])),wl=e=>zs(()=>Sl(e,xl)[0]),Tl=/*#__PURE__*/ Xr(e=>Ls(ps(e.id))),El=e=>Xr(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(Ol)),e)),Dl=/*#__PURE__*/ Hr({op:`SetInterruptible`,[mr](e){if(e.interruptible=this[ur],e._interruptedCause&&e.interruptible)return()=>Ls(e._interruptedCause)}}),Ol=/*#__PURE__*/ Dl(!0),kl=/*#__PURE__*/ Dl(!1),Al=e=>{if(e.interruptible=!0,e._stack.push(kl),e._interruptedCause)return Ls(e._interruptedCause)},jl=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(Ol))},Ml=e=>{let t=e;if(!t.interruptible)return Al(t)},Nl=e=>Xr(t=>t.interruptible?e:Al(t)??e),Pl=e=>Xr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(Ol),e(Nl)):e(M)),Fl=(e,t)=>xee(e)?t?.mode===`result`?Ll(e,Nc,t):Ll(e,M,t):t?.discard?t.mode===`result`?Ll(Object.values(e),Nc,t):Ll(Object.values(e),M,t):Bs(()=>{let n={};return tc(Ll(Object.entries(e),([e,r])=>hc(t?.mode===`result`?Nc(r):r,t=>{ir(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),Il=/*#__PURE__*/ Hr({op:`While`,[fr](e,t){return this[ur].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[ur].body()):yc},[dr](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[ur].body()):yc}}),Ll=/*#__PURE__*/ j(e=>typeof e[1]==`function`,(e,t,n)=>Bs(()=>{let r=zl(n?.concurrency);if(r===1)return Rl(e,t,n);let i=Da(e),a=i.length;if(a===0)return n?.discard?Gs:Is([]);let o=n?.discard?void 0:Array(a),s=Ul({f:t,out:o},i,{concurrency:r});return s?tc(s,o):Is(o)})),Rl=(e,t,n)=>Bs(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return tc(Il({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),zl=e=>e===`unbounded`?1/0:Math.max(1,e??1),Bl=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>pc(Rc(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Gs),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!mc(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},Vl=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=Yr(e);return f=t,c=!0,u&&u.size>0?pc(El(Fs(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(mc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=Gl(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=kr(e);f=qr(f._tag===`Failure`?jr(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??Gs)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return qs(e=>{l=Os(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Bs(()=>(f??=yc,pc(u?Fs(u):Gs,()=>f?._tag===`Failure`?f:Gs)))})}if(c=!0,f){if(u&&u.size>0){let e=js(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(Gs);else return yc}};return h()}},Hl=()=>e=>Vl(e),Ul=/*#__PURE__*/ Vl({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)}}),Wl=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>Xr(n=>(ed(),Is(Gl(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),Gl=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new ks(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Ds(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},Kl=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n)=>Xr(r=>{let i=Gl(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};Qc(t,e,()=>ine(e=>e===i.id?Gs:Ps(i))),i.addObserver(()=>$c(t,e))}else i.interruptUnsafe(r.id,js(r))}return Is(i)})),ql=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>pc(il,n=>Kl(e,n,t))),Jl=e=>(t,n)=>{let r=new ks(n?.scheduler?ia(e,bo,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},Yl=/*#__PURE__*/ j(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):($c(t,e),Qc(t,e,()=>Ps(e)),e.addObserver(()=>$c(t,e)),e)),Xl=/*#__PURE__*/ Jl(/*#__PURE__*/ na()),Zl=e=>{let t=Jl(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},Ql=e=>{let t=Zl(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw vs(e.cause);return e.value})},$l=/*#__PURE__*/ Ql(/*#__PURE__*/ na()),eu=e=>{let t=Jl(e);return e=>{if(mc(e))return e;let n=new To(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Yr(new Lu(r))}},tu=/*#__PURE__*/ eu(/*#__PURE__*/ na()),nu=/*#__PURE__*/ (e=>{let t=eu(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw vs(n.cause);return n.value}})(/*#__PURE__*/ na()),ru=/*#__PURE__*/ Is(!0),iu=/*#__PURE__*/ Is(!1);var au=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return ru;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=[],ru}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](yc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](yc)}open=/*#__PURE__*/ Xr(e=>this._isOpen?iu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ Xr(e=>this._isOpen?iu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ qs(e=>this._isOpen?e(Gs):(this.waiters.push(e),zs(()=>{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__*/ zs(()=>this.closeUnsafe());whenOpen=e=>pc(this.await,()=>e);isOpen(){return this._isOpen}};const ou=e=>new au(e??!1),su=e=>zs(()=>ou(e)),cu=/*#__PURE__*/ BigInt(0),lu={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:cu,endTime:cu,exit:yc},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},uu=e=>Object.assign(Object.create(lu),e),du=e=>e?la(e.annotations,qo)?e._tag===`Span`?du(Li(e.parent)):Oi():ki(e):Oi(),fu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&la(n.annotations,qo),i=n?.parent===void 0?n?.root?Oi():du(e.cache.span):ki(n.parent),a;if(r)a=uu({name:t,parent:i,annotations:ia(n?.annotations??na(),qo,!0)});else{let r=e.cache.tracer??Qo,o=e.getRef(xu),s=e.getRef(rs),c=e.getRef(is),l=e.getRef(as),u=n?.level??e.getRef(Jo),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??na(),links:d,startTime:s?o.currentTimeNanosUnsafe():cu,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(ji(i)&&i.value.sampled===!1?!1:!Hu(e.getRef(Yo),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},pu=(e,t)=>El(Xr(n=>{let r=ca(n.context,Hc),i=fu(n,e,t??{}),a=n.getRef(xu),o=n.getRef(rs);return tc(Xc(r,e=>hu(i,e,a,o)),i)})),mu=(e,t)=>(t=typeof t==`function`?t:Pt,Sc(ts,n=>({name:e,stack:t,parent:n}))),hu=(e,t,n,r)=>zs(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():cu,t)}),gu=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return Xr(t=>{let i=fu(t,e,n),a=t.getRef(xu),o=t.getRef(rs);return pl(t,e=>hu(i,e,a,o)),r(i)})},_u=/*#__PURE__*/ Tc(Wo),vu=function(){let e=vr(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=M;return t._tag===`Span`&&(n=us(n),r=mu(t.name,n?.captureStackTrace)),e?_u(r(arguments[0]),t):e=>_u(r(e),t)},yu=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=us(arguments[2]);if(e){let e=arguments[0];return gu(t,arguments[2],t=>vu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>gu(t,r?r(...a):i,t=>vu(e,t,n))},bu=(...e)=>Xr(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 Gs}),xu=/*#__PURE__*/ ha(`effect/Clock`,{defaultValue:()=>new Cu}),Su=2**31-1;var Cu=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ zs(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Eu()}currentTimeNanos=/*#__PURE__*/ zs(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return Tu()}monotonicTimeNanos=/*#__PURE__*/ zs(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(uo(e))}sleepMillis(e){return e<=0?Vs:Number.isFinite(e)?qs(t=>{let n=e>Su?this.sleepMillis(e-Su):Gs,r=setTimeout(()=>t(n),Math.min(e,Su));return zs(()=>clearTimeout(r))}):Js}};const wu=/*#__PURE__*/ BigInt(1e6),Tu=/*#__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())*wu;return e>t&&(t=e),t}}(),Eu=/*#__PURE__*/ function(){let e=/*#__PURE__*/ BigInt(1e9),t;return()=>{let n=Tu(),r=BigInt(Date.now())*wu;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}}(),Du=e=>Xr(t=>e(t.getRef(xu))),Ou=e=>Du(t=>t.sleep(Ka(e))),ku=/*#__PURE__*/ Du(e=>e.currentTimeMillis),Au=`~effect/Cause/TimeoutError`;var ju=class extends (/*#__PURE__*/ Qr(`TimeoutError`)){[Au]=Au;constructor(e){super({message:e})}};const Mu=`~effect/Cause/IllegalArgumentError`;var Nu=class extends (/*#__PURE__*/ Qr(`IllegalArgumentError`)){[Mu]=Mu;constructor(e){super({message:e})}};const Pu=`~effect/Cause/ExceededCapacityError`;var Fu=class extends (/*#__PURE__*/ Qr(`ExceededCapacityError`)){[Pu]=Pu;constructor(e){super({message:e})}};const Iu=`~effect/Cause/AsyncFiberError`;var Lu=class extends (/*#__PURE__*/ Qr(`AsyncFiberError`)){[Iu]=Iu;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const Ru=`~effect/Cause/UnknownError`;var zu=class extends (/*#__PURE__*/ Qr(`UnknownError`)){[Ru]=Ru;constructor(e,t){super({message:t,cause:e})}};const Bu=/*#__PURE__*/ ha(`effect/Console`,{defaultValue:()=>globalThis.console}),Vu=/*#__PURE__*/ Ci(Si,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}}),Hu=/*#__PURE__*/ Ti(Vu),Uu=/*#__PURE__*/ ha(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([Qu,$u])}),Wu=/*#__PURE__*/ ha(`effect/Logger/LogToStderr`,{defaultValue:Nt}),Gu={"~effect/Logger":{_Message:M,_Output:M},pipe(){return Ot(this,arguments)}},Ku=e=>{let t=Object.create(Gu);return t.log=e,t},qu=e=>e.replace(/[\s="]/g,`_`),Ju=(e,t)=>`${qu(e[0])}=${t-e[1]}ms`,Yu=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Sr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?kr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Nr),Xr(r=>{let i=e??r.cache.logLevel;if(Hu(r.cache.minimumLogLevel,i))return Gs;let a=r.getRef(xu),o=r.getRef(Uu);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 Gs})},Xu={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};Xu.gray,Xu.blue,Xu.green,Xu.yellow,Xu.red,Xu.bgBrightRed,Xu.black;const Zu=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`)}`,Qu=/*#__PURE__*/ Ku(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Ss(e));let o=t.getTime(),s=n.getRef(ls),c=``;for(let e of s)c+=` ${Ju(e,o)}`;let l=n.getRef(os);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Bu);(n.getRef(Wu)?u.error:u.log)(`[${Zu(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),$u=/*#__PURE__*/ Ku(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(xu),a=t.getRef(os),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))ir(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Ss(e)),o.event(Mee(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function ed(){As.interruptChildren??=Xte}const td=/*#__PURE__*/ j(e=>vr(e[0]),(e,t)=>_l(e,e=>Xr(n=>(nd(n,e,t?.defectsOnly),Gs)))),nd=(e,t,n)=>{let r=e.getRef(es);if(r.size===0||n&&!hs(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(xu).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},rd=Sr,id=Cr,ad=Rr,od=zr,sd=kr,cd=Pr,ld=Ir,ud=e=>new Or(e),dd=e=>new Fr(e),are=Mte,ore=Lte,fd=zte,sre=jr,pd=vs,cre=ms,md=hs,hd=gs,lre=Fte,ure=Ss,dre=Iee,gd=Lee,_d=ti,vd=zee,yd=Nu,fre=Fu,pre=zu,bd=Rte;var xd=class extends (/*#__PURE__*/ P()(`effect/Cause/StackTrace`)){};const Sd=yr,Cd=Wr,wd=qr,Td=Jr,Ed=Yr,Dd=gc,Od=yc,kd=_c,Ad=Cne,mre=vc,hre=bc,jd=`~effect/Deferred`,gre=e=>N(e,jd),_re={[jd]:{_A:M,_E:M},pipe(){return Ot(this,arguments)}},Md=function(){this.resumes=void 0,this.effect=void 0};Md.prototype=_re;const Nd=()=>new Md,Pd=()=>zs(()=>Nd()),Fd=e=>qs(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),zs(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),Id=/* @__PURE__ */ j(2,(e,t)=>zs(()=>Bd(e,t))),vre=/*#__PURE__*/ j(2,(e,t)=>Id(e,qr(t))),yre=/*#__PURE__*/ j(2,(e,t)=>vre(e,ps(t))),Ld=e=>zs(()=>Rd(e)),Rd=e=>e.effect!==void 0,zd=/*#__PURE__*/ j(2,(e,t)=>Id(e,Wr(t))),Bd=(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},bre=os,Vd=ss,xre=rs,Hd=Hc,Sre=rl,Ud=el,Wd=al,Gd=Xc,Kd=Zc,qd=Jc,Jd=Yc,Yd=Uc,Xd=Wc,Cre=sl,Zd=`~effect/Layer/MemoMap`,wre=(e,t)=>{let n={observers:0,deferred:Nd(),scope:Ud(),finalizer:r=>Bs(()=>--n.observers>0?Gs:(e.map.delete(t),Yd(n.scope,r)))};return n},Qd=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Qc(t,{},e.finalizer),!0),Tre={"~effect/Layer":{_ROut:M,_E:M,_RIn:M},pipe(){return Ot(this,arguments)}},$d=e=>{let t=Object.create(Tre);return t.build=e,t},ef=e=>$d((t,n)=>{let r=Jd(n);return ml(e(t,r),e=>e._tag===`Failure`?Yd(r,e):Gs)}),Ere=e=>{let t=ef((n,r)=>n.getOrElseMemoize(t,r,e));return t};var tf=class{get[Zd](){return Zd}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(Qd(n,t),n.deferred.effect??Fd(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Bs(()=>{let r;return fl(Bs(()=>{let i=this.get(e,t);if(i)return i;let a=wre(this,e);return Qd(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&Bd(r,e)})})}};const nf=()=>new tf,Dre=e=>new tf(e);var rf=class e extends (/*#__PURE__*/ P()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=oa(t,e);return n?Dre(n):nf()}};const af=/*#__PURE__*/ j(3,(e,t,n)=>Tc(hc(Bs(()=>e.build(t,n)),ia(rf,t)),rf,t)),Ore=e=>Xr(t=>af(e,rf.forkOrCreate(t.context),ca(t.context,Hd))),kre=/*#__PURE__*/ j(2,(e,t)=>Xr(n=>af(e,rf.forkOrCreate(n.context),t))),of=function(){return arguments.length===1?e=>sf(ra(arguments[0],e)):sf(ra(arguments[0],arguments[1]))},sf=e=>$d(jt(Is(e))),cf=/*#__PURE__*/ sf(/*#__PURE__*/ na()),lf=function(){return arguments.length===1?e=>uf(arguments[0],e):uf(arguments[0],arguments[1])},uf=(e,t)=>df(hc(t,t=>ra(e,t))),df=e=>Ere((t,n)=>Wd(e,n)),ff=e=>df(tc(e,na())),pf=/*#__PURE__*/ P(`effect/Layer/unwrap`),mf=e=>Are(lf(pf)(e),la(pf)),hf=(e,t,n)=>{let r=Jd(n,`parallel`);return Ll(e,e=>e.build(t,Jd(r,`sequential`)),{concurrency:e.length}).pipe(hc(e=>nte(...e)))},gf=(...e)=>ef((t,n)=>hf(e,t,n)),_f=/*#__PURE__*/ j(2,(e,t)=>gf(e,...Array.isArray(t)?t:[t])),vf=(e,t,n)=>ef((r,i)=>pc(Array.isArray(t)?hf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(wc(t),hc(e=>n(e,t))))),yf=/*#__PURE__*/ j(2,(e,t)=>vf(e,t,M)),bf=/*#__PURE__*/ j(2,(e,t)=>vf(e,t,(e,t)=>pa(t,e))),Are=/*#__PURE__*/ j(2,(e,t)=>ef((n,r)=>pc(e.build(n,r),e=>t(e).build(n,r)))),jre=e=>$d((t,n)=>e.build(nf(),n)),xf=xu,Sf=ku,Cf=`~effect/DateTime`,wf=`~effect/DateTime/TimeZone`,Tf={[Cf]:Cf,pipe(){return Ot(this,arguments)},[Xn](){return this.toString()},toJSON(){return jf(this).toJSON()}},Mre={...Tf,_tag:`Utc`,[sn](){return mn(this.epochMilliseconds)},[En](e){return Df(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${jf(this).toJSON()})`}};({...Tf});const Ef={[wf]:wf,[Xn](){return this.toString()}};({...Ef}),{...Ef};const Df=e=>N(e,Cf),Nre=e=>e._tag===`Utc`,Of=e=>{let t=Object.create(Mre);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},kf=e=>{let t=e.getTime();if(Number.isNaN(t))throw new yd(`Invalid date`);return Of(t)},Af=e=>{if(Df(e))return e;if(e instanceof Date)return kf(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return kf(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return Rre(t,e),kf(t)}return typeof e==`string`&&!Pre(e)?kf(/* @__PURE__ */ new Date(e+`Z`)):kf(new Date(e))},Pre=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Fre=/*#__PURE__*/ Ri(Af),Ire=e=>Of(e.epochMilliseconds),jf=e=>new Date(e.epochMilliseconds),Lre=e=>e.epochMilliseconds,Rre=(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)},zre=e=>jf(e).toISOString();globalThis.String;const Bre=e=>e.trim(),Vre=(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)},Mf=/*#__PURE__*/ j(2,(e,t)=>kc(e,Hre,e=>t(e))),Nf=e=>e.reasons.some(Pf),Pf=e=>e._tag===`Fail`&&gd(e.error),Ff=e=>{let t,n=!1;for(let r of e.reasons)Pf(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?ya(e):n?ya(sd(e.reasons.filter(e=>!Pf(e)))):va(t)},Hre=e=>{let t=Ff(e);return xa(t)?t:va(t.success.value)},If=e=>{let t=Ff(e);return xa(t)?wd(t.failure):Cd(t.success.value)},Ure=/*#__PURE__*/ j(2,(e,t)=>Pc(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Ff(e);return xa(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Wre=(e,t,n)=>cl(r=>pc(n?.local?af(t,nf(),r):kre(t,r),t=>wc(e,t))),Gre=/*#__PURE__*/ j(e=>vr(e[0]),(e,t,n)=>ea(t)?wc(e,t):Wre(e,Array.isArray(t)?gf(...t):t,n)),Lf=`~effect/MutableHashMap`,Kre={[Lf]:Lf,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${Gn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:Zn(Array.from(this))}},[Xn](){return this.toJSON()},pipe(){return Ot(this,arguments)}},qre=()=>{let e=Object.create(Kre);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},Rf=/*#__PURE__*/ j(2,(e,t)=>{if(e.backing.has(t))return ki(e.backing.get(t));if(zf(t))return Oi();let n=cn(t),r=e.buckets.get(n);return r===void 0?Oi():Jre(e,r,t)}),zf=e=>typeof e!=`object`&&typeof e!=`function`,Jre=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(Dn(n,t[r])){let n=t[r];return ki(e.backing.get(n))}return Oi()},Yre=/*#__PURE__*/ j(3,(e,t,n)=>{if(e.backing.has(t)||zf(t))return e.backing.set(t,n),e;let r=cn(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Xre(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Xre=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Dn(t,e[n]))return e[n]},Bf=/*#__PURE__*/ j(2,(e,t)=>{if(zf(t))return e.backing.delete(t),e;let n=cn(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||Dn(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Zre=e=>(e.backing.clear(),e.buckets.clear(),e),Qre=e=>e.backing.size,Vf=vr,Hf=Fl,Uf=Ll,Wf=Il,Gf=nne,Kf=rne,F=Is,qf=Hs,Jf=Bs,I=zs,L=Gs,Yf=qs,Xf=Js,R=one,z=Rs,Zf=Ls,Qf=ene,$f=Us,ep=tne,$re=Vs,tp=Xr,np=$te,B=pc,eie=vne,rp=lc,ip=uc,ap=Nc,tie=Yne,op=Rc,V=hc,sp=tc,cp=dc,lp=Ac,up=Une,nie=Wne,dp=Dc,fp=Rne,pp=jc,rie=Lne,mp=Mc,hp=Kne,gp=Vne,_p=zne,vp=qne,yp=Jne,iie=td,aie=rre,bp=zc,oie=tre,xp=Ou,sie=hne,Sp=fc,cie=Pne,Cp=Lc,lie=gne,wp=Pc,Tp=Ic,Ep=jne,Dp=Cc,Op=Gre,kp=wc,uie=Nne,Ap=kne,jp=Ane,Mp=xc,Np=Tc,Pp=il,Fp=ol,die=cl,Ip=ll,Lp=ul,Rp=hl,zp=_l,Bp=fl,Vp=ml,Hp=wl,Up=Cl,Wp=Tl,Gp=Nl,Kp=yl,qp=El,Jp=Pl,Yp=Fne,fie=bu,pie=pu,Xp=gu,Zp=yu,Qp=vu,$p=Wl,em=Kl,tm=ql,nm=Xl,rm=Jl,im=$l,mie=Ql,am=nu,om=tu,H=Ys,sm=sne,cm=Du,lm=/*#__PURE__*/ Yu(`Fatal`),um=/*#__PURE__*/ Yu(`Warn`),dm=/*#__PURE__*/ Yu(`Error`),fm=/*#__PURE__*/ Yu(`Info`),pm=/*#__PURE__*/ Yu(`Debug`),mm=/*#__PURE__*/ j(e=>Vf(e[0]),(e,...t)=>Sc(e,bre,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||ir(n,t[0],t[1]),n})),hm=(e,t,n)=>(...r)=>Yf(i=>{try{e(...r,(e,n)=>{i(e?t?Jf(()=>z(t(e,r))):z(e):F(n))})}catch(e){i(n?z(n(e,r)):$f(e))}}),gm=yne,_m=bne,vm=xne,ym=_ne,bm=Sne,xm=cne,Sm=`~effect/BigDecimal`,Cm={[Sm]:Sm,[sn](){let e=jm(this);return dn(hn(String(e.value)),mn(e.scale))},[En](e){return wm(e)&&Fm(this,e)===0},toString(){return`BigDecimal(${Lm(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Xn](){return this.toJSON()},pipe(){return Ot(this,arguments)}},wm=e=>N(e,Sm),Tm=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(Cm);return n.value=e,n.scale=t,n},Em=(e,t)=>{let n=Tm(e,t);return n.normalized=n,n},Dm=/*#__PURE__*/ BigInt(0),Om=/*#__PURE__*/ BigInt(1),km=/*#__PURE__*/ BigInt(10),Am=/*#__PURE__*/ Em(Dm,0),jm=e=>{if(e.normalized===void 0){if(e.value===Dm)e.normalized=Am;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=Em(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Mm=[Om],Nm=(e,t)=>e===t?0:e<t?-1:1,Pm=(e,t)=>{let n=`${e.value<Dm?-e.value:e.value}`,r=`${t.value<Dm?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Dm)return i<Dm?-1:1;let a=Math.max(n.length,r.length);return xi(n.padEnd(a,`0`),r.padEnd(a,`0`))},Fm=(e,t)=>{if(e.scale===t.scale)return Nm(e.value,t.value);let n=Im(e),r=Im(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?Pm(t,e):Pm(e,t);let o=Mm[a]??=km**BigInt(a);return i>0?Nm(e.value,t.value*o):Nm(e.value*o,t.value)},Im=e=>e.value===Dm?0:e.value<Dm?-1:1,Lm=e=>{let t=jm(e);if(Math.abs(t.scale)>=16)return Rm(t);let n=t.value<Dm,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},Rm=e=>{if(zm(e))return`0e+0`;let t=jm(e),n=`${t.value}`,r=t.value<Dm?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},zm=e=>e.value===Dm,Bm=globalThis.BigInt,Vm=e=>e>Bm(2**53-1)||e<Bm(-(2**53-1))?Oi():ki(Number(e)),Hm=/*#__PURE__*/ BigInt(0),Um=/*#__PURE__*/ BigInt(1),Wm=/*#__PURE__*/ BigInt(1e3),Gm=/*#__PURE__*/ BigInt(1024),Km=[{symbol:`B`,factor:Um,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Wm,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Wm**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Wm**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Wm**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Wm**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Wm**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Wm**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Wm**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Wm**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Wm**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],qm=[Km[0],{symbol:`KiB`,factor:Gm,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:Gm**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:Gm**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:Gm**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:Gm**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:Gm**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:Gm**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:Gm**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],Jm=[...Km,.../*#__PURE__*/ qm.slice(1)],Ym=/*#__PURE__*/ new Map(/*#__PURE__*/ Jm.flatMap(e=>e.names.map(t=>[t,e]))),Xm=/*#__PURE__*/ new Map(/*#__PURE__*/ Jm.map(e=>[e.symbol,e])),Zm=e=>e,Qm=/*#__PURE__*/ Zm(Hm),$m=e=>{throw Error(`Invalid ByteSize: ${e}`)},eh=e=>!Number.isSafeInteger(e)||e<0?$m(`expected a non-negative safe integer, received ${e}`):Zm(BigInt(e)),th=(e,t)=>{if(typeof e==`bigint`)return e<Hm?$m(`expected a non-negative quantity, received ${e}`):Zm(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?$m(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):Zm(BigInt(n))},nh=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return $m(`unsupported syntax ${JSON.stringify(e)}`);let n=Ym.get(t[3]);if(n===void 0)return $m(`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===Hm?Zm(a/i):$m(`${JSON.stringify(e)} does not represent an integral number of bytes`)},rh=e=>{switch(typeof e){case`bigint`:return e<Hm?$m(`expected a non-negative bigint, received ${e}`):Zm(e);case`number`:return eh(e);case`string`:return nh(e)}return $m(`unsupported input ${e}`)},ih=/*#__PURE__*/ Ri(rh),ah=e=>typeof e==`bigint`?rh(e):eh(e),oh=/*#__PURE__*/ (e=>t=>th(t,Xm.get(e)))(`MiB`),sh=Df,ch=Nre,lh=kf,uh=Af,dh=Fre,fh=Ire,ph=Lre,mh=zre,hh=e=>vh(typeof e==`string`?yh.encode(e):e),gh=e=>{let t=xh(e),n=t.length;if(n%4!=0)return ya(new Io({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 ya(new Io({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=wh(t.charCodeAt(e))<<18|wh(t.charCodeAt(e+1))<<12|wh(t.charCodeAt(e+2))<<6|wh(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return va(r)}catch(e){return ya(new Io({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},_h=e=>Ca(gh(e),e=>bh.decode(e)),vh=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Sh[e[r-2]>>2],n+=Sh[(e[r-2]&3)<<4|e[r-1]>>4],n+=Sh[(e[r-1]&15)<<2|e[r]>>6],n+=Sh[e[r]&63];return r===t+1&&(n+=Sh[e[r-2]>>2],n+=Sh[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Sh[e[r-2]>>2],n+=Sh[(e[r-2]&3)<<4|e[r-1]>>4],n+=Sh[(e[r-1]&15)<<2],n+=`=`),n},yh=/*#__PURE__*/ new TextEncoder,bh=/*#__PURE__*/ new TextDecoder,xh=e=>e.replace(/[\n\r]/g,``),Sh=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ch=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)Ch[/*#__PURE__*/ Sh.charCodeAt(e)]=e;Ch[61]=0;const wh=e=>{if(e>=Ch.length||Ch[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Ch[e]},Th=`~effect/http/Cookies`,Eh=e=>N(e,Th),Dh=`~effect/http/Cookies/Cookie`,Oh=`~effect/http/Cookies/CookieError`;var kh=class extends No{},Ah=class e extends (/*#__PURE__*/ Po(`CookiesError`)){static fromReason(t,n){return new e({reason:new kh({_tag:t,cause:n})})}[Oh]=Oh;get message(){return this.reason._tag}};const jh={[Th]:Th,...Qn,toJSON(){return{_id:`effect/Cookies`,cookies:wa(this.cookies,e=>e.toJSON())}},pipe(){return Ot(this,arguments)}},Mh=e=>{let t=Object.create(jh);return t.cookies=e,t},Nh=e=>{let t={};for(let n of e)ir(t,n.name,n);return Mh(t)},Ph=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=Fh(e.trim());t&&n.push(t)}return Nh(n)};function Fh(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!zh.test(r))return;let i=t[0].slice(n+1),a=Qh(i);if(t.length===1)return Object.assign(Object.create(Hh),{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=ao(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(Hh),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const Ih=/*#__PURE__*/ Nh([]),Lh=e=>ute(e.cookies),Rh=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,zh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Bh=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,Vh=/^[\u0020-\u003a\u003c-\u007e]+$/,Hh={[Dh]:Dh,...Qn,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function Uh(e,t,n){let r=encodeURIComponent(t),i=Wh(e,r,n);return i===void 0?va(Object.assign(Object.create(Hh),{name:e,value:t,valueEncoded:r,options:n})):ya(i)}function Wh(e,t,n){if(!zh.test(e))return Ah.fromReason(`InvalidCookieName`);if(t&&!Rh.test(t))return Ah.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!Bh.test(n.domain))return Ah.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!Vh.test(n.path))return Ah.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!Xa(Ka(n.maxAge)))return Ah.fromReason(`CookieInfinityMaxAge`)}const Gh=/*#__PURE__*/ j(2,(e,t)=>Mh({...e.cookies,...t.cookies})),Kh=/*#__PURE__*/ j(e=>Eh(e[0]),(e,t,n,r)=>Ca(Uh(t,n,r),n=>Mh(pte(e.cookies,t,n))));function qh(e){let t=Wh(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=fo(Ka(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 Jh=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),Yh=e=>{let t={},n=Object.values(e.cookies);for(let e=0;e<n.length;e++){let r=n[e];ir(t,r.name,r.value)}return t},Xh=e=>Object.values(e.cookies).map(qh);function Zh(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();ir(t,o,n.indexOf(`%`)===-1?n:Qh(n))}r=i+1}return t}const Qh=e=>{try{return decodeURIComponent(e)}catch{return e}},$h=/*#__PURE__*/ new WeakMap,eg=e=>{if($h.has(e))return $h.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},tg=`~effect/Redacted`,ng=e=>N(e,tg),rg=(e,t)=>{let n=Object.create(ig);return t?.label&&(n.label=t.label),$h.set(n,e),n},ig={[tg]:{_A:e=>e},label:void 0,...gr,toJSON(){return this.toString()},toString(){return`<redacted${Gt(this.label)?`:`+this.label:``}>`},[sn](){return cn($h.get(this))},[En](e){return ng(e)&&Dn($h.get(this),$h.get(e))}},ag=eg,og=e=>ri((t,n)=>e(ag(t),ag(n))),sg=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),cg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[sg]:{value:sg},[Bn]:{value(e){return yg(this,la(e,xg))}},toJSON:{value(){return Vn(this)}},[En]:{value(e){return ug(this,e)}},[sn]:{value(){return _n(this)}},toString:{value:Qn.toString},[Xn]:{value:Qn[Xn]}}),lg=e=>Object.assign(Object.create(cg),e),ug=/*#__PURE__*/ hte(/*#__PURE__*/ ii()),dg=/*#__PURE__*/ Object.create(cg),fg=e=>{if(e===void 0)return dg;if(Symbol.iterator in e){let t=Object.create(cg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(cg);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},pg=e=>Object.setPrototypeOf(e,cg),mg=/*#__PURE__*/ j(3,(e,t,n)=>{let r=lg(e);return r[t.toLowerCase()]=n,r}),hg=/*#__PURE__*/ j(2,(e,t)=>lg({...e,...fg(t)})),gg=/*#__PURE__*/ j(2,(e,t)=>{let n=lg(e);return Object.assign(n,t),n}),_g=/*#__PURE__*/ j(2,(e,t)=>{let n=lg(e);return delete n[t.toLowerCase()],n}),vg=/*#__PURE__*/ j(2,(e,t)=>{let n=lg(e);for(let e of t)delete n[e.toLowerCase()];return n}),yg=/*#__PURE__*/ j(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=rg(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=rg(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),bg=(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},xg=/*#__PURE__*/ ha(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Sg=e=>typeof e==`string`?e:ag(e),Cg=`~effect/http/UrlParams`,wg=e=>N(e,Cg),Tg={...gr,[Cg]:Cg,[Symbol.iterator](){return this.params[Symbol.iterator]()},[Bn](e){return{_id:`UrlParams`,params:Object.fromEntries(Ig(this,la(e,Kg)))}},toJSON(){return Vn(this)},[En](e){return Ag(this,e)},[sn](){return yn(this.params.flat())}},Eg=e=>{let t=Object.create(Tg);return t.params=e,t},Dg=e=>{if(wg(e))return e;let t=Og(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 Eg(n)},Og=e=>{let t=typeof e[Symbol.iterator]==`function`?Da(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,kg(r[t])]);else if(typeof r==`object`&&r&&!ng(r)){let t=Og(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,kg(r)]);return n},kg=e=>ng(e)?e:String(e),Ag=/*#__PURE__*/ ri((e,t)=>jg(e.params,t.params)),jg=/*#__PURE__*/ xte(/*#__PURE__*/ ste([/*#__PURE__*/ ii(),/*#__PURE__*/ wee()])),Mg=/*#__PURE__*/ Eg([]),Ng=/*#__PURE__*/ j(2,(e,t)=>{let n=Dg(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 Eg(n)}),Pg=e=>new URLSearchParams(Dg(e).params.map(([e,t])=>[e,Sg(t)])).toString(),Fg=e=>{let t={};for(let[n,r]of e.params){let e=Sg(r);if(!Object.hasOwn(t,n))ir(t,n,e);else{let r=t[n];typeof r==`string`?ir(t,n,[r,e]):r.push(e)}}return t},Ig=/*#__PURE__*/ j(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Lg(e,n)?rg(t):t])}),Lg=bg,Rg=(e,t=Gg())=>{e.includes(`@`)&&(e=Hg(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)+Ug(e.slice(n+1,i),t)+e.slice(i)},zg=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Bg=/[/\\?#]/,Vg=/[/?#]/,Hg=e=>{let t=``,n=[];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===9||i===10||i===13||t===``&&i<=32||(t+=e[r],n.push(r))}let r=zg.exec(t);if(r===null)return e;let i=r[0].length,a=r[1]!==void 0||!r[0].includes(`:`),o=t.slice(i),s=o.search(a?Bg:Vg),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])},Ug=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Lg(Wg(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),Wg=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},Gg=()=>la(globalThis[`~effect/Fiber/currentFiber`]?.context??na(),Kg),Kg=/*#__PURE__*/ ha(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function qg(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Jg(e){return t=>qg(t)?.[e]}const Yg=`~structural`,Xg=`~identifier`,Zg=`~sentinels`,Qg=`~constructor`,$g=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],e_=/*#__PURE__*/ Jg(`identifier`),t_=/*#__PURE__*/ Jg(Xg),n_=/*#__PURE__*/ Jg(`description`),r_=/*#__PURE__*/ Rt(e=>{let t=qg(e)?.identifier;return typeof t==`string`?t:e.getExpected(r_)}),i_=/*#__PURE__*/ new Set([Zg,Yg,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),a_=/*#__PURE__*/ Symbol(),o_=Cd,s_=/*#__PURE__*/ o_(a_),c_=/*#__PURE__*/ o_(a_),l_=e=>e===a_?Oi():ki(e),u_=e=>e._tag===`None`?s_:o_(e.value),d_=`~effect/SchemaIssue/Issue`;function f_(e){return N(e,d_)&&e[d_]===d_}function p_(e){return Object.hasOwn(e,`input`)}var m_=class{[d_]=d_;constructor(e,t){t?.reportInput===!0&&e!==a_&&(this.input=e)}};const h_=class extends m_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},g_=class extends m_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},__=class extends m_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},v_=class extends m_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},y_=class extends m_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},b_=class extends m_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},x_=class extends m_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},S_=class extends m_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function C_(e,t,n,r,i){return new b_(e,[new __([t],n)],r,i)}const w_=class extends m_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},T_=class extends m_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},E_=class extends m_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function D_(e,t,n){if(f_(e))return e;if(typeof e==`string`)return new S_({message:e},t,n);let r=typeof e.issue==`string`?new S_({message:e.issue},t,n):e.issue;return new __(e.path,r)}function O_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new S_(void 0,t,n):D_(e,t,n)}function k_(e,t,n,r){return Array.isArray(t)?ja(t)?t.length===1?D_(t[0],n,r):new b_(e,Pa(t,e=>D_(e,n,r)),n,r):void 0:O_(t,n,r)}const A_=e=>{let t=V_(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return F_(r_(e.ast),e);case`InvalidValue`:{let t=P_(e);if(t!==void 0)return F_(t,e);let n=N_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=N_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=N_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},j_=e=>V_(e.issue)??V_(e);function M_(e){return t=>({issues:I_(t,[],e?.leafHook??A_,e?.checkHook??j_)})}function N_(e){return p_(e)?Gn(e.input):void 0}function P_(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function F_(e,t){let n=N_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function I_(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 I_(e.issue,t,n,r);let a=P_(e.issue);return[{path:t,message:a===void 0?F_(L_(e.filter),e):F_(a,e.issue)}]}case`Encoding`:return I_(e.issue,t,n,r);case`Pointer`:return I_(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>I_(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:V_(e)??F_(r_(e.ast),e)}]:e.issues.flatMap(e=>I_(e,t,n,r));default:return[{path:t,message:n(e)}]}}function L_(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=>L_(e)).join(` & `)}}function R_(){return e=>B_(e,``)}const z_=/*#__PURE__*/ R_();function B_(e,t){let n;switch(e._tag){case`Filter`:{let r=j_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return B_(e.issue,t);let r=P_(e.issue);n=r===void 0?F_(L_(e.filter),e):F_(r,e.issue)}break}case`Encoding`:return B_(e.issue,t);case`Pointer`:return B_(e.issue,t+qn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>B_(e,t)).join(`
|
|
16
|
-
`);n=V_(e)??F_(r_(e.ast),e);break;default:n=A_(e)}return t?`${n}\n at ${t}`:n}function V_(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return V_(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 H_(e){let t;for(let n of e.reasons){if(!ad(n)||!f_(n.error))return;t??=n.error}return t}function U_(e,t){let n=H_(e);if(n===void 0)throw Error(t,{cause:e});return n}const W_=(e,t,n)=>{switch(e._tag){case`Passthrough`:return F(t);case`Transform`:return F(zi(t,e.transform));case`TransformOptional`:return F(e.transform(t));case`TransformEffect`:return Ai(t)?qf:gm(e.transform(t.value,n),ki);case`TransformOptionalEffect`:return e.transform(t,n)}},G_=e=>Object.assign(Object.create(kt),e),K_=(e,t)=>nv((n,r)=>ym(W_(e,n,r),e=>W_(t,e,r))),q_=/*#__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 $_(n=>t.transform(e.transform(n)));case`TransformOptional`:return tv(n=>t.transform(zi(n,e.transform)));case`TransformEffect`:return ev((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return K_(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return tv(n=>zi(e.transform(n),t.transform));case`TransformOptional`:return tv(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return K_(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return ev((n,r)=>gm(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return K_(e,t);case`TransformEffect`:return ev((n,r)=>ym(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return K_(e,t)}});function J_(e){return nv((t,n)=>z(e(t,n)))}function Y_(e){return J_((t,n)=>{let r={message:e(t)};return ji(t)?new w_(r,t.value,n):new w_(r)})}const X_=/*#__PURE__*/ Y_(()=>`Encoding is not supported`),Z_=/*#__PURE__*/ G_({_tag:`Passthrough`});function Q_(){return Z_}function $_(e){return G_({_tag:`Transform`,transform:e})}function ev(e){return G_({_tag:`TransformEffect`,transform:e})}function tv(e){return G_({_tag:`TransformOptional`,transform:e})}function nv(e){return G_({_tag:`TransformOptionalEffect`,transform:e})}function rv(e){return nv(t=>{let n=Vi(t,Qt);return ji(n)?F(n):gm(e,ki)})}function iv(){return $_(globalThis.String)}function av(){return $_(globalThis.Number)}function ov(){return $_(Bre)}function sv(e){return ev((t,n)=>ep({try:()=>JSON.parse(t,e?.reviver),catch:()=>new S_({expected:`a valid JSON string`},t,n)}))}function cv(e){return ev((t,n)=>ep({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 S_({expected:`a JSON-serializable value`},t,n)}))}function lv(e){let t=e?.separator??`,`;return $_(e=>e===``?[]:e.split(t))}function uv(){return $_(hh)}function dv(){return ev((e,t)=>_m(np(gh(e)),()=>new S_({expected:`a valid Base64 string`},e,t)))}const fv=class extends At{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new fv(this.encode,this.decode)}},pv=`~effect/SchemaTransformation/Transformation`,mv=class extends At{[pv]=pv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new mv(this.encode,this.decode)}};function hie(e){return N(e,pv)&&e[pv]===pv}const hv=e=>hie(e)?e:new mv(e.decode,e.encode);function gv(e){return new mv(ev(e.decode),ev(e.encode))}function _v(e){return new mv($_(e.decode),$_(e.encode))}function gie(){return new mv(ov(),Q_())}const _ie=/*#__PURE__*/ new mv(/*#__PURE__*/ Q_(),/*#__PURE__*/ Q_());function vv(){return _ie}const yv=/*#__PURE__*/ new mv(/*#__PURE__*/ av(),/*#__PURE__*/ iv()),vie=e=>nn(e)&&typeof e.message==`string`,yie=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:bv(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},bie=e=>{try{let t=Yn(e);return t===void 0?Gn(e):JSON.parse(t)}catch{return Gn(e)}},xie=(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},Sie=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(bee(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=xie(r,e,n);return t.delete(r),i}return bie(r)};return n},bv=e=>vie(e)?yie(e):e,Cie=e=>_v({decode:bv,encode:Sie(e)}),xv=/*#__PURE__*/ new mv(/*#__PURE__*/ dv(),/*#__PURE__*/ uv());function wie(e){return new mv(sv(e??{}),cv(e))}function Sv(e){return t=>t._tag===e}const Cv=/*#__PURE__*/ Sv(`Declaration`),Tie=/*#__PURE__*/ Sv(`Null`),Eie=/*#__PURE__*/ Sv(`Undefined`),wv=/*#__PURE__*/ Sv(`Void`),Die=/*#__PURE__*/ Sv(`Never`),Tv=/*#__PURE__*/ Sv(`Literal`),Ev=/*#__PURE__*/ Sv(`UniqueSymbol`),Oie=/*#__PURE__*/ Sv(`Enum`),Dv=/*#__PURE__*/ Sv(`Arrays`),Ov=/*#__PURE__*/ Sv(`Objects`),kv=/*#__PURE__*/ Sv(`Union`),Av=/*#__PURE__*/ Sv(`Suspend`),jv=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Mv={},Nv=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}},Pv=`~effect/Schema`;var Fv=class{[Pv]=Pv;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 Iv=class extends Fv{_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===a_?s_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Gy(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Iv(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>`}},Lv=/*#__PURE__*/ new class extends Fv{_tag=`Null`;getParser(){return tb(this,null)}getExpected(){return`null`}},kie=class extends Fv{_tag=`Undefined`;getParser(){return tb(this,void 0)}toCodecJson(){return Py(this,[Rv])}getExpected(){return`undefined`}},Rv=/*#__PURE__*/ new jv(Lv,/*#__PURE__*/ new mv(/*#__PURE__*/ $_(()=>void 0),/*#__PURE__*/ $_(()=>null))),zv=/*#__PURE__*/ new kie,Aie=/*#__PURE__*/ new class extends Fv{_tag=`Void`;getParser(){let e=o_(void 0);return t=>t===a_?s_:e}toCodecJson(){return Py(this,[Rv])}getExpected(){return`void`}},jie=/*#__PURE__*/ new class extends Fv{_tag=`Never`;getParser(){return nb(this,yee)}getExpected(){return`never`}},Mie=/*#__PURE__*/ new class extends Fv{_tag=`Any`;getParser(){return nb(this,tn)}getExpected(){return`any`}},Bv=/*#__PURE__*/ new class extends Fv{_tag=`Unknown`;getParser(){return nb(this,tn)}getExpected(){return`unknown`}};function Vv(e){return typeof e==`number`?`parts[${e}]`:e}function Hv(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${Vv(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=Vv(t);r=!e.checks&&e.parts.every((e,t)=>Hv(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=Vv(t);r=!e.checks&&e.types.every((e,t)=>Hv(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const Nie=class extends Fv{_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(!Hv(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 Jv(!1,this.parts.map(ob),[]),n=e(Jy(Gv,t,Pie(this)));return(e,t)=>{if(e===a_)return s_;let r=n(e,t);return r._tag===`Success`?c_:vm(r,{onSuccess:()=>e,onFailure:n=>new b_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return rb(this,e,t)===void 0?void 0:e}};function Pie(e){return new mv(ev((t,n)=>{let r=rb(e,t,n);return r?F(r):z(new S_({expected:`a string matching template literal parts`},t,n))}),$_(e=>e.join(``)))}const Uv=class extends Fv{_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 ${Gn(e)}`);this.literal=e}getParser(){return tb(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Wv(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Wv(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Wv(e){let t=globalThis.String(e.literal);return Py(e,[new jv(new Uv(t),new mv($_(()=>e.literal),$_(()=>t)))])}const Gv=/*#__PURE__*/ new class extends Fv{_tag=`String`;getParser(){return nb(this,Gt)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&lb(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Fie=class extends Fv{_tag=`Number`;getParser(){return nb(this,Kt)}matchKey(e,t){return this._match(aae,e,t)}matchPart(e,t){return this._match(sb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:lb(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Kv(this.checks,`effect/schema/isFinite`)||Kv(this.checks,`effect/schema/isInt`))?this:Py(this,[qie])}toCodecStringTree(){return this.toCodecJson()===this?Py(this,[sae]):Py(this,[cae])}getExpected(){return`number`}};function Kv(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Kv(e.checks,t))}const qv=/*#__PURE__*/ new Fie,Iie=/*#__PURE__*/ new class extends Fv{_tag=`Boolean`;getParser(){return nb(this,qt)}getExpected(){return`boolean`}},Jv=class extends Fv{_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(Yy(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(Yy(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 y_(n,t[o],i),a=new __([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return z(new b_(n,[a],t,i))}return e.issues?z(new b_(n,e.issues,t,i)):o_(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:zl(t.concurrency),f=d===1?Rie(i,e,0,u):zie(i,e,{concurrency:d,end:u});if(!f)return c(i);if(mc(f))return ym(f,()=>c(i));let p=!0;return Jf(()=>p?(p=!1,B(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===a_)return s_;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 x_(n,e,a))}catch(e){return $f(e)}}}_rebuild(e,t,n){let r=Gy(this.elements,e),i=Gy(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Jv(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 Lie(e,t,n,r){if(n._tag===`Failure`)return Xv(e,e.ast,r,n);let i=n===c_?t:n[ur];if(i!==a_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Yy(t.ast))return;let n=new __([r],new v_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Td(new b_(e.ast,[n],e.input,e.options))}}const Yv={onItem(e,t,n){let r=n<e.len?t:a_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Lie},Rie=/*#__PURE__*/ Bl()(Yv),zie=/*#__PURE__*/ Hl()(Yv),Xv=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=H_(r.cause);if(i===void 0)return wd(fd(r.cause,r=>new b_(t,[new __([n],r)],e.input,e.options)));let a=new __([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Td(new b_(t,[a],e.input,e.options))},Zv=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function Qv(e,t,n=Mv){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(ib(Qy(t)))}const $v=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ey(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ey);default:return!1}}function ty(e){let t=Iy(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ty);default:return!1}}function Bie(e){return ey(e)&&ty(e)}const ny=class{parameter;type;constructor(e,t){if(!Bie(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Yy(t)&&!eb(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},ry=class extends Fv{_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 nb(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(ib(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 Xv(t,n,i,s)??Od;let c=s===c_?o:s[ur];if(a!==a_&&c!==a_){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Od;ir(t.out,a,c)}return Od},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!mc(t))return B(op(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Xv(e,n,r,a)??Od;let o=a===c_?r:a[ur],s=e.input[r],l=i.parserValue(s,e.options);return mc(l)?t(e,r,o,s,l):B(op(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return mc(a)?t(e,n,n,i,a):B(op(a),r=>t(e,n,n,i,r))},u=i?Hl()({onItem:(e,[t,n])=>n.is.parameter===Gv?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return xm(function*(t,d){if(t===a_)return a_;if(typeof t!=`object`||!t||Array.isArray(t))return yield*z(new x_(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:zl(d.concurrency),v=i&&g?n.indexSignatures.map(e=>Qv(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 y_(n,f[a],d),r=new __([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*z(new b_(n,[r],t,d))}}}if(r){let e=_===1?oy(m,a):Vie(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Gv?l:c,r=v?.[e]??(t.is.parameter===Gv?Object.keys(f):Qv(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!mc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Ma();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Gv?Object.keys(f):Qv(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 b_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return B(op(n),n=>{let i=iy(e,r,n);if(i)return i;let o=()=>o_(e.out),s=oy(e,a.slice(t+1));return s?ym(s,o):o()})};return(e,t)=>{if(e===a_)return s_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&zl(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return z(new x_(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=vy(i,s),l=c?i[s]:a_,d=n.parser(l,t);if(!mc(d))return u(o,e,d);if(d===c_){c&&ir(a,s,l);continue}let f=iy(o,n,d);if(f)return f}}catch(e){return $f(e)}return o_(a)}}_rebuild(e,t,n,r){let i=Gy(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new $v(t.name,n)}),a=Gy(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new ny(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new ry(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 iy(e,t,n){if(n._tag===`Failure`)return Xv(e,e.ast,t.name,n);if(n===c_)return;let r=n[ur];if(r!==a_)ir(e.out,t.name,r);else if(delete e.out[t.name],!Yy(t.type)){let n=new __([t.name],new v_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Td(new b_(e.ast,[n],e.input,e.options))}}const ay={onItem(e,t){if(!vy(e.input,t.name))return t.parser(a_,e.options);let n=e.input[t.name];return ir(e.out,t.name,n),t.parser(n,e.options)},step:iy},oy=/*#__PURE__*/ Bl()(ay),Vie=/*#__PURE__*/ Hl()(ay);function sy(e,t){return e?t?[...e,...t]:e:t}function cy(e,t,n){return new ry(Reflect.ownKeys(e).map(t=>new $v(t,e[t].ast)),[],n,t)}function ly(e){return e.ast}function uy(e,t=void 0){return new Jv(!1,e.map(e=>e.ast),[],void 0,t)}function dy(e,t,n){return new yy(e.map(ly),t,void 0,n)}function Hie(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=sy(i,e.checks)}return new ry(n,r,void 0,i)}const fy=/*#__PURE__*/ zt(e=>{for(;;){if(Av(e))return Bv;let t=e.encoding;if(!t)return e.recur?.(fy,M)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==M))return Bv;e=t[t.length-1].to}});function py(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(py)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function my(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Zg];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Yy(t)){if(Tv(t))return[{key:e.name,literal:t.literal}];if(Ev(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Yy(e)){if(Tv(e))return[{key:t,literal:e.literal}];if(Ev(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>my(fy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return my(e.thunk())}}const hy=/*#__PURE__*/ new WeakMap,gy=/*#__PURE__*/ Object.freeze([]),_y=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,vy=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Uie(e){let t=hy.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=fy(c);if(Die(l))continue;if(Tv(l)||Ev(l)){a??=/* @__PURE__ */ new Map;let e=Tv(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=my(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=py(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??gy);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??gy;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=/* @__PURE__ */ new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(an(e)){let n=vy(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??gy;if(t)return o}return gy}}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=_y(t);if(!an(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=vy(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=vy(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=vy(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(_y(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return hy.set(e,t),t}const yy=class extends Fv{_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===a_)return s_;let i=(o??=Uie(n.types))(e,r);if(i.length===0)return z(new T_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:mc(r)?by(n,r.cause,e,t):Wie(n,r,e,t)}return xy(n,a,i,e,t)}}_rebuild(e,t,n){let r=Gy(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new yy(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=Qy(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Tv);if(t.length>0)return`${wy(n.isMutable)}[ ${t.map(t=>e(t)+Ty(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Tv(e.type));if(t.length>0)return`{ ${t.map(t=>`${wy(t.type.context?.isMutable)}${Kn(t.name)}${Ty(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function by(e,t,n,r){let i=H_(t);return i?Td(new T_(e,[i],n,r)):wd(t)}function Wie(e,t,n,r){return dp(t,t=>by(e,t,n,r))}function xy(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=Gie(a,n);if(!o)return a.out?a.out:z(new T_(e,a.issues??[],r,i));if(mc(o))return Sy(o,a);let s=!0;return Jf(()=>s?(s=!1,Sy(o,a)):xy(e,t,n,r,i))}function Sy(e,t){return ym(e,e=>t.out===c_?F(t.input):t.out?t.out:z(new T_(t.ast,t.issues??[],t.input,t.options)))}const Gie=/*#__PURE__*/ Bl()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=H_(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]),Td(new E_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Od}}}),Cy=/*#__PURE__*/ new yy([/*#__PURE__*/ new Uv(`Infinity`),/*#__PURE__*/ new Uv(`-Infinity`),/*#__PURE__*/ new Uv(`NaN`)]);function wy(e){return e?``:`readonly `}function Ty(e){return e?`?`:``}const Ey=class extends At{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Ey(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Ey(this.run,this.annotations,!0)}and(e,t){return new Dy([this,e],t)}},Dy=class extends At{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Dy(this.checks,{...this.annotations,...e})}and(e,t){return new Dy([this,e],t)}};function Oy(e,t,n=!1){return new Ey((t,n,r)=>k_(n,e(t,n,r),t,r),t,n)}function Kie(e){return Oy(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 ky=/*#__PURE__*/ zy(qv,[/*#__PURE__*/ Kie()]),qie=/*#__PURE__*/ new jv(/*#__PURE__*/ new yy([ky,Cy]),/*#__PURE__*/ new mv(/*#__PURE__*/ av(),/*#__PURE__*/ $_(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Ay(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Oy(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 jy=/*#__PURE__*/ new WeakMap;function My(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&jy.set(n,Ny(e)),n}function Ny(e){let t=jy.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 jy.set(e,n),n}function Py(e,t){return e.encoding===t?e:My(e,{encoding:t})}function Fy(e,t){if(e.context===t)return e;let n=Ny(e);return n.context===t&&n.encoding===e.encoding?n:My(e,{context:t})}function Iy(e){return e.encoding?Iy(e.encoding[e.encoding.length-1].to):e}function Ly(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Ry(e,ka(e.checks.slice(0,-1),n.annotate(t)))}return My(e,{annotations:{...e.annotations,...t}})}function Ry(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:My(e,{checks:t})}function zy(e,t){return Ry(e,sy(e.checks,t))}function By(e,t){let n=t(e.to);return n===e.to?e:new jv(n,e.transformation)}function Vy(e,t){let n=e,r=n[n.length-1],i=By(r,t);return i===r?e:ka(e.slice(0,e.length-1),i)}function Hy(e){return t=>t.encoding?Py(t,Vy(t.encoding,e)):t}function Uy(e,t){return Hy(e=>Fy(e,t))(e)}function Jie(e){function t(n){return n.encoding?Py(n,Vy(n.encoding,t)):e(n)}return Rt(t)}function Wy(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:Py(r,Vy(r.encoding,n))}return e(r)}return zt(n)}function Yie(e,t,n){let r=new jv(e,t);return Py(n,n.encoding?[...n.encoding,r]:[r])}function Gy(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 Ky(e,t){return Fy(e,e.context?new Nv(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Nv(!1,!1,void 0,t))}const qy=/*#__PURE__*/ zt(e=>{let t=e.context?e.context.isOptional===!1?new Nv(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Nv(!0,!1);return Xie(Fy(e,t))}),Xie=/*#__PURE__*/ Hy(qy),Zie=/*#__PURE__*/ Rt(e=>qy(new yy([e,zv])));function Qie(e,t){return Fy(e,e.context?new Nv(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Nv(!1,!1,t))}function Jy(e,t,n){return Yie(e,n,t)}function $ie(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Yt(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 eae(e,t){let{literals:n,parameters:r}=$ie(e);return new ry(n.map(e=>new $v(e,t)),r.map(e=>new ny(e,t)))}function Yy(e){return e.context?.isOptional??!1}function tae(e){return e.context?.isMutable??!1}function Xy(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Xy)}function nae(e){function t(e){return Xy(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Aa(n)?n:void 0}function rae(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Av(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const Zy=/*#__PURE__*/ zt(e=>{let t=Ny(e);if(t!==e){let n=Zy(t);return n===t&&e.encoding===void 0?e:Fy(n,e.context)}let n=`recur`in e?e.recur(Zy):e;if(`encodingChecks`in n&&n.encodingChecks){let t=rae(e)?n.encodingChecks:Dv(n)||Ov(n)||Cv(n)&&n.typeParameters.length>0?nae(n.encodingChecks):void 0;return My(n,{encodingChecks:void 0,checks:sy(n.checks,t)})}return n}),Qy=/*#__PURE__*/ zt(e=>Zy($y(e)));function iae(e,t){let n=t,r=n.length,i=n[r-1],a=[new jv($y(Py(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new jv($y(n[e-1].to),n[e].transformation.flip()));let o=$y(i.to);return o.encoding?Py(o,[...o.encoding,...a]):Py(o,a)}const $y=/*#__PURE__*/ Rt(e=>{if(e.encoding)return iae(e,e.encoding);let t=Ny(e);if(t!==e){let n=$y(t);return n===t?e:Fy(n,e.context)}return`flip`in e?e.flip($y):`recur`in e?e.recur($y):e});function eb(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(eb);default:return!1}}function tb(e,t){let n=t===0?c_:o_(t);return(r,i)=>r===a_?s_:r===t?n:z(new x_(e,r,i))}function nb(e,t){return(n,r)=>n===a_?s_:t(n)?c_:z(new x_(e,n,r))}function rb(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 ib=/*#__PURE__*/ Wy(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(ib)}}),ab=/*#__PURE__*/ Wy(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(ab)}}),ob=/*#__PURE__*/ Wy(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(ob)}}),sb=/*#__PURE__*/ new globalThis.RegExp(`^${Zv}$`),aae=/*#__PURE__*/ new globalThis.RegExp(`^(?:${Zv}|Infinity|-Infinity|NaN)$`);function oae(e){return Ay(sb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:sb.source}),...e})}const cb=/*#__PURE__*/ zy(Gv,[/*#__PURE__*/ oae()]),sae=/*#__PURE__*/ new jv(cb,yv),cae=/*#__PURE__*/ new jv(/*#__PURE__*/ new yy([cb,Cy]),yv);function lb(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=lb(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 h_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function lae(e){if(!Cv(e))return;let t=e.annotations?.[Qg];return Xt(t)?t(e.typeParameters):void 0}const ub=Jg,db=e_,uae=n_;function dae(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function fae(e){return e===void 0||typeof e==`string`}function fb(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 pb(e){return fb(e,dae)}const mb=/*#__PURE__*/ new Iv([],()=>(e,t,n)=>pb(e)?c_:z(new x_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>gb}),hb=/*#__PURE__*/ new jv(mb,/*#__PURE__*/ vv()),pae=/*#__PURE__*/ new jv(/*#__PURE__*/ new yy([/*#__PURE__*/ new Jv(!1,[],[mb]),/*#__PURE__*/ new ry([],[/*#__PURE__*/ new ny(Gv,mb)])]),/*#__PURE__*/ vv());function mae(e){return fb(e,fae)}const gb=/*#__PURE__*/ new jv(/* @__PURE__ */ new Iv([],()=>(e,t,n)=>mae(e)?c_:z(new x_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ vv()),_b=(e,t,n)=>e===c_?n(t):ym(e,n);function vb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===c_?e.decode(o_(l_(n)),r):e.decode(gm(t,l_),r);return yb(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===c_?o_(t):e;case`Transform`:{let e=e=>e===a_?s_:o_(t.transform(e));return(t,n)=>_b(t,n,e)}case`TransformOptional`:{let e=e=>u_(t.transform(l_(e)));return(t,n)=>_b(t,n,e)}case`TransformEffect`:return(e,n,r)=>_b(e,n,e=>e===a_?s_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>_b(e,n,e=>yb(t.transform(l_(e),r)))}}const yb=e=>ym(e,u_),bb=(e,t,n,r)=>dp(r,r=>Qf(()=>fd(r,r=>new g_(e,r,t,n))));function hae(e,t){let n=vb(e.link.transformation),r;return(i,a)=>{if(i===a_)return s_;if(e.isConstructed(i))return c_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function gae(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==a_&&r!==void 0)return t(r,i);let a=n;if(mc(a)&&a._tag===`Success`){let e=t(a[ur],i);return e===c_?a:e}return ym(bb(e,r,i,a),e=>{let n=t(e,i);return n===c_?o_(e):n})}}function _ae(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:gae(e,n)}function xb(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?lae(e):void 0,o=a?hae(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>vb(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(mc(r)){if(r._tag===`Success`){let i=r===c_?t:r[ur];if(t!==a_&&i!==a_){let i=lb(u,t,void 0,e,n);i&&(r=z(new b_(e,i,t,n)))}}}else r=B(r,r=>{if(t!==a_&&r!==a_){let r=lb(u,t,void 0,e,n);if(r)return z(new b_(e,r,t,n))}return F(r)})}if(s&&!n.disableChecks){if(mc(r)){if(r._tag===`Success`){let i=r===c_?t:r[ur];if(i===a_)return r;let a=lb(s,i,void 0,e,n);a&&(r=z(new b_(e,a,i,n)))}}else r=B(r,t=>{if(t!==a_){let r=lb(s,t,void 0,e,n);if(r)return z(new b_(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[ur],o=t(a,r)):o=ym(o,e=>{let n=t(e,r);return n===c_?o_(e):n})}if(o._tag===`Success`){let e=o[ur],t=p(e,r);return t===c_?o:t}return o=bb(e,n,r,o),ym(o,e=>{let t=p(e,r);return t===c_?o_(e):t})}:p}const vae=/*#__PURE__*/ Symbol(),Sb=/*#__PURE__*/ new WeakMap,yae=e=>wb(e).parser,Cb=e=>wb(e).makeEffect,bae=e=>_ae(e,Cb);var xae=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=xb(this.ast,yae)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=xb(this.ast,Cb,bae)}};function wb(e){let t=Sb.get(e);if(t!==void 0)return t;let n=new xae(e);return Sb.set(e,n),n}function Tb(e){let t=e.ast,n;return(e,r)=>(n??=Pb(Mae,Zy(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Eb(e){let t=Tb(e);return(e,n)=>{let r=om(t(e,n));return kd(r)?ki(r.value):(U_(r.cause,`Option adapter can only return none for schema issues`),Oi())}}function Db(e){return Aae(Zy(e.ast))}function Sae(e){return Ob(e.ast)}function Cae(e){{let t=Fb(Nb(e));return e=>{let n=t(e,Mv);return kd(n)?!0:(U_(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function Ob(e){let t=Zy(e),n=e=>(n=Cae(t),n(e));return e=>n(e)}function kb(e,t){let n=Nb(e.ast);return t===void 0?n:(e,r)=>n(e,jb(t,r))}function wae(e,t){return Dae(kb(e,t))}function Tae(e,t){return Oae(kb(e,t))}function Ab(e,t){let n=Nb($y(e.ast));return t===void 0?n:(e,r)=>n(e,jb(t,r))}const jb=(e,t)=>t?{...e,...t}:e,Mb=e=>e===a_?z(new S_):F(e);function Nb(e){return Pb(jae,e)}function Eae(e,t){return e===c_?F(t):mc(e)?e[`~effect/Effect/args`]===a_?Mb(a_):e:ym(e,Mb)}function Pb(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Mv);return a===c_?F(r):mc(a)?a[`~effect/Effect/args`]===a_?Mb(a_):a:ym(a,Mb)}}function Fb(e){return(t,n)=>om(e(t,n))}function Dae(e){let t=Fb(e);return(e,n)=>{let r=t(e,n);return kd(r)?ki(r.value):(U_(r.cause,`Option adapter can only return none for schema issues`),Oi())}}function Oae(e){let t=Fb(e);return(e,n)=>{let r=t(e,n);return kd(r)?va(r.value):ya(U_(r.cause,`Result adapter can only return schema issues`))}}function kae(e,t){let n=om(e);if(kd(n))return n.value;let r=U_(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Aae(e){let t,n;return(r,i)=>{t??=wb(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Mv,o=t.make;if(o!==void 0&&r!==a_){let e;try{e=o(r,a)}catch(e){throw U_(ld(e),`Constructor adapter can only throw schema issues`),e}if(e!==vae&&e!==a_)return e}return kae(Eae((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const jae=e=>wb(e).parser,Mae=e=>wb(e).makeEffect,Ib=`~effect/Schema/Schema`,Lb=/*#__PURE__*/ Symbol(),Nae={[Ib]:Ib,get make(){let e=Db(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=Tb(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Eb(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Ot(this,arguments)},annotate(e){return this.rebuild(Ly(this.ast,e))},annotateKey(e){return this.rebuild(Ky(this.ast,e))},check(...e){return this.rebuild(zy(this.ast,e))},rebuild(e){return Rb(e,this[Lb])}};function Rb(e,t){function n(){}let r=Object.setPrototypeOf(n,Nae);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[Lb]=t,r.ast=e,r}function Pae(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function zb(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Bb(e){return encodeURI(Pae(e)).replace(/#/g,`%23`)}function Vb(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 Hb(e){let t=Vb(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(zb)}function Fae(e){return e.reduce((e,t)=>`${e}/${Bb(t)}`,`#`)}const Iae=[`example`,`discriminator`,`xml`,`externalDocs`];function Lae(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>Ub.test(e))),i=t.filter(e=>!Ub.test(e)).sort().map(e=>[e,Rae(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=Kb(t.$id),a=nn(t.$defs)?t.$defs:void 0;return Wb(t,(t,o)=>{Vae(t,Iae,`OpenAPI 3.1`,`Draft 2020-12`),Gb(t,(t,s)=>{let c=t.startsWith(`#`)?Hb(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))&&Jb(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:Fae([`components`,`schemas`,n.get(l)??l,...c.slice(2)])})})}let o=e.schemas.map(e=>a(e,!0)),s={};for(let r of t)ir(s,n.get(r)??r,a(e.definitions[r]));return{dialect:`openapi-3.1`,schemas:o,definitions:s}}const Ub=/^[a-zA-Z0-9.\-_]+$/;function Rae(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function Wb(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!nn(e))return e;let a=r||!i&&Kb(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=Bae(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)}ir(o,t,i)}return t(o,a),o}}function zae(e,t){return Wb(e,e=>{Gb(e,t)})}function Gb(e,t){typeof e.$ref==`string`&&ir(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&ir(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function Bae(e,t){if(!nn(e))return;let n={};for(let r of Object.keys(e))ir(n,r,t(e[r],r));return n}function Kb(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const qb=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...qb],[...qb];function Jb(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Vae(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Jb(i,n,`it is not active in ${r} but would become active in the target`)}function Hae(e){return Rb(Yb(e.ast),{schema:e})}const Yb=/*#__PURE__*/ Wy(e=>{let t=Wae(e,Yb),n=e.context;return t===e||n===void 0?t:Uy(t,Xb(n))});function Xb(e){return e.constructorDefault===void 0?e:new Nv(e.isOptional,e.isMutable,void 0,e.annotations)}function Zb(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Qb(e){return t=>{let n=[...t].sort((t,n)=>e(Qy(t))-e(Qy(n)));return n.some((e,n)=>e!==t[n])?n:t}}const Uae=/*#__PURE__*/ Qb(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wae(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Xt(n))return Py(e,[hb]);let r=n(e.typeParameters.map(e=>Rb(Qy(e))));return r===void 0?e:Py(e,[By(r,t)])}case`Unknown`:return Py(e,[hb]);case`ObjectKeyword`:return Py(e,[pae]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Zb(e),e.recur(t,ab);case`Union`:{let n=Uae(e.types);return n===e.types?e.recur(t):new yy(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 Gae(e){return Rb(tx(e.ast),{schema:e})}function Kae(e){return Rb(rx(e.ast))}const qae=/*#__PURE__*/ Qb(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Jae(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>Rb(t(Qy(e)))),i=e.annotations?.toCodecStringTree;if(Xt(i)){let n=i(r);return n===void 0?e:Py(e,[By(n,t)])}let a=e.annotations?.toCodecJson,o=Xt(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(Xt(s)?s(r):void 0);return c===void 0?n(e):Py(e,[By(c,t)])}case`Null`:return Py(e,[Yae]);case`Boolean`:return Py(e,[Xae]);case`Unknown`:case`ObjectKeyword`:return Py(e,[gb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Zb(e),e.recur(t,ab);case`Union`:{let n=qae(e.types);return n===e.types?e.recur(t):new yy(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 Yae=/*#__PURE__*/ new jv(/*#__PURE__*/ new Uv(`null`),/*#__PURE__*/ new mv(/*#__PURE__*/ $_(()=>null),/*#__PURE__*/ $_(()=>`null`))),Xae=/*#__PURE__*/ new jv(/*#__PURE__*/ new yy([/*#__PURE__*/ new Uv(`true`),/*#__PURE__*/ new Uv(`false`)]),/*#__PURE__*/ new mv(/*#__PURE__*/ $_(e=>e===`true`),/*#__PURE__*/ iv())),$b=/*#__PURE__*/ new mv(/*#__PURE__*/ $_(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ Q_()),ex=e=>e.transformation===$b,tx=/*#__PURE__*/ Wy(e=>{let t=Jae(e,tx,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?Uy(t,Xb(e.context)):t},{stopAt:ex}),nx=e=>Yy(e)?qy(Bv):Bv,rx=/*#__PURE__*/ Wy(e=>{let t=Zae(e);if(Dv(t)){let n=Jy(new yy([new Jv(t.isMutable,t.elements.map(nx),t.rest.map(nx)),Gv],{mode:`anyOf`}),t,$b);return Yy(e)?qy(n):n}return t},{stopAt:ex});function Zae(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur(rx):e}globalThis.RegExp;const Qae=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function ix(e,t){return t.length>0&&(e+=`\n at ${qn(t)}`),Error(e)}function ax(e){return`#/$defs/${Bb(e)}`}const $ae=/*#__PURE__*/ new Set([...i_,Xg,...$g]);function ox(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;pb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&pb(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(pb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!$ae.has(r)&&t.includeAnnotationKey(r)&&pb(i)&&ir(n,r,i);return Object.keys(n).length===0?void 0:n}function sx(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=sx(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 eoe(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 cx(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function toe(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}function noe(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 lx=`|title|description|default|examples|readOnly|writeOnly|`;function ux(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=eoe(e);if(i!==void 0||a){let r=sx(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:cx(r.schema,lx)&&toe(o,s)?{...o,...r.schema}:ux(o,r.schema,n)}}if(n){let n=noe(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 dx(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>dx(e,t)))}function roe(e){return Array.isArray(e)}function fx(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=Pa(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!dx(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=g(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Dn(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Pa(u,h),f={};for(let e of l)a.has(e)||ir(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 ix(`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 zae(e,e=>{let t=Vb(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(zb(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,ax(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[Xg]: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=roe(s);c&&i.push(!1);let l=c?s[0]:s,u=ox(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`&&cx(d,f)&&(u===void 0||cx(u,lx))?!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=ox(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:ax(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=ox(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&ioe(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=ux(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 ix(`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(px).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw ix(`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=ox(e.annotations,r);return s===void 0?o:p(ux(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 ix(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=ox(s.annotations,r);ir(a,c,u===void 0?l:p(ux(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=v(i.type,[...t,`indexSignatures`,r,`type`],n);Dn(a,{not:{}})&&(a=!1),l.push(a);let o=b(i.parameter,[...t,`indexSignatures`,r,`parameter`],/* @__PURE__ */ new Set);if(o===void 0)u=!0,n.push(!1);else if(o.length===0)c.push(a);else for(let e of o){let t=s[e];ir(s,e,t===void 0?a:t===!1||a===!1?!1:p(ux(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=aoe(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 ix(`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 dx(n)&&r.type===`string`&&typeof r.pattern==`string`&&cx(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(px).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 ix(`Invalid schema representation document`,t)}}}function ioe(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function aoe(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 px(e){switch(e._tag){case`Literal`:return Qae(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return Zv;case`TemplateLiteral`:return e.parts.map(px).join(``);case`Union`:return`(?:${e.types.map(px).join(`|`)})`;default:throw ix(`Invalid schema representation document`,[])}}function ooe(e,t){let n=fx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function soe(e,t){return fx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const coe=({identifier:e})=>e;function mx(e){return e===void 0?void 0:{annotations:e}}function loe(e,t){let{references:n,representations:r}=hx([e],t);return{representation:r[0],references:n}}function hx(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??coe;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:Pa(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:Ly(e,{identifier:n}):t_(e)===r?e:Ly(e,{[Xg]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),ir(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=Iy(e),n=Ny(t),r=e_(t),i=r===void 0?(t===e?void 0:e_(e))??t_(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(Zy(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,...mx(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...mx(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...mx(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...mx(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...mx(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=Iy(e),n=t.context?.annotations;return{isOptional:Yy(t),type:m(e),...mx(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...mx(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=Iy(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Yy(t),isMutable:tae(t),...mx(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...mx(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...mx(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...mx(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:Pa(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(Zy(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function gx(e){return kd(e)?e.value:{issues:[{message:ure(e.cause)}]}}function uoe(e,t){let n=kb(e),r={errors:`all`,...t?.parseOptions},i=M_(t),a=e=>{let t=new To(`sync`),a=nm(Cp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?gx(o):new Promise(e=>{a.addObserver(t=>{e(gx(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 doe=/*#__PURE__*/ j(2,(e,t)=>moe(e,(e,n)=>poe(t,e)?void 0:[e,n])),foe=/*#__PURE__*/ j(2,(e,t)=>({...e,...t})),_x=e=>e;function poe(e,t){return e.some(e=>e===t||typeof e==`number`&&String(e)===t)}function moe(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;ir(n,e,t)}}return n}const vx=`~effect/Schema/SchemaError`;function yx(e){return N(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...Qn}),{...Qn},{...Qn},{...Qn},{...Qn},{...Qn},{...Qn},{...Qn};const bx=Ib;function xx(){return(e,t,n)=>Px(new Iv(e.map(ly),e=>t(e.map(e=>Px(e))),n))}function Sx(e,t){return xx()([],()=>(t,n,r)=>e(t)?F(t):z(new x_(n,t,r)),t)}var Cx=class extends (/*#__PURE__*/ Po(`SchemaError`)){[vx]=vx;constructor(e){let t=er();tr(0);try{super({issue:e})}finally{tr(t)}}get message(){return z_(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[Xn](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function hoe(e){return yx(e)}function wx(e){return mc(e)?goe(e):dp(e,e=>Qf(()=>fd(e,e=>new Cx(e))))}function goe(e){return kd(e)?e:wd(fd(e.cause,e=>new Cx(e)))}function _oe(e,t){let n;for(let r of e.reasons){if(!ad(r)||!hoe(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 Tx(e){let t=om(e);if(kd(t))return t.value;throw _oe(t.cause,`Sync adapter can only throw schema errors`)}function voe(e,t){return uoe(e,t)}const Ex=Sae;function Dx(e,t){let n=kb(e,t);return(e,t)=>wx(n(e,t))}const Ox=Dx,yoe=wae;function boe(e,t){let n=Tae(e,t);return(e,t)=>ite(n(e,t),e=>new Cx(e))}function kx(e,t){let n=Dx(e,t);return(e,t)=>Tx(n(e,t))}const xoe=kx;function Ax(e,t){let n=Ab(e,t);return(e,t)=>wx(n(e,t))}const jx=Ax;function Mx(e,t){let n=Ax(e,t);return(e,t)=>Tx(n(e,t))}const Nx=Mx,Px=Rb;function Fx(e){return N(e,bx)&&e[bx]===bx}const Ix=/*#__PURE__*/ _x(e=>Px(qy(e.ast),{schema:e})),Lx=/*#__PURE__*/ _x(e=>{let t=nS(e);return Px(Zie(e.ast),{schema:t})}),Rx=/*#__PURE__*/ _x(e=>Px(Zy(e.ast),{schema:e})),Soe=/*#__PURE__*/ _x(e=>Px(Qy(e.ast),{schema:e}));function zx(e){let t=Px(new Uv(e),{literal:e,transform(n){return t.pipe(rS(zx(n),{decode:$_(()=>n),encode:$_(()=>e)}))}});return t}function Coe(e){return e.map(e=>Fx(e)?e.ast:new Uv(e))}function Bx(e){return Px(new Nie(Coe(e)),{parts:e})}const Vx=/*#__PURE__*/ Px(jie),Hx=/*#__PURE__*/ Px(Mie),Ux=/*#__PURE__*/ Px(Bv),woe=/*#__PURE__*/ Px(Lv),Toe=/*#__PURE__*/ Px(zv),U=/*#__PURE__*/ Px(Gv),Wx=/*#__PURE__*/ Px(qv),Gx=/*#__PURE__*/ Px(Iie),Kx=/*#__PURE__*/ Px(Aie);function qx(e,t){return Px(e,{fields:t,mapFields(e,t){let n=e(this.fields);return qx(cy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function W(e){return qx(cy(e,void 0),e)}function Jx(e){return _x(t=>t.mapFields(foe(e)))}function Yx(e,t){return Px(eae(e.ast,t.ast),{key:e,value:t})}function Xx(e,t){return Px(Hie(e.ast,t.map(ly)),{schema:e,records:t})}function Zx(e,t){return Px(e,{elements:t,mapElements(e,t){let n=e(this.elements);return Zx(uy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Eoe(e){return Zx(uy(e),e)}const G=/*#__PURE__*/ _x(e=>Px(new Jv(!1,[],[e.ast]),{value:e})),Qx=/*#__PURE__*/ _x(e=>Px(new Jv(!1,[e.ast],[e.ast]),{value:e}));function $x(e,t){return Px(e,{members:t,mapMembers(e,t){let n=e(this.members);return $x(dy(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function K(e,t){return $x(dy(e,t,void 0),e)}function eS(e){let t=e.map(zx);return Px(dy(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return K(e(this.members))},pick(e){return eS(e)},transform(e){return K(t.map((t,n)=>t.transform(e[n])))}})}const tS=/*#__PURE__*/ _x(e=>K([e,woe])),nS=/*#__PURE__*/ _x(e=>K([e,Toe]));function rS(e,t){return n=>Px(Jy(n.ast,e.ast,t?hv(t):vv()),{from:n,to:e})}function Doe(){return(e,t)=>cS()(e,{decode:t,encode:X_})}const Ooe=/*#__PURE__*/ eS([`true`,`yes`,`on`,`1`,`y`]),koe=/*#__PURE__*/ eS([`false`,`no`,`off`,`0`,`n`]),Aoe=/*#__PURE__*/ eS([...Ooe.literals,...koe.literals]).pipe(/*#__PURE__*/ rS(Gx,/*#__PURE__*/ _v({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function joe(e){return t=>rS(Rx(t),e)(t)}function iS(e){return t=>Px(Qie(t.ast,e),{schema:t})}function aS(e){return zx(e).pipe(iS(F(e)))}function oS(e,t){return W({_tag:aS(e),...t})}function sS(){return e=>e}function Moe(e,t){return Sx(t=>t instanceof e,t)}function cS(){return(e,t)=>new jv(e.ast,hv(t))}const lS=Oy,uS=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Noe(e){let t=new globalThis.RegExp(uS);return lS(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:uS,flags:``}]},...e})}function dS(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${Gn(n)})`:`new RegExp(${Gn(n)}, ${Gn(r)})`;return Ay(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const fS=/*#__PURE__*/ Px(ky);function Poe(e){let t=Di(e.order),n=e.formatter??Gn;return(r,i)=>lS(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 Foe(e){let t=Di(e.order),n=Ti(e.order),r=Ei(e.order),i=wi(e.order),a=e.formatter??Gn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return lS(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 pS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${Gn(e)}`);return e}const Ioe=/*#__PURE__*/ Poe({order:Si,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:pS(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${Gn(e)})`})})}),mS=/*#__PURE__*/ Foe({order:Si,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:pS(e.minimum),maximum:pS(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${Gn(e.minimum)}, maximum: ${Gn(e.maximum)}, exclusiveMinimum: ${Gn(t)}, exclusiveMaximum: ${Gn(n)} })`})}}});function Loe(e){return lS(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 hS=/*#__PURE__*/ Wx.check(/*#__PURE__*/ Loe());function gS(e,t){return e=yS(e),_S(e,Math.ceil(e/2),t)}function _S(e,t,n){return lS(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})`}),[Yg]:!0,arbitraryConstraint:{minLength:e},...n})}function Roe(e){return _S(1,1,e)}function vS(e,t){return e=yS(e),lS(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})`}),[Yg]:!0,arbitraryConstraint:{maxLength:e},...t})}function yS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function zoe(e,t){return e=yS(e),lS(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})`}),[Yg]:!0,arbitraryConstraint:{minProperties:e},...t})}function bS(e){return lS(e=>Ste(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 xS=/*#__PURE__*/ U.check(/*#__PURE__*/ Roe()),Boe=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),Voe=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},SS=[];function CS(e){let t=Boe(e),n=SS[t];if(n!==void 0)return n;let r=QS.pipe(rS(Ux,Cie(Voe(t))));return SS[t]=r,r}globalThis.RegExp,globalThis.URL;const Hoe=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function wS(e,t){return Hoe.pipe(rS(e,wie(t)))}const Uoe=/*#__PURE__*/ wS(Ux);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const Woe=/*#__PURE__*/ U.check(/*#__PURE__*/ Noe()),TS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ rS(Woe,/*#__PURE__*/ gie())),ES=/*#__PURE__*/ U.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),DS=/*#__PURE__*/ Moe(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>cS()(ES,xv)}),OS=/*#__PURE__*/ ES.pipe(/*#__PURE__*/ rS(DS,xv));function kS(e,t){let n=xx()([e,t],([e,t])=>(n,r,i)=>{if(!id(n))return z(new x_(r,n,i));switch(n._tag){case`Fail`:return vm(kb(e)(n.error,i),{onSuccess:ud,onFailure:e=>C_(r,`error`,e,n,i)});case`Die`:return vm(kb(t)(n.defect,i),{onSuccess:dd,onFailure:e=>C_(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])=>cS()(K([W({_tag:zx(`Fail`),error:e}),W({_tag:zx(`Die`),defect:t}),W({_tag:zx(`Interrupt`),fiberId:nS(fS)})]),_v({decode:e=>{switch(e._tag){case`Fail`:return ud(e.error);case`Die`:return dd(e.defect);case`Interrupt`:return are(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 Px(n.ast,{error:e,defect:t})}function AS(e,t){let n=xx()([e,t],([e,t])=>{let n=G(kS(e,t));return(e,t,r)=>rd(e)?vm(kb(n)(e.reasons,r),{onSuccess:sd,onFailure:n=>C_(t,`failures`,n,e,r)}):z(new x_(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])=>cS()(G(kS(e,t)),_v({decode:sd,encode:({reasons:e})=>e}))});return Px(n.ast,{error:e,defect:t})}const jS=/*#__PURE__*/ gv({decode:(e,t)=>Mi(dh(e),{onNone:()=>z(new S_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>F(fh(e))}),encode:e=>F(mh(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 hS.check(mS({minimum:e,maximum:t}))}const PS=/*#__PURE__*/ Sx(e=>sh(e)&&ch(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 Doe()(NS(t,n),$_(uh))},toCodecJson:()=>cS()(U,jS),toFormatter:()=>e=>e.toString()}),FS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ rS(PS,jS));function IS(e,t,n){let r=xx()([e,t,n],([e,t,n])=>{let r=AS(t,n);return(t,n,i)=>{if(!Sd(t))return z(new x_(n,t,i));switch(t._tag){case`Success`:return vm(kb(e)(t.value,i),{onSuccess:Cd,onFailure:e=>C_(n,`value`,e,t,i)});case`Failure`:return vm(kb(r)(t.cause,i),{onSuccess:wd,onFailure:e=>C_(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])=>cS()(K([W({_tag:zx(`Success`),value:e}),W({_tag:zx(`Failure`),cause:AS(t,n)})]),_v({decode:e=>e._tag===`Success`?Cd(e.value):wd(e.cause),encode:e=>kd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return Px(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:kb(zx(n)),o=xx()([e],([e])=>(t,n,r)=>{if(ng(t)){let i=a===void 0?L:_m(a(t.label,r),e=>new __([`label`],e));return ym(i,()=>vm(kb(e)(ag(t),r),{onSuccess:e=>rg(e,{label:t.label}),onFailure:()=>new b_(n,[new __([`value`],new S_(void 0,t,r))],t,r)}))}return z(new x_(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}, ${Gn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>cS()(e,{decode:$_(e=>rg(e,{label:n})),encode:r?Y_(e=>`Cannot serialize Redacted`+(ji(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):$_(ag)}),toEquivalence:([e])=>og(e)});return Px(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[bx]=bx;get[o](){return o}static[RS]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return Ot(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return Db(a(this))(e??{},t)}static makeOption(e,t){return Eb(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Ly(this.ast,e))}static annotateKey(e){return this.rebuild(Ky(this.ast,e))}static check(...e){return this.rebuild(zy(this.ast,e))}static extend(e){return(t,r)=>{let a=WS(t)?t:W(t),o={...n.fields,...a.fields},s=cy(o,n.ast.checks,{identifier:e});return BS(this,e,qx(zy(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 mv($_(t=>new e(t,{"~payload":{token:zS,value:t}})),Q_())}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=rS(Px(new Iv([e.ast],()=>(e,t,n)=>o(e)?F(e):z(new x_(t,e,n)),{identifier:t,[Qg]:([e])=>({isConstructed:o,link:new jv(e,s)}),toCodec:([e])=>new jv(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[Zg]:my(e.ast),...n})),s)(e)}}function WS(e){return Fx(e)}const GS=e=>(t,n)=>{let r=WS(t)?t:W(t);return BS(ko,e,r,n,e=>({toString(){return`${e}(${Gn({...this})})`}}))},KS=e=>(t,n)=>{let r=WS(t)?t:W(t);return BS(Zr,e,r,n,e=>({name:e}))},qS=e=>(t,n,r)=>{let i=WS(n)?n.mapFields(e=>({_tag:aS(t),...e}),{unsafePreserveChecks:!0}):oS(t,n);return KS(e??t)(i,r)};function JS(e,t){return ooe(loe(Yb(e.ast),t),t)}const YS=Hae,XS=Gae,ZS=Kae,QS=/*#__PURE__*/ Px(/*#__PURE__*/ Ly(mb,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),q=/*#__PURE__*/ Yx(U,QS);function $S(){return Object.assign(e=>e,{option:e=>ki(e),result:e=>va(e),is:e=>!0})}const eC=Ns,tC=Ps,nC=Os,rC=Yl,iC=ou,aC=su,oC=`~effect/MutableRef`,sC={[oC]:oC,...gr,toJSON(){return{_id:`MutableRef`,current:Zn(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,Da(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=_a(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,Ud(),iC(!1),cC(!1),e.strategy(),cC(Oi()))),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)=>Jf(()=>e.shutdownFlag.current||ji(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=>qp(Dp(t=>{let n=la(t,Hd),r=Jd(e.scope),i=FC(e.pubsub,e.subscribers,e.strategy,e.ended);return Kd(r,kC(i)).pipe(rp(Gd(n,e=>Yd(r,e))),sp(i))})),kC=e=>qp(tp(t=>(lC(e.shutdownFlag,!0),Uf(bC(e.pollers),e=>yre(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(ip(()=>I(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),cie(e.shutdownHook.open),cp)))),AC=e=>Jf(()=>{if(e.shutdownFlag.current)return Wp;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=>Yf(t=>{if(e.shutdownFlag.current)return t(Wp);if(ji(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=Nd(),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=_a(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 Ot(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 Ot(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):(Bd(o,Cd(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=_a(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,...gr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:mw(this)}}},YC=e=>Xr(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},Is(n)}),XC=e=>YC({capacity:e}),ZC=e=>YC({capacity:e,strategy:`dropping`}),QC=/*#__PURE__*/ j(2,(e,t)=>Bs(()=>$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)=>qs(n=>{let r=tw(e,t);return r.length===0||e.strategy===`dropping`?n(Wr(r)):Ew(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),tw=(e,t)=>{if(e.state._tag!==`Open`)return Da(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 Da(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)=>zs(()=>rw(e,t))),rw=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=qr(t),r=One(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,Pr(ti())),aw=e=>rw(e,Pr(ti())),ow=e=>zs(()=>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=>Bs(()=>{let t=Ma();return tc(Mf(Il({while:Mt,body:jt(cw(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>Gs),t)}),uw=/*#__PURE__*/ j(3,(e,t,n)=>(t=_a(t),n=_a(n),Sw(()=>xw(e,t,n)??lc(ww(e,()=>Cw(e,t)),uw(e,t,n))))),dw=e=>Sw(()=>pw(e)??lc(ww(e,()=>Cw(e,1)),dw(e))),fw=e=>Sw(()=>{let t=pw(e);return t===void 0?Is(Oi()):t._tag===`Success`?Is(ki(t.value)):Is(Oi())}),pw=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=xC(e.messages);return kw(e),Wr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=Ow(e.state.offers);return kw(e),Wr(t)}},mw=e=>e.state._tag===`Done`?0:e.messages.length,hw=/*#__PURE__*/ Wr(!1),gw=/*#__PURE__*/ Wr(!0),_w=/*#__PURE__*/ Jr(/*#__PURE__*/ ti()),vw=/*#__PURE__*/ gc(),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(yc),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 Wr([]);if(!Cw(e,t))return;let r=e.messages.length>0?yC(e.messages,n):[Ow(e.state.offers)];return kw(e),Wr(r)},Sw=/*#__PURE__*/ Hr({op:`QueueTake`,[dr](e){let t=this[ur]();return yr(t)?t[dr](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)=>qs(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(yc);let r={ready:t,resume:n};return e.state.takers.add(r),zs(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),Tw=(e,t)=>qs(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),zs(()=>{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(Wr(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(Wr([]))),n},kw=e=>{if(e.state._tag===`Done`)return Nf(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(Aw(e,e.state.exit),Nf(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(Wr([]))}let r=e.state;if(r._tag===`Done`)return Nf(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)=>qs(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),zs(()=>{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=Bs(()=>this.free<e?Mw(this,e,t):(this.taken+=e,Is(e)));return t}takeIfAvailable(e){return Bs(()=>this.free<e?Is(!1):(this.taken+=e,Is(!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 Xr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Gs))}release(e){return Xr(t=>Is(this.releaseUnsafe(t,e)))}get releaseAll(){return Xr(e=>Is(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Pl(n=>{let r=Bs(()=>{if(this.free<e){let t=Mw(this,e,Gs);return pc(n(t),()=>r)}return this.taken+=e,fl(n(t),()=>{this.releaseUnsafe(Os(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>Pl(n=>this.free<e?Hs:(this.taken+=e,fl(n(cc(t)),()=>{this.releaseUnsafe(Os(),e)},!0)))}};const Pw=e=>zs(()=>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 Ot(this,arguments)}},Rw=e=>{let t=Object.create(Lw);return t.transform=(t,n)=>dp(e(t,n),e=>F(Zf(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=Jd(n),i=e=>Yd(r,If(e)),a=yield*zp(e(t,n,r),i);return zp(a,i)})),Hw=e=>e.transform,Uw=(e,t,n)=>YC({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(ip(t=>Kd(e,ow(t))),ip(n=>Wd(t(n),e).pipe(dp(e=>nw(n,e)),em(e)))),Ww=(e,t)=>Rw((n,r)=>V(Uw(r,e,t),cw)),Gw=e=>Rw((t,n)=>Jf(()=>Hw(e())(t,n))),Kw=e=>Bw(I(()=>{let t=e();return Jf(()=>{let e=t.next();return e.done?vd(e.value):F(e.value)})})),qw=e=>Qw(F(e)),Jw=/*#__PURE__*/ Bw(/*#__PURE__*/ F(/*#__PURE__*/ vd())),Yw=e=>Bw(F(z(e))),Xw=e=>Bw(Zf(e)),Zw=e=>Xw(ld(e)),Qw=e=>Bw(I(()=>{let t=!1;return Jf(()=>t?vd():(t=!0,e))})),$w=e=>Bw(B(e,()=>vd())),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=Jf(()=>n.current?n.current:wp(Kf({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Zf(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?vd():F(Na(t))}));return sp(Kd(e.scope,e.releaseLockOnEnd?I(()=>t.releaseLock()):Gf(()=>t.cancel().catch(Ft))),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(Mf(e,e=>B(t(e),vd))))),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*Kd(a,ow(l));let u=rm(yield*Ep()),d=rC(a);if(n.unordered){let e=jw(c),n=jt(e.release(1)),r=wp({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(Jf(()=>t(e,n))))),L}),Yp({disableYield:!0}),dp(t=>e.withPermits(c-1)(nw(l,t))),em(a))}else{let e=yield*XC(c-2);yield*Kd(a,ow(e)),yield*dw(e).pipe(eie,B(e=>QC(l,e)),Yp({disableYield:!0}),dp(e=>nw(l,e)),em(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,rw(l,e.cause))};yield*s.pipe(B(i=>{if(n)return Zf(n);let a=o++,s=u(Jf(()=>t(i,a)));return d(s),s.addObserver(r),QC(e,eC(s))}),Yp({disableYield:!0}),dp(t=>QC(e,wd(t)).pipe(rp(nw(e,t)))),em(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??=Jd(r),ym(Hw(t(e))(n,a),e=>(i=s(e),i)))),s=Mf(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Yd(a,Od);return a=void 0,B(t,()=>o)});return Jf(()=>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=Jd(r);return V(Hw(e)(n,i),e=>{let a=e.pipe(dp(e=>{if(Nf(e))return Zf(e);let o=i;return i=Jd(r),Yd(o,wd(e)).pipe(rp(Hw(t(e))(n,i)),B(e=>(a=e,e)))}));return Jf(()=>a)})})),hT=/*#__PURE__*/ j(2,(e,t)=>mT(e,e=>$w(B(t(e),t=>Zf(e))))),gT=/*#__PURE__*/ j(3,(e,t,n)=>mT(e,e=>{let r=t(e);return xa(r)?Xw(r.failure):n(r.success,e)})),_T=/*#__PURE__*/ j(2,(e,t)=>gT(e,cre,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*Kd(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*$p(f),yield*Sp(c.take(1),rp(eC(e),Xf))));let t=e===void 0?yield*f:yield*eC(e),n=Jd(o),r=yield*Hw(t)(i,n);for(;u.size>=s;){let e=cte(u);u.delete(e),u.size===0&&(yield*l.open),yield*tC(e)}let a=yield*r.pipe(ip(()=>$re),B(e=>QC(d,e)),Yp({disableYield:!0}),zp(H(function*(e){let t=If(e),r=yield*op(Yd(n,t));if(!u.has(a))return;let i=hre([t,r]);Ad(i)&&(yield*nw(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),$p);l.closeUnsafe(),u.add(a)}}).pipe(dp(e=>{let t=Ff(e);return Sa(t)?l.whenOpen(nw(d,e)):nw(d,e)}),em(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*Kd(a,ow(s));let c=0;function l(e,t){if(c++,!Nf(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)),Yp)),zp(t=>Bp(If(t),e=>Yd(n,e)).pipe(wp({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),em(a));return yield*u(`left`,e,Jd(a)),yield*u(`right`,t,Jd(a)),dw(s)}))),xT=()=>Rw((e,t)=>I(()=>{let t=``,n=!1,r=Oi();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 ja(r)?r:null}let a=Jf(()=>r._tag===`Some`?vd(r.value):Ure(e,{onSuccess:o,onFailure:Zf,onDone:e=>{if(r=ki(e),t.length>0){let e=t;return t=``,n=!1,F([e])}return vd(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=dp(e,e=>Nf(e)?Zf(e):$f(_d(e)));return V(Hw(t)(n,r),e=>fp(e,e=>gd(e)?Zf(e.value):$f(e)))}))),wT=e=>Rw((t,n)=>{let r;return F(Jf(()=>r||e.pipe(Wd(n),B(e=>Hw(e)(t,n)),B(e=>r=e))))}),TT=/*#__PURE__*/ j(2,(e,t)=>Vw((n,r,i)=>Gd(i,t).pipe(rp(Hw(e)(n,r))))),ET=/*#__PURE__*/ j(2,(e,t)=>TT(e,e=>t)),DT=(e,t,n)=>Jf(()=>{let r=Ud(),i=Hw(e)(vd(),r);return Mf(B(i,t),n||F).pipe(Vp(e=>Yd(r,e)))}),OT=/*#__PURE__*/ j(2,(e,t)=>Rw((n,r)=>V(kp(Hw(e)(n,r),t),kp(t)))),kT=/*#__PURE__*/ j(2,(e,t)=>DT(e,e=>Yp(B(e,t),{disableYield:!0}))),AT=/*#__PURE__*/ j(3,(e,t,n)=>Jf(()=>{let r=t();return DT(e,e=>Wf({while:Mt,body:()=>e,step:e=>{r=n(r,e)}}),()=>F(r))})),jT=(e,t)=>Hw(e)(vd(),t),MT=`~effect/PlatformError`;var NT=class extends (/*#__PURE__*/ Po(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},PT=class extends No{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},FT=class extends (/*#__PURE__*/ Po(`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 Ot(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 Ot(this,arguments)}},GT=e=>N(e,VT),KT=e=>qT((t,n)=>Hw(e)(t,n).pipe(B(Yp({disableYield:!0})),Mf(F))),qT=e=>{let t=Object.create(WT);return t.transform=e,t},JT=e=>Rw((t,n)=>F(B(e.transform(t,n),vd))),YT=/*#__PURE__*/ qT(e=>Mf(Yp(e,{disableYield:!0}),()=>HT)),XT=e=>ZT(Uf(t=>e(t),{discard:!0})),ZT=e=>qT(t=>t.pipe(B(e),Yp({disableYield:!0}),Mf(()=>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:qre()},pipe(){return Ot(this,arguments)}}),tE=e=>tp(t=>{let n=t.context,r=la(n,Hd),i=eE({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?Lt(e.idleTimeToLive,Ka):jt(Ka(e.idleTimeToLive??eo)),capacity:Math.max(e.capacity??1/0,0)});return sp(Gd(r,()=>{if(i.state._tag===`Closed`)return L;let e=i.state.map;return i.state={_tag:`Closed`},Uf(e,([,e])=>op(iE(e))).pipe(ip(()=>I(()=>{Zre(e)})))}),i)}),nE=/*#__PURE__*/ j(2,(e,t)=>Jp(n=>{if(e.state._tag===`Closed`)return Wp;let r=e.state,i=nC(),a=Rf(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&Qre(e.state.map)>=e.capacity)return z(new fre(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:Nd(),scope:Ud(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=aE(e,t,o),Yre(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(Hd.key,o.scope);let a=$i(n);Jf(()=>e.lookup(t)).pipe(rm(a),rC(o.scope)).addObserver(n=>{mre(n)&&rE(e,t,o,a),Bd(o.deferred,n)})}let s=ca(i.context,Hd);return Kd(s,o.finalizer).pipe(rp(n(Fd(o.deferred))))})),rE=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=Rf(e.state.map,t);i._tag!==`None`&&i.value===n&&(Bf(e.state.map,t),!(n.refCount>0)&&iE(n).pipe(rm(r),rC(e.scope)))},iE=e=>e.fiber?tC(e.fiber).pipe(rp(Yd(e.scope,Od))):Yd(e.scope,Od),aE=(e,t,n)=>tp(r=>{if(n.refCount--,n.refCount>0)return L;if(e.state._tag===`Closed`)return iE(n);let i=Rf(e.state.map,t);if(i._tag===`None`||i.value!==n)return iE(n);if(Za(n.idleTimeToLive))return Bf(e.state.map,t),iE(n);if(!Xa(n.idleTimeToLive))return L;let a=r.getRef(xf);return n.expiresAt=a.currentTimeMillisUnsafe()+uo(n.idleTimeToLive),n.fiber||=Jp(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=Rf(e.state.map,t);return r._tag===`None`||r.value!==n?L:(Bf(e.state.map,t),Yd(n.scope,Od))}return B(i(a.sleep(io(s))),()=>r(i))}).pipe(Rp(I(()=>{n.fiber=void 0})),rm(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 Ot(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=>tp(t=>{let n=t.context,r=la(n,Hd),i=new lE(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:Ka(e.idleTimeToLive));return sp(Gd(r,()=>{let e=i.state;return i.state=sE,e._tag===`Acquired`?Yd(e.scope,Od):e._tag===`Acquiring`?tC(e.fiber):L}),i)}),dE=(e,t)=>{switch(e.state._tag){case`Closed`:return Wp;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?sp(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=Ud(),i=kp(e.acquire,ia(e.context,Hd,r)).pipe(B(t=>{if(e.state!==n)return Wp;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)}),Vp(t=>kd(t)?L:(e.state===n&&(e.state=oE),Yd(r,t))));return n.fiber=rm(nC().context)(i),fE(e,n,t)}}},fE=(e,t,n)=>Vp(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)):Ad(n)?mE(e,r):L}),pE=e=>{let t=e;return Jp(e=>B(Pp,n=>B(dE(t,e),e=>sp(Gd(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),Yd(t.scope,Od)):(Xa(n)&&(t.fiber=Jp(r=>B(r(xp(n)),()=>e.state===t&&t.refCount===0?(e.state=oE,Yd(t.scope,Od)):L)).pipe(Rp(I(()=>{t.fiber=void 0})),rm(e.context),rC(e.scope))),L)},hE=uE,gE=pE,_E=e=>N(e,`~effect/Stream`),vE=BT,yE=e=>vE(Qw(V(e,Na))),bE=e=>xE(I(()=>{let t=!0,n=F(Na(void 0)),r=oie(n,e);return Jf(()=>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=>ja(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,Pa(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=_a(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=Jf(()=>{if(i!==void 0){let e=i;return i=void 0,F(e)}return e}).pipe(lp(e=>(r=Td(e),vd()))),o=V(Jf(()=>t.transform(a,n)),([e,t])=>(i=t,Na(e)));return Jf(()=>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)=>die(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 Wf({while:()=>n<e.length,body:()=>t(e[n++]),step:Ft})})),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=nm(kp(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(pd(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,im(cp(tC(i)))}},n?.strategy)}),tD=/*#__PURE__*/ j(e=>_E(e[0]),(e,t)=>V(Ep(),n=>eD(e,n,t))),nD=`~effect/FileSystem`,rD=/*#__PURE__*/ P(`effect/FileSystem`),iD=e=>rD.of({...e,[nD]:nD,exists:t=>It(e.access(t),sp(!0),up(`PlatformError`,e=>e.reason._tag===`NotFound`?F(!1):z(e))),readFileString:(t,n)=>B(e.readFile(t),e=>ep({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:rh(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:rh(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return xE(F(B(Jf(()=>a!==void 0&&a<=o?vd():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),Mi({onNone:()=>vd(),onSome:e=>(o+=BigInt(e.length),F(Na(e)))}))))},jE),sink:(t,n)=>It(e.open(t,{...n,flag:n?.flag??`w`}),V(e=>XT(t=>e.writeAll(t))),QT),writeFileString:(t,n,r)=>B(ep({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 Oi();let r=e.resolve(t),i=e.resolve(r,n),a=e.relative(r,i);return a===`..`||a.startsWith(`..${e.sep}`)||e.isAbsolute(a)?Oi():ki(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__*/ ha(`effect/ConfigProvider`,{defaultValue:()=>xD()}),mD={...gr,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(gte)?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__*/ Di(Vu),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__*/ ni({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=>ym(e(t,[]),np),t}const AD=(e,t,n)=>e.evaluator(t,n),jD=/*#__PURE__*/ j(2,(e,t)=>kD((n,r)=>gm(AD(e,n,r),e=>xa(e)?va(t):e))),MD=e=>on(e,`SourceError`),ND=()=>`<configuration>`,PD=e=>t=>dp(t,t=>Zf(sd(t.reasons.map(e)))),FD=(e,t)=>e.load(t).pipe(PD(e=>ad(e)?dd(e.error).annotate(bd(e)):e),gm(n=>({provider:e,path:t,node:n,toString:ND}))),ID=(e,t)=>FD(e.provider,[...e.path,t]),LD=(e,t)=>Jy(Bv,e,new mv(ev(e=>t(e)),Q_())),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__*/ Rt(e=>{let t=/* @__PURE__ */ new WeakSet,n=Jie(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>Ob(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&&ir(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=Qy(n.ast),i=kb(Px(BD(n.ast))),a=typeof t==`string`?[t]:t??[];return kD((e,t)=>{let n=[...t,...a];return FD(e,n).pipe(ym(e=>i(e).pipe(gm(va),bm(t=>{let i=new DD(new Cx(n.length>0?new __(n,t):t));return zD(r,e.node)?z(i):F(ya(i))}))),PD(e=>od(e)&&MD(e.defect)?ud(new DD(e.defect)).annotate(bd(e)):e))})}const HD=/*#__PURE__*/ hS.check(/*#__PURE__*/ mS({minimum:1,maximum:65535})),UD=e=>Gt(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(rS(XS(a),{decode:lv(i),encode:q_(Q_({strict:!1}),$_(e=>e.join(o)))})),a]),r?t:void 0)}function KD(e){return VD(Aoe,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(()=>Vre(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=>cm(n=>{let r=rO(n.currentTimeMillisUnsafe(),t(16));return F(e?.format===`bytes`?r:$D(r))}),randomULID:cm(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=>tp(t=>(nd(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 Ot(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 Sa(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?mO(this.provided,va(e.evaluate(this.provided))):this},pipe(){return Ot(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,ya(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 ba(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Sa(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?va(t.evaluate(r,...n)):ya(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 va(t.evaluate(r,...n))}return ya(r)}},DO=`effect/match/Match/exhaustive: absurd`,OO=e=>{let t=EO(e);if(ba(t)){if(Sa(t))return t.success;throw Error(DO)}return(...e)=>{let n=t(...e);if(Sa(n))return n.success;throw Error(DO)}},kO=_O,AO=vO,jO=yO,MO=SO,NO=CO,PO=wO,FO=Gt,IO=Kt,LO=qt,RO=TO,zO=OO,BO={"~effect/Ref":{_A:M},...gr,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)=>I(()=>{let n=e.ref.current;return e.ref.current=t,n})),KO=/*#__PURE__*/ j(2,(e,t)=>e===void 0?void 0:t(e)),qO=`~effect/Stdio`,JO=/*#__PURE__*/ P(qO),YO=e=>({[qO]:qO,stdinIsTerminal:F(!1),stdoutIsTerminal:F(!1),stderrIsTerminal:F(!1),...e}),XO=`~effect/Terminal`,ZO=`~effect/Terminal/QuitError`;var QO=class extends (/*#__PURE__*/ KS(`QuitError`)({_tag:/*#__PURE__*/ aS(`QuitError`)})){[ZO]=ZO};const $O=/*#__PURE__*/ P(`effect/Terminal`),ek=e=>$O.of({...e,[XO]:XO}),tk=/*#__PURE__*/ $S(),nk=/*#__PURE__*/ $S(),rk=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,ik={[rk]:rk,...Qn,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},ak=e=>Object.setPrototypeOf({...e},ik),ok=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 sk.of({spawn:e,exitCode:t=>Fp(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 sk=class extends (/*#__PURE__*/ P()(`effect/process/ChildProcessSpawner`)){};const ck=`~effect/process/ChildProcess`,lk={.../*#__PURE__*/ ni({label:`Command`,evaluate(e){return ca(e.context,sk).spawn(this)}}),[ck]:ck},uk=(e,t,n)=>Object.assign(Object.create(lk),{_tag:`StandardCommand`,command:e,args:t,options:n}),dk=function(...e){if(fk(e[0])){let[t,...n]=e,r=hk(t,n);return uk(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!fk(e[0])){let t=e[0];return function(e,...n){let r=hk(e,n);return uk(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return uk(t,[],n)}let[t,n=[],r={}]=e;return uk(t,n,r)},fk=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),pk=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},mk=e=>`fd${e}`,hk=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=gk(e,t,n,i,r);return n},gk=(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}=bk(r,a),l=xk(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>_k(e)):[_k(u)];return xk(l,d,s)},_k=e=>typeof e==`string`?e:String(e),vk=/*#__PURE__*/ new Set([` `,` `,`\r`,`
|
|
21
|
-
`]),yk={x:3,u:5},bk=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let n=vk.has(t[0]),r=[],i=0;for(let n=0,a=0;n<e.length;n+=1,a+=1){let o=t[a];if(vk.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+=yk[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},xk=(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)],Sk=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},Ck=(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})},wk=e=>KT(iT(Tk(e),e=>[e])),Tk=e=>Rw(t=>{let n=e.evaluate();return F(Ek({...e,writable:n,pull:t}))}),Ek=e=>e.pull.pipe(B(t=>{let n=0;return Yf(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)})})}),Yp({disableYield:!0}),e.endOnDone===!1?M:Mf(t=>`closed`in e.writable&&e.writable.closed?vd(t):Yf(n=>{let r=()=>n(vd(t));return e.writable.once(`finish`,r),e.writable.end(),I(()=>{e.writable.off(`finish`,r)})})),Sp(Yf(t=>{let n=n=>t(z(e.onError(n)));return e.writable.once(`error`,n),I(()=>{e.writable.off(`error`,n)})}))),Dk=e=>vE(Ok(e)),Ok=e=>Rw((t,n)=>Nk({scope:n,readable:e.evaluate(),onError:e.onError??Pk,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),kk=e=>Rw((t,n)=>{let r=e.evaluate(),i=cC(void 0),a=iC(!1);return Ek({pull:t,writable:r,onError:e.onError??Pk,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(dp(e=>(Nf(e)||(i.current=wd(e),a.openUnsafe()),L)),em(n),B(()=>Nk({scope:n,exit:i,latch:a,readable:r,onError:e.onError??Pk,chunkSize:e.chunkSize})))}),Ak=/*#__PURE__*/ j(2,(e,t)=>UE(e,kk(t))),jk=(e,t)=>{let n=Fk(t?.maxBytes),r=t?.onError??Pk;return Yf(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()})})},Mk=(e,t)=>V(jk(e,t),e=>new Uint8Array(e)),Nk=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=Td(e.onError(t)),i.openUnsafe()}function s(){r.current=Td(_d()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=Jf(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?z(_d()):(i.closeUnsafe(),B(i.await,n));let o=Na(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return F(o)});return sp(Kd(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)},Pk=e=>new pre(e),Fk=e=>e===void 0||e===1/0?void 0:Number(rh(e)),Ik=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Lk=(e,t,n)=>{let{commands:r}=Uk(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return Ck(`ChildProcess`,e)(t,[i])},Rk=1e3,zk=e=>{let t=()=>{};e.on(`error`,t),e.once(`close`,()=>e.off(`error`,t))},Bk=(e,t)=>{if(!Rd(t))return!0;if(globalThis.process.platform===`win32`)return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},Vk=(e,t=()=>{})=>{e.exitCode!==null||e.signalCode!==null?t(null):gt.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t)},Hk=/*#__PURE__*/ lf(sk,/* @__PURE__ */ R(function*(){let e=yield*rD,t=yield*cD,n=H(function*(n){if(!Zt(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 Zt(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 Zt(n)?{stream:`pipe`}:typeof n==`string`||GT(n)?{stream:n}:{stream:n.stream}},c=e=>{if(Zt(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=pk(n);Qt(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&&(zk(n),t=wk({evaluate:()=>n,onError:t=>Lk(`fromWritable(fd${o})`,Ik(t),e)})),a.stream&&(yield*tm(YE(a.stream,t))),r.set(o,t);break}case`output`:{let t=TE;if(n&&`read`in n){let r=new vt;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=Dk({evaluate:()=>r,onError:t=>Lk(`fromReadable(fd${o})`,Ik(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)=>Jf(()=>{let r=YT;return $t(t.stdin)&&(zk(t.stdin),r=wk({evaluate:()=>t.stdin,onError:t=>Lk(`fromWritable(stdin)`,Ik(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),_E(n.stream)?sp(tm(YE(n.stream,r)),r):F(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new vt;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),Dk({evaluate:()=>n,onError:t=>Lk(`fromReadable(stdout)`,Ik(t),e)})})():TE,a=t.stderr?(()=>{let n=new vt;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),Dk({evaluate:()=>n,onError:t=>Lk(`fromReadable(stderr)`,Ik(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)=>Yf(n=>{let r=Nd(),i=gt.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(z(Lk(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{Bd(r,Cd(e))}),i.on(`spawn`,()=>{n(F([i,r]))}),I(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?Yf(n=>{Vk(t,t=>{n(t?z(Lk(`kill`,Ik(t),e)):L)})}):ep({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>Lk(`kill`,Ik(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`)Vk(e);else try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>Jf(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return z(Lk(`kill`,t,e))}return L}),_=(e,t,n)=>Yf(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{clearTimeout(a),Date.now()>=i||!Bk(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(lp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),Zt(r?.forceKillAfter)?yield*_(t,n,Rk):(yield*_(t,n,uo(r.forceKillAfter)),Bk(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,Rk))),yield*Fd(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=pk(n);return Qt(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*Ip(p(e,Sk(e.options,{cwd:_,env:y,stdio:b},process.platform)),H(function*([t,n]){if(yield*Ld(n)){let[r]=yield*Fd(n);(r!==0&&$t(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*vp(v(e,t,n,e.options)))}else g&&(yield*vp(v(e,t,n,e.options)))})),ee=nk(x.pid);x.on(`exit`,t=>{t!==0&&$t(t)&&h(x,e.options.killSignal??`SIGTERM`)});let C=I(()=>{g||=(x.ref(),!0)}),te=I(()=>(g&&=(x.unref(),!1),C)),ne=yield*d(e,x,t),{all:w,stderr:T,stdout:re}=f(e,x,i,a),{getInputFd:ie,getOutputFd:ae}=yield*u(e,x,m),oe=V(Ld(S),e=>!e),se=B(Fd(S),([t,n])=>{if($t(t))return F(tk(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return z(Lk(`exitCode`,r,e))});return ak({pid:ee,exitCode:se,isRunning:oe,kill:t=>v(e,x,S,t),stdin:ne,stdout:re,stderr:T,all:w,getInputFd:ie,getOutputFd:ae,unref:te})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=Uk(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(dk(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=pk(l);if(Qt(e)){let n=mk(e),r=t.options.additionalFds??{};a.push(yield*b(dk(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(dk(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>Uf([...a].reverse(),t=>vp(t.kill(e)),{discard:!0}),l=R(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return Uf([...e].reverse(),e=>e,{discard:!0})});return ak({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 ok(b)})),Uk=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}},Wk=`~effect/http/HttpBody`,Gk=`~effect/http/HttpBody/HttpBodyError`;var Kk=class extends (/*#__PURE__*/ Po(`HttpBodyError`)){[Gk]=Gk},qk=class{[Wk];constructor(){this[Wk]=Wk}[Xn](){return this.toJSON()}toString(){return Gn(this,{ignoreToString:!0})}};const Jk=/*#__PURE__*/ new class extends qk{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var Yk=class extends qk{_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 Xk=(e,t)=>new Yk(e,t?.contentType,t?.contentLength);var Zk=class extends qk{_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??=tA(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 Qk=(e,t)=>new Zk(e,t??`application/octet-stream`,e.length),$k=/*#__PURE__*/ new TextEncoder,eA=globalThis.Buffer,tA=eA===void 0?e=>$k.encode(e):e=>eA.from(e,`utf8`),nA=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),eA!==void 0)return new Zk(void 0,t??`text/plain`,eA.byteLength(e,`utf8`),e);let n=$k.encode(e);return new Zk(n,t??`text/plain`,n.length,e)},rA=(e,t)=>nA(JSON.stringify(e),t??`application/json`),iA=(e,t)=>ep({try:()=>nA(JSON.stringify(e),t??`application/json`),catch:e=>new Kk({reason:{_tag:`JsonError`},cause:e})}),aA=(e,t)=>{let n=Ab(YS(e));return(e,r)=>n(e,t).pipe(mp(e=>new Kk({reason:{_tag:`SchemaError`,issue:e},cause:e})),B(e=>iA(e,r)))};var oA=class extends qk{_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 sA=(e,t,n)=>new oA(e,t??`application/octet-stream`,n),cA=`~effect/http/HttpClientError`;var lA=class extends (/*#__PURE__*/ Po(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[cA]=cA;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 uA=e=>e.endsWith(`Error`)?e.slice(0,-5):e,dA=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,fA=e=>`${e.method} ${Rg(e.url)}`;var pA=class extends (/*#__PURE__*/ Po(`TransportError`)){get methodAndUrl(){return fA(this.request)}get message(){return dA(uA(this._tag),this.description,this.methodAndUrl)}},mA=class extends (/*#__PURE__*/ Po(`InvalidUrlError`)){get methodAndUrl(){return fA(this.request)}get message(){return dA(uA(this._tag),this.description,this.methodAndUrl)}},hA=class extends (/*#__PURE__*/ Po(`StatusCodeError`)){get methodAndUrl(){return fA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return dA(uA(this._tag),this.description,e)}},gA=class extends (/*#__PURE__*/ Po(`DecodeError`)){get methodAndUrl(){return fA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return dA(uA(this._tag),this.description,e)}},_A=class extends (/*#__PURE__*/ Po(`EmptyBodyError`)){get methodAndUrl(){return fA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return dA(uA(this._tag),this.description,e)}};const vA=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,yA=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],bA=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?_g(_g(e,`content-type`),`content-length`):(e=t.contentType===void 0?_g(e,`content-type`):mg(e,`content-type`,t.contentType),t.contentLength===void 0?_g(e,`content-length`):mg(e,`content-length`,t.contentLength.toString())),xA=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var SA=class extends (/*#__PURE__*/ Po(`UrlError`)){};const CA=(e,t,n)=>rte({try:()=>{let r=new URL(e,wA());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Sg(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new SA({cause:e})}),wA=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},TA=`~effect/http/HttpClientRequest`,Goe={[TA]:TA,...Qn,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Rg(this.url),urlParams:this.urlParams,hash:this.hash,headers:Vn(this.headers),body:this.body.toJSON()}},pipe(){return Ot(this,arguments)}};function EA(e,t,n,r,i,a){let o=Object.create(Goe);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const Koe=/*#__PURE__*/ EA(`GET`,``,Mg,/*#__PURE__*/ Oi(),dg,Jk),DA=e=>(t,n)=>Joe(Koe,{method:e,url:t,...n??void 0}),qoe=/*#__PURE__*/ DA(`GET`),OA=/*#__PURE__*/ DA(`POST`),Joe=/*#__PURE__*/ j(2,(e,t)=>{let n=e;return t.method&&(n=Yoe(n,t.method)),t.url&&(n=Qoe(n,t.url)),t.headers&&(n=kA(n,t.headers)),t.urlParams&&(n=$oe(n,t.urlParams)),t.hash&&(n=ese(n,t.hash)),t.body&&(n=jA(n,t.body)),t.accept&&(n=AA(n,t.accept)),t.acceptJson&&(n=Zoe(n)),n}),Yoe=/*#__PURE__*/ j(2,(e,t)=>EA(t,e.url,e.urlParams,e.hash,e.headers,e.body)),Xoe=/*#__PURE__*/ j(3,(e,t,n)=>EA(e.method,e.url,e.urlParams,e.hash,mg(e.headers,t,n),e.body)),kA=/*#__PURE__*/ j(2,(e,t)=>EA(e.method,e.url,e.urlParams,e.hash,hg(e.headers,t),e.body)),AA=/*#__PURE__*/ j(2,(e,t)=>Xoe(e,`Accept`,t)),Zoe=/*#__PURE__*/ AA(`application/json`),Qoe=/*#__PURE__*/ j(2,(e,t)=>{if(typeof t==`string`)return EA(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Dg(n.searchParams),i=Fi(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,EA(e.method,n.toString(),r,i,e.headers,e.body)}),$oe=/*#__PURE__*/ j(2,(e,t)=>EA(e.method,e.url,Ng(e.urlParams,t),e.hash,e.headers,e.body)),ese=/*#__PURE__*/ j(2,(e,t)=>EA(e.method,e.url,e.urlParams,ki(t),e.headers,e.body)),jA=/*#__PURE__*/ j(2,(e,t)=>EA(e.method,e.url,e.urlParams,e.hash,bA(e.headers,t),t)),MA=/*#__PURE__*/ j(2,(e,t)=>jA(e,rA(t)));function tse(e){let t=CA(e.url,e.urlParams,Li(e.hash));return Sa(t)?ki(t.success):Oi()}const NA=`~effect/http/HttpIncomingMessage`,PA=(e,t)=>{let n=Ox(YS(e)),r=t?.reviver===void 0?void 0:Ox(wS(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))},FA=/*#__PURE__*/ ha(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),IA=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=am(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=am(e.text)}catch{}let i={...t,headers:Vn(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},LA=`~effect/http/HttpClientResponse`,nse=(e,t)=>new rse(e,t);var rse=class extends $n{[NA];[LA];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[NA]=NA,this[LA]=LA}toJSON(){return IA(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=tse(this.request);return Ai(e)?``:(e.value.hash=``,e.value.href)}get headers(){return fg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Ph(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Oi()}get stream(){return this.source.body?AE({evaluate:()=>this.source.body,onError:e=>new lA({reason:new gA({request:this.request,response:this,cause:e})})}):DE(new lA({reason:new _A({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return B(this.text,e=>ep({try:()=>e===``?null:JSON.parse(e),catch:e=>new lA({reason:new gA({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=>ep({try:()=>Dg(new URLSearchParams(e)),catch:e=>new lA({reason:new gA({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Kf({try:()=>this.source.formData(),catch:e=>new lA({reason:new gA({request:this.request,response:this,cause:e})})}).pipe(Hp,am)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Kf({try:()=>this.source.arrayBuffer(),catch:e=>new lA({reason:new gA({request:this.request,response:this,cause:e})})}).pipe(Hp,am),this.arrayBufferBody}pipe(){return Ot(this,arguments)}};const ise=e=>pg({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Mi(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),ase=e=>{let t=use(e);return ji(t)||(t=ose(e),ji(t))?t:sse(e)},ose=e=>{if(!(`b3`in e))return Oi();let t=e.b3.split(`-`);return t.length<2||zA(t[0],t[1])===!1?Oi():ki(Ko({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},sse=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]||zA(e[`x-b3-traceid`],e[`x-b3-spanid`])===!1?Oi():ki(Ko({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`})),cse=/^[0-9a-f]{32}$/i,RA=/^[0-9a-f]{16}$/i,lse=/^(?:[0-9a-f]{16}|[0-9a-f]{32})$/i,zA=(e,t)=>lse.test(e)&&RA.test(t),use=e=>{if(!e.traceparent)return Oi();let t=e.traceparent.split(`-`);if(t.length!==4)return Oi();let[n,r,i,a]=t;switch(n){case`00`:return cse.test(r)===!1||RA.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Oi():ki(Ko({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Oi()}},dse={"http:":80,"https:":443,"ws:":80,"wss:":443},BA=(e,t,n)=>{let r=Rg(t.search,n).slice(1);if(e.attribute(`url.full`,Rg(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===``?dse[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},fse=(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()]},VA=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,bg(a,i)?`<redacted>`:n[a])},HA=`~effect/http/HttpClient`,UA=/*#__PURE__*/ P(`effect/HttpClient`),pse=/*#__PURE__*/ j(2,(e,t)=>WA(B(n=>t(e.postprocess(F(n)),n)),e.preprocess)),mse=/*#__PURE__*/ j(2,(e,t)=>WA(n=>t(e.postprocess(n)),e.preprocess)),WA=(e,t)=>{let n=Object.create(hse);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},hse={[HA]:HA,pipe(){return Ot(this,arguments)},...Qn,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ yA.map(([e,t])=>[t,function(t,n){return this.execute(DA(e)(t,n))}]))},gse=e=>WA(t=>B(t,t=>tp(n=>{let r=KA.get(t),i=r??new AbortController,a=CA(t.url,t.urlParams,Li(t.hash));if(xa(a))return z(new lA({reason:new mA({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(qo)||n.getRef(yse)(t)){let a=e(t,o,i.signal,n);return r?a:Jp(e=>wp(e(a),{onSuccess(e){return GA.register(e,i),F(new qA(e,i))},onFailure(e){return hd(e)&&i.abort(),Zf(e)}}))}return Xp(n.getRef(Sse)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(xg);BA(a,o,fse(t.urlParams,n.getRef(Kg)));let c=n.getRef(bse);return VA(a,`request`,t.headers,c,s),t=n.getRef(xse)?kA(t,ise(a)):t,Jp(l=>l(e(t,o,i.signal,n)).pipe(Qp(a,{captureStackTrace:!1}),wp({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),VA(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),_se(n,a,t,e)),r?F(e):(GA.register(e,i),F(new qA(e,i)))),onFailure(e){return!r&&hd(e)&&i.abort(),Zf(e)}})))})})),F),_se=(e,t,n,r)=>{let i=er();tr(0);let a;try{a=Td(new lA({reason:new hA({request:n,response:r})}))}finally{tr(i)}t.end(e.getRef(xre)?e.getRef(xf).currentTimeNanosUnsafe():BigInt(0),a)},vse=e=>pse(e,(e,t)=>{let n=new AbortController;return KA.set(t,n),rp(Lp(()=>I(()=>n.abort())),e)}),yse=/*#__PURE__*/ ha(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Nt}),bse=/*#__PURE__*/ ha(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>Nt}),xse=/*#__PURE__*/ ha(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:Mt}),Sse=/*#__PURE__*/ ha(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Cse=e=>lf(UA)(Dp(t=>V(e,e=>mse(e,Mp(e=>pa(t,e)))))),GA=/*#__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))}}})(),KA=/*#__PURE__*/ new WeakMap;var qA=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[LA]=LA;[NA]=NA;applyInterrupt(e){return Jf(()=>(GA.unregister(this.original),Kp(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(()=>(GA.unregister(this.original),qE(this.original.stream,I(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Xn](){return this.original[Xn]()}pipe(){return Ot(this,arguments)}};const JA=/\+/g,YA=function(){};YA.prototype=/*#__PURE__*/ Object.create(null);function XA(e){let t=new YA;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(JA,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(JA,` `)),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 wse=/^https?:\/\/.*?\//,ZA=/(\/:[^/()]*?)\?(\/?)/,Tse=[],Ese=/^[^:*(]*\/:[^/:*(.-]+$/,Dse=e=>Ese.test(e),Ose=(e={})=>new kse(e);var kse=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(ZA);if(r&&r.index!==void 0){Nse(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(ZA,`$1$2`),a=t.replace(ZA,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=tj(t)),this.options.ignoreTrailingSlash&&(t=nj(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(Rse,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new ej(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new ej(``),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=rj(r,d),t=r.slice(d,e+1);c.push(Fse(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=Ise(_))),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(Dse(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(wse,`/`));let e;try{e=Lse(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreDuplicateSlashes&&(t=tj(t)),this.options.ignoreTrailingSlash&&(t=nj(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(Tse),searchParams:XA(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=aj(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:XA(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:XA(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=aj(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=aj(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}}}},Ase=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Pse(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},QA=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 Ase),this.isLeafNode=!0,this.handlerStorage.add(e)}},$A=class extends QA{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 ej(e),this.staticChildren[n]}},ej=class e extends $A{_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 jse(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 Mse),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}},jse=class extends $A{_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)}},Mse=class extends QA{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Nse=(e,t)=>{if(!e)throw Error(t)};function tj(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function nj(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Pse(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 rj(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 Fse(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 Ise(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ij(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 Lse(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);ij(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 aj(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=ij(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 Rse=/* @__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(`.`),oj=Ose,sj=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var cj=class extends (/*#__PURE__*/ P()(`effect/http/Etag/Generator`)){};const lj=e=>{let t=Mi(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},uj=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,zse=/*#__PURE__*/ of(cj)({fromFileInfo(e){return I(()=>({_tag:`Strong`,value:lj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Strong`,value:uj(e)}))}}),Bse=/*#__PURE__*/ of(cj)({fromFileInfo(e){return I(()=>({_tag:`Weak`,value:lj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Weak`,value:uj(e)}))}}),Vse=/*#__PURE__*/ Object.getPrototypeOf(dg),Hse=()=>Object.create(Vse),dj=`~effect/http/HttpServerResponse`,fj=e=>N(e,dj),pj=e=>Oj({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?fg(e.headers):void 0,cookies:e?.cookies}),mj=(e,t)=>{let n=pg({location:e.toString()});return Oj({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?gg(n,fg(t.headers)):n,cookies:t?.cookies??Ih})},hj=(e,t)=>{let n=t?.headers?fg(t.headers):dg;return Oj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Ih,body:Qk(e,gj(t,n))})},gj=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},_j=(e,t)=>{let n=t?.headers?fg(t.headers):dg;return Oj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Ih,body:nA(e,gj(t,n))})},Use=(e,t)=>{let n=aA(e,t);return(e,t)=>{let r=t?.headers?fg(t.headers):dg;return V(n(e,gj(t,r)),e=>Oj({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},vj=(e,t)=>{let n=t?.headers?fg(t.headers):dg;return Oj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:rA(e,gj(t,n))})},Wse=(e,t)=>{let n=t?.headers?fg(t.headers):dg;return Oj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:nA(Pg(Dg(e)),gj(t,n)??`application/x-www-form-urlencoded`)})},yj=(e,t)=>Oj({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&fg(t.headers),cookies:t?.cookies,body:Xk(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),bj=(e,t)=>{let n=t?.headers?fg(t.headers):dg;return Oj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:sA(e,gj(t,n),t?.contentLength)})},xj=/*#__PURE__*/ j(3,(e,t,n)=>Oj(e,mg(e.headers,t,n))),Sj=/*#__PURE__*/ j(2,(e,t)=>Oj({...e,headers:_g(e.headers,t)})),Cj=/*#__PURE__*/ j(2,(e,t)=>Oj(e,hg(e.headers,t))),wj=/*#__PURE__*/ j(e=>fj(e[0]),(e,t,n,r)=>V(np(Kh(e.cookies,t,n,r)),t=>Oj({...e,cookies:t}))),Tj=/*#__PURE__*/ j(2,(e,t)=>Oj({...e,cookies:Gh(e.cookies,t)})),Ej=/*#__PURE__*/ j(2,(e,t)=>Oj({...e,body:t},bA(e.headers,t))),Gse=/*#__PURE__*/ j(e=>fj(e[0]),(e,t,n)=>Oj({...e,status:t,statusText:n??e.statusText})),Kse=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,Dj=(e,t)=>{for(let[n,r]of t)n===`set-cookie`?e.append(n,r):e.set(n,r);return e},qse=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!Lh(e.cookies)){let t=Xh(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=Kse(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 Dj(e.headers,n),e}let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:Dj(new globalThis.Headers(t.headers),n)})}if(a)return r._tag===`Raw`&&Jse(r.body)&&r.body.cancel().catch(Ft),new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});switch(r._tag){case`Empty`:return new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});case`Uint8Array`:return new Response(r.text??r.body,{status:e.status,statusText:e.statusText,headers:n});case`Raw`:return new Response(r.body,{status:e.status,statusText:e.statusText,headers:n});case`FormData`:return new Response(r.formData,{status:e.status,statusText:e.statusText,headers:n});case`Stream`:return new Response(eD(r.stream,t?.context??na(),{signal:t?.signal}),{status:e.status,statusText:e.statusText,headers:n})}},Jse=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,Yse={...gr,[dj]:dj,[lO]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Vn(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},Oj=(e,t)=>{let n=Object.create(Yse);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??Ih,n.body=e.body??Jk,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===dg?Hse():pg({...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??dg;return n},Xse=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=pj({status:e.status,statusText:e.statusText,headers:t,cookies:Ph(n)});if(e.body){let t=e.headers.get(`content-type`);r=Ej(r,sA(AE({evaluate:()=>e.body,onError:e=>e}),t??void 0,xA(e.headers.get(`content-length`))))}return r},Zse=(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}`},Qse=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:Zse(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),Cj(e,r)})}}),kj={"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(kj);let Aj;const $se=()=>{if(Aj!==void 0)return Aj;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(kj)){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 Aj={extensionToType:e,typeToExtension:t,typeToExtensions:n},Aj},jj=e=>{if(typeof e!=`string`)return Oi();let t=e.replace(/^.*[/\\]/s,``).toLowerCase(),n=t.replace(/^.*\./s,``).toLowerCase(),r=t.length<e.length;return!(n.length<t.length-1)&&r?Oi():Ii($se().extensionToType.get(n))};var Mj=class extends (/*#__PURE__*/ P()(`effect/http/HttpPlatform`)){};const ece=/*#__PURE__*/ H(function*(e){let t=yield*rD,n=yield*cj;return Mj.of({platform:e.platform,compression:Qse(e.compression),fileResponse:H(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?Qm:yield*Pj(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*Pj(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*Fj(c,`offset`),m=f===void 0?void 0:yield*Fj(f,`end`),h=mg(Nj(i),`etag`,sj(o));return ji(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=gg(Nj(r),pg({etag:sj(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),Nj=e=>{let t=e?.headers?fg(e.headers):dg;return e?.contentType?mg(t,`content-type`,e.contentType):t},Pj=(e,t)=>{let n=ih(e);return ji(n)?F(n.value):z(LT({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},Fj=(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}`}))},Ij=`~effect/http/HttpServerRespondable`,Lj=e=>N(e,Ij),tce=/*#__PURE__*/ pj({status:400}),nce=/*#__PURE__*/ pj({status:404}),rce=(e,t)=>fj(e)?F(e):Lj(e)?dp(e[Ij](),()=>F(t)):yx(e)?F(tce):dre(e)?F(nce):F(t),ice=(e,t)=>fj(e)?F(e):Lj(e)?dp(e[Ij](),()=>F(t)):F(t),Rj=`~effect/http/HttpServerError`;var zj=class extends (/*#__PURE__*/ Po(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[Rj]=Rj;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[Ij](){return this.reason[Ij]()}get[lO](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},Bj=class extends (/*#__PURE__*/ Po(`RequestParseError`)){[Ij](){return F(pj({status:400}))}get methodAndUrl(){return Uj(this.request)}get message(){return Wj(this._tag,this.description,this.methodAndUrl)}},ace=class extends (/*#__PURE__*/ Po(`RouteNotFound`)){[Ij](){return F(pj({status:404}))}[lO]=!0;get methodAndUrl(){return Uj(this.request)}get message(){return Wj(this._tag,this.description,this.methodAndUrl)}};const oce=e=>N(e,Rj);var Vj=class extends (/*#__PURE__*/ Po(`ResponseError`)){[Ij](){return F(pj({status:500}))}get methodAndUrl(){return Uj(this.request)}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},Hj=class extends (/*#__PURE__*/ P()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ ia(xd,{name:`ClientAbort`,stack:Pt,parent:void 0}))};const Uj=e=>`${e.method} ${Rg(e.url)}`,Wj=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},Gj=e=>{let t,n=cce,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=rce(s.error,Kj),r.push(s);break;case`Die`:fj(s.defect)?t=s.defect:(n=ice(s.defect,Kj),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(Hj.key),r.length>0)break;i.push(s)}}return t?F([t,sd(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?lce:uce),gm(n,e=>(r.push(dd(e)),[e,sd(r)])))},sce=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&fj(e.defect)?(t=e.defect,!1):!0);return[t??Kj,n.length>0?ki(sd(n)):Oi()]},Kj=/*#__PURE__*/ pj({status:500}),cce=/*#__PURE__*/ F(Kj),lce=/*#__PURE__*/ F(/*#__PURE__*/ pj({status:499})),uce=/*#__PURE__*/ F(/*#__PURE__*/ pj({status:503})),qj=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,Jj=/\\([\v\u0020-\u{10ffff}])/gu,dce=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,fce=/^[!#$%&'*+.^\w|~-]+$/u,Yj={value:``,parameters:/*#__PURE__*/ Object.create(null)};function Xj(e,t=!1){if(typeof e!=`string`)return Yj;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?fce:dce).test(r)===!1)return Yj;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(qj.lastIndex=n;o=qj.exec(e);){if(o.index!==n)return Yj;n+=o[0].length,a=o[1].toLowerCase(),s=o[2],s[0]===`"`&&(s=s.slice(1,s.length-1),!t&&Jj.test(s)&&(s=s.replace(Jj,`$1`))),i.parameters[a]=s}return n===e.length?i:Yj}const Zj=16384,Qj={key:0,whitespace:1,value:2},$j={_tag:`Continue`},eM=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")eM[/*#__PURE__*/ e.charCodeAt(0)]=1;const tM=/*#__PURE__*/ new Uint8Array(256);tM[9]=1;for(let e=32;e<=126;e++)tM[e]=1;for(let e=128;e<=255;e++)tM[e]=1;function pce(){let e=new TextDecoder,t={state:Qj.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=Qj.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===Qj.key){let n=o;for(;n<l;n++){if(t.size++>Zj)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=Qj.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=Qj.value):(o=n+1,t.state=Qj.whitespace);break}if(eM[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),$j}if(t.state===Qj.whitespace){for(;o<l;o++){if(t.size++>Zj)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=Qj.value;break}}if(o===l)return $j}if(t.state===Qj.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>Zj)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),$j;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=Qj.key;continue outer}}else if(tM[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)),$j}}return o>l&&(t.size+=l-o),$j}}function mce(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 hce(e,t,n,r){let i=mce(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 nM={headers:0,body:1},gce={_tag:`InvalidDisposition`},_ce={_tag:`EndNotReached`},vce={_tag:`ReachedLimit`,limit:`MaxParts`},yce={_tag:`ReachedLimit`,limit:`MaxTotalSize`},bce={_tag:`ReachedLimit`,limit:`MaxPartSize`},rM={_tag:`ReachedLimit`,limit:`MaxFieldSize`},xce=/*#__PURE__*/ new TextEncoder().encode(`\r
|
|
23
|
-
`);function iM(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function Sce(e){return Xj(e[`content-type`]).parameters.boundary}function aM(e){}const oM=e=>e===1/0?1/0:Number(rh(e));function Cce({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=iM,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=oM(s),d=oM(c),f=oM(l),p=Sce(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:aM,end(){}};let m={state:nM.headers,index:0,parts:0,onChunk:aM,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=nM.body,m.isFile=!0,m.onChunk=aM}function g(e){m.stopped=!0,m.state===nM.body&&m.isFile&&m.onChunk(null),r(e)}let _=pce(),v=hce(`\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=nM.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(vce)}if((m.partSize+=s.length)>d)return g(bce);if(m.state===nM.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=Xj(e.headers[`content-type`]),i=Xj(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(gce);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=nM.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(rM);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(rM);m.fieldChunks.push(s)}}}},xce,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(yce):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(_ce),m.state=nM.headers,m.index=0,m.parts=0,m.onChunk=aM,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const sM=/*#__PURE__*/ new TextDecoder(`utf-8`);function wce(e){if(e===`utf-8`||e===`utf8`||e===``)return sM;try{return new TextDecoder(e)}catch{return sM}}function Tce(e,t){return wce(e.contentTypeParameters.charset??`utf-8`).decode(t)}const Ece=Cce,Dce=iM,Oce=Tce,cM=`~effect/http/Multipart`,lM=`~effect/http/Multipart/MultipartError`,kce=e=>Mce(e)?e:uM.fromReason(`InternalError`,e);var Ace=class extends No{};const jce={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var uM=class e extends (/*#__PURE__*/ Po(`MultipartError`)){static fromReason(t,n){return new e({reason:new Ace({_tag:t,cause:n})})}[lM]=lM;[lO]=!0;[Ij](){return F(pj({status:jce[this.reason._tag]}))}get message(){return this.reason._tag}};const Mce=e=>N(e,lM),Nce=e=>tp(t=>{let n=la(t.context,hM);return F({headers:e,maxParts:t.getRef(fM),maxFieldSize:t.getRef(pM),maxPartSize:t.getRef(mM),maxTotalSize:t.getRef(FA),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&Dce(e)})});var Pce=class extends $n{[cM];constructor(){super(),this[cM]=cM}};const Fce=(e,t)=>B(rD,n=>mp(YE(t.content,n.sink(e)),kce)),Ice=/*#__PURE__*/ new TextEncoder,Lce=e=>{let t=Array.from(e),n=``,r=0;for(let e=t.length-1;e>=0&&(r+=Ice.encode(t[e]).length,!(r>128));e--)n=t[e]+n;return n===``||n===`.`||n===`..`?`file`:n},Rce=(e,t=Fce)=>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=Lce(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 zce(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(up(`PlatformError`,e=>z(uM.fromReason(`InternalError`,e))));var zce=class extends Pce{_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 dM=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(fM.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(pM.key,rh(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(mM.key,rh(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(FA.key,rh(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(hM.key,e.fieldMimeTypes),$i(t)},fM=/*#__PURE__*/ ha(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),pM=/*#__PURE__*/ ha(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ jt(/*#__PURE__*/ oh(10))}),mM=/*#__PURE__*/ ha(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),hM=/*#__PURE__*/ ha(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ jt([`application/json`])}),gM=`~effect/http/HttpServerRequest`,_M=/*#__PURE__*/ P(`effect/http/HttpServerRequest`);var vM=class extends (/*#__PURE__*/ P()(`effect/http/ParsedSearchParams`)){};const Bce=(e,t)=>{let n=Dx(e);return B(_M,e=>n(e.cookies,t))},Vce=(e,t)=>{let n=Dx(e);return B(_M,e=>n(e.headers,t))},Hce=(e,t)=>{let n=Dx(e);return B(vM,e=>n(e,t))},Uce=e=>{let t=e.headers.host??`localhost`,n=e.headers[`x-forwarded-proto`]===`https`?`https`:`http`;try{return ki(new URL(e.url,`${n}://${t}`))}catch{return Oi()}},yM=/*#__PURE__*/ new WeakMap,Wce=(e,t)=>{let n=yM.get(e.source),r=n?(e,r)=>B(n(e,r),n=>t(e,n)):t;yM.set(e.source,r)},Gce=e=>e,Kce=/*#__PURE__*/ new WeakSet,qce=e=>tp(t=>{let n=ca(t.context,_M);return Kce.add(n.source),e}),Jce=/*#__PURE__*/ ha(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>Nt}),Yce=/*#__PURE__*/ ha(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Xce=/*#__PURE__*/ ha(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>Nt}),bM=(e,t)=>!e.cache.tracerEnabled||e.getRef(Jce)(t),xM=(e,t)=>{if(!(t.status>=500&&t.status<600))return Cd(t);let n=er();tr(0);try{return Td(new zj({reason:new Vj({request:e,response:t})}))}finally{tr(n)}},SM=/*#__PURE__*/ Gce(e=>tp(t=>{let n=ca(t.context,_M);if(bM(t,n))return e;let r=t.getRef(Yce),i=fu(t,r(n),{parent:Li(ase(n.headers)),kind:`server`}),a=t.context;return t.setContext(ia(t.context,Wo,i)),pl(t,e=>{t.setContext(a);let r=t.getRef(xf).currentTimeNanosUnsafe();if(kd(e)&&(!i.sampled||t.getRef(Zo)===Qo)){i.end(r,xM(n,e.value));return}let o=t.getRef(xg),s=t.getRef(Xce),c,l;if(Ad(e)){let[t,r]=sce(e.cause);c=t,l=ji(r)&&(c.status>=500||hd(r.value))?wd(r.value):xM(n,c)}else c=e.value,l=xM(n,c);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=Uce(n);ji(e)&&BA(i,e.value,t.getRef(Kg)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),VA(i,`request`,n.headers,s,o),ji(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,c.status),VA(i,`response`,c.headers,s,o)}i.end(r,l)}),e})),Zce=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return ym(Gj(n),([e,n])=>{let i=nC();nd(i,n);let a=yM.get(r.source),o=n.reasons.length===0?F(e):Zf(n);return a===void 0?(r[CM]=!0,ym(t(r,e),()=>o)):ym(ym(a(r,e),e=>(r[CM]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=yM.get(e.source);return r===void 0?(e[CM]=!0,gm(t(e,n),e=>fj(e)?e:n)):ym(r(e,n),r=>(e[CM]=!0,gm(t(e,r),e=>fj(e)?e:n)))},a=a=>{let o=a.request,s=wp(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:wp(SM(n(s)),{onFailure(e){return nd(nC(),e),CM in o?L:lie(Gj(e),{onFailure(e){return t(o,pj({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return CM in o?L:t(o,e)}})},o=e=>SM(a(e)),s=(e,t,n)=>Bp(n,n=>{if(t.setContext(e.prev),!(wM in e.scope))return Xd(e.scope,e.cause===void 0?n:wd(e.cause))},!0);class c{scope;prev;request;cause;constructor(e,t,n){this.scope=e,this.prev=t,this.request=n}[fr](e,t){let n=i(this.request,e);if(mc(n)&&n._tag===`Success`){if(t.setContext(this.prev),wM in this.scope)return n;let e=Xd(this.scope,n);return e===void 0?n:B(e,()=>n)}return s(this,t,n)}[pr](e,t){return s(this,t,r(this,e))}}return tp(t=>{jl(t);let r=Ud(),i=new c(r,t.context,ca(t.context,_M));t.setContext(ia(i.prev,Hd,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===Qo||bM(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},CM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),wM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),Qce=e=>_M.use(t=>(TM(t,e),L)),TM=Wce,$ce=/*#__PURE__*/ j(2,(e,t)=>_M.use(n=>(TM(n,t),e))),EM=`~effect/http/HttpRouter`,DM=/*#__PURE__*/ P(`effect/http/HttpRouter`),ele=/*#__PURE__*/ R(function*(){let e=yield*rle,t=e.ignoreDuplicateSlashes??!0,n=oj(e),r=/* @__PURE__ */ new Set,i=e=>Dp(r=>{let i=BM(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]:MM({...e[r],handler:a(e[r].handler)}),s={route:o,prefixSegments:ji(o.prefix)?nle(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 DM.of({[EM]:EM,prefixed(e){return e=PM(e),DM.of({...this,prefixed:t=>this.prefixed(FM(t,e)),addAll:t=>i(t.map(ole(e))),add:(t,n,r,a)=>i([MM({method:t,path:FM(n,e),handler:fj(r)?F(r):Vf(r)?r:B(_M,r),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:i,add:(e,t,n,r)=>i([NM(e,t,n,r)]),addGlobalMiddleware:e=>I(()=>{r.add(e)}),asHttpEffect(){let e=tp(e=>{let r=e.context,i=ca(r,_M),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 zj({reason:new ace({request:i})}));let{route:o,prefixSegments:s}=a.handler;if(s!==void 0&&(r=ia(r,_M,tle(i,s,t))),r=ia(r,vM,a.searchParams),r=ia(r,OM,{route:o,params:a.params}),e.getRef(Zo)!==Qo){let e=oa(r,Wo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,o.path)}if(e.setContext(r),!o.uninterruptible){let t=Ml(e);if(t!==void 0)return t}return o.handler});if(r.size===0)return e;for(let t of yte(r))e=t(e);return e}})});function tle(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 nle(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=rj(e,i),r=!1)}return n}const rle=/*#__PURE__*/ ha(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var OM=class extends (/*#__PURE__*/ P()(`effect/http/HttpRouter/RouteContext`)){};const kM=e=>ff(B(DM,e)),AM=(e,t,n,r)=>kM(i=>i.add(e,t,n,r)),ile=/*#__PURE__*/ lf(DM)(ele),ale=e=>Dp(t=>{let n=la(t,Hd),r=rf.forkOrCreate(t);return V(af(bf(e,ile),r,n),e=>la(e,DM).asHttpEffect())}),jM=`~effect/http/HttpRouter/Route`,MM=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?ki(e.prefix):e.prefix??Oi(),[jM]:jM}),NM=(e,t,n,r)=>MM({...r,method:e,path:t,handler:fj(n)?F(n):Vf(n)?n:B(_M,n),uninterruptible:r?.uninterruptible??!1}),PM=e=>e.endsWith(`/`)?e.slice(0,-1):e,FM=/*#__PURE__*/ j(2,(e,t)=>(t=PM(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),ole=/*#__PURE__*/ j(2,(e,t)=>MM({...e,path:FM(e.path,t),prefix:Mi(e.prefix,{onNone:()=>PM(t),onSome:e=>FM(e,t)})})),IM=function(){return arguments.length===0?LM:LM(arguments[0],arguments[1])},LM=(e,t)=>t?.global?ff(R(function*(){let t=yield*DM,n=Vf(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new cle(Vf(e)?df(V(e,e=>$i(/* @__PURE__ */ new Map([[RM,e]])))):sf($i(/* @__PURE__ */ new Map([[RM,e]]))));let sle=0;const RM=`effect/http/HttpRouter/MiddlewareFn`;var cle=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++sle}`;this.layer=df(R({self:this},function*(){let e=yield*Ep(),t=[sa(e,RM)];if(this.dependencies){let n=yield*rf,r=la(e,Hd),i=yield*af(this.dependencies,n,r);t.push(...BM(i))}return $i(/* @__PURE__ */ new Map([[n,t]]))})).pipe(yf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?bf(this.dependencies,t.layer):t.layer)}};const zM=/*#__PURE__*/ new WeakMap,BM=e=>{let t=zM.get(e);if(t)return t;let n=Ma(),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=Da(e).reverse()}return zM.set(e,t),t};(/*#__PURE__*/ IM(qce)).layer;var VM=class extends (/*#__PURE__*/ P()(`effect/workers/Transferable/Collector`)){};const HM=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return VM.of({addAllUnsafe:t,addAll:e=>I(()=>t(e)),readUnsafe:n,read:I(n),clearUnsafe:r,clear:I(r)})},UM=(e,t)=>e===void 0?t:`${e}.${t}`,WM=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),GM=`~effect/rpc/RpcSchema/StreamSchema`;function KM(e){return N(e,GM)}function qM(e){return KM(e)?ki({success:e.success,error:e.error}):Oi()}const lle=/*#__PURE__*/ Sx(_E);function ule(e,t){return Px(lle.ast,{[GM]:GM,success:e,error:t})}var dle=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ ia(xd,{name:`ClientAbort`,stack:Pt,parent:void 0}))};const JM=`~effect/rpc/Rpc`;var YM=class{id;annotations;constructor(e){this.id=e,this.annotations=na()}annotate(e,t){return this.annotations=ia(this.annotations,e,t),this}};const fle={[JM]:JM,pipe(){return Ot(this,arguments)},setSuccess(e){return XM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return XM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return XM({_tag:this._tag,payloadSchema:Fx(e)?e:W(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return XM({_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 XM({_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 XM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ia(this.annotations,e,t)})},annotateMerge(e){return XM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:pa(this.annotations,e)})}},XM=e=>{function t(){}return Object.setPrototypeOf(t,fle),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},J=(e,t)=>{let n=t?.success??Kx,r=t?.error??Vx,i=t?.defect??CS(),a;return a=t?.primaryKey?class extends GS(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:Fx(t?.payload)?t?.payload:t?.payload?W(t?.payload):Kx,XM({_tag:e,payloadSchema:a,successSchema:t?.stream?ule(n,r):n,errorSchema:t?.stream?Vx:r,defectSchema:i,annotations:na(),middlewares:/* @__PURE__ */ new Set})},ZM=/*#__PURE__*/ new WeakMap,QM=e=>{if(ZM.has(e))return ZM.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=qM(t.successSchema);ji(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=IS(ji(r)?Kx:t.successSchema,K([...n]),t.defectSchema);return ZM.set(e,i),i},$M=e=>`~effect/rpc/Rpc/Wrapper`in e,eN=e=>e,ple={_tag:`Eof`},tN=e=>({_tag:`Defect`,defect:e}),mle={_tag:`Pong`},nN=YS;let hle;const rN=e=>(hle??=new TextDecoder).decode(e);var iN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSerialization`)){};const gle=/*#__PURE__*/ iN.of({contentType:`application/json`,includesFraming:!1,codecFor:nN,makeUnsafe:()=>({decode:e=>{let t=JSON.parse(typeof e==`string`?e:rN(e));return Array.isArray(t)?t:[t]},encode:e=>JSON.stringify(e)})}),aN=e=>iN.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:nN,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>_le(JSON.parse(typeof t==`string`?t:rN(t)),e),encode:t=>{let n=vle(t,e);return n&&JSON.stringify(n)}}}});function _le(e,t){if(Array.isArray(e)){let n={size:0,responses:/* @__PURE__ */ new Map},r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!nn(a))continue;let o=oN(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return nn(e)?[oN(e)]:[]}function oN(e){if(Object.hasOwn(e,`method`)){let t=e;if(en(t.id)&&Gt(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 sN(e,t){if(!(`requestId`in e))return cN(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(),cN):void 0):cN(e)}function vle(e,t){if(Array.isArray(e)===!1)return sN(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=sN(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 cN(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:yle,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const yle=-32603,ble=e=>of(iN)(aN(e)),xle=()=>e=>Jf(()=>{let t=jw(1),n=[],r=(...e)=>Dp(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*kp(Jf(()=>e(...t)),r);return n=[],r=e,yield*Vp(Xf,()=>(r=t,L))}))}}))}),Sle=e=>Jf(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>Dp(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*kp(Jf(()=>i(e)),t)}return yield*Vp(Xf,()=>(t.delete(e),r.delete(e),L))})}}))});let Cle=0;const lN=/*#__PURE__*/ H(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Cle++),o=yield*Ep(),s=la(o,Hd),c=/* @__PURE__ */ new Map,l=!1;yield*Kd(s,tp(e=>(l=!0,u(Dd(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=KM(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?fg(s.headers):dg,l=s?.context??na();if(!r){let r=t=>f(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):Xp(UM(n,e._tag),{kind:`client`,attributes:WM(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)=>tp(d=>{if(l)return Wp;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:gg(d.getRef(uN),o)});if(u)return p;let m;return Kp(Yf(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?Qp(r,{captureStackTrace:!1}):M,rm(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),rp(tC(m),h(f,Array.from(e),s))))}),p=H(function*(e,r,o,s,u,d){if(l)return yield*Wp;let f=i?void 0:yield*pie(UM(n,e._tag),{kind:`client`,attributes:WM(e._tag,t.spanAttributes)}),p=nC(),m=a(),g=ca(p.context,Hd),_=yield*XC(u);return yield*Gd(g,e=>(sw(_),c.has(m)?(c.delete(m),h(m,Ad(e)?Array.from(lre(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:gg(p.getRef(uN),s)}).pipe(f?Qp(f,{captureStackTrace:!1}):M,zp(e=>nw(_,e)),Gp,em(g,{startImmediately:!0})),_}),m=e=>{let t=[];for(let n of e.middlewares.values()){let e=sa(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)=>Yf(i=>{let a=nC();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(aie(1e3),rm(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,dp(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(Ed(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=>{ir(_,e._tag,d(e))});return{client:_,write:g}});let wle=0;const Tle=/*#__PURE__*/ H(function*(e,t){let n=wle++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*dN,c=Ele(r),l=xoe(r(CS())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):L,{client:f,write:p}=yield*lN(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?HM():void 0,o=nC(),l={rpc:r,context:i?ia(o.context,VM,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(kp(l.context),hp,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=eN(e.requestId),n=u.get(t);if(!n||Ai(n.schemas.decodeChunk))return L;let r=n.schemas.decodeChunk.value;return Jp(i=>i(r(e.values).pipe(kp(n.context),hp,B(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(zp(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:wd(e)}).pipe(rp(hd(e)?L:vp(d(t))))),rie(e=>!hd(e),()=>L)))}case`Exit`:{let t=eN(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(kp(n.context),hp,wp({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:wd(e)})}))):L}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=Td(e.error);return Uf(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return L}}).pipe(dp(dm),Gp,tm),f}),Ele=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=qM(n.successSchema);return r={decodeChunk:zi(i,t=>Dx(e(Qx(t.success)))),encodePayload:jx(e(n.payloadSchema)),decodeExit:Dx(e(QM(n)))},t.set(n,r),r}},uN=/*#__PURE__*/ ha(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>dg});var dN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcClient/Protocol`)){static make=Sle};const Dle=/*#__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*Ep(),l=la(c,Hd),u=rC(Jd(l,`parallel`)),d=o===`unbounded`?void 0:yield*Pw(o),f=/* @__PURE__ */ new Map,p=!1,m=iC(!1);yield*Kd(l,tp(e=>{p=!0;for(let t of f.values())if(t.ended=!0,t.fibers.size===0)u(rm(c)(_(t)));else for(let n of t.fibers.values())n.interruptUnsafe(e.id);return f.size===0?L:m.await}));let h=e=>tp(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)=>fp(tp(i=>{if(p)return Wp;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new YM(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`&&n._tag!==`Ack`||!a.fibers.has(n.requestId)))return Wp;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?cp(e.open):L}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,dle.annotation),L):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:Dd()})}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?rp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return Wp;let p=e.requests.get(l.tag),m=sa(c,p?.key);if(!p||!m){let e=fp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Ed(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:Rp(e,_(o))}let h=KM(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=$M(v),S=x&&v.fork,ee=x&&v.uninterruptible,C=x?v.value:v,te,ne=h?y(o,l,C,e=>{te=e}):C,w=p.middlewares.size===0?ne:h?B(op(_N(c,ne,g)),e=>te?Zf(te):e):_N(c,ne,g),T=!1,re=Ud(),ie,ae=Vp(w,e=>{T=!0;let n;if(e._tag===`Success`)gre(e.value)?(ie=e.value,n=L):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});else if(te)return Xd(re,e)??L;else n=!s&&md(e.cause)&&!hd(e.cause)?b(o,pd(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=Xd(re,e);return e._tag===`Failure`&&nd(nC(),e.cause),r?Rp(n,r):n});if(f?.onRequest&&(ae=f.onRequest(ae)),n){let e=oa(i.context,Wo);ae=Zp(ae,UM(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:WM(l.tag,t.spanAttributes),parent:r&&l.spanId?Ko({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=rm(ia(Ale(m,i.context),Hd,re));return u(oe(tp(e=>(o.fibers.set(l.id,e),ae)),ee?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ie){let n=u(oe(Vp(Fd(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:Dd()}))),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=>zp(t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r}),e=>(ore(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))),Vf(r)?r.pipe(B(e=>Wf({while:Mt,body:jt(B(cw(e),e=>{let t=o(e);return s?(s.closeUnsafe(),B(t,()=>s.await)):t})),step:Ft})),Mf(()=>L),Fp):QE(r,e=>{let t=o(e);return s?(s.closeUnsafe(),rp(t,s.await)):t})},b=(e,n)=>Jf(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?rp(i,_(e)):i});return M({write:g,disconnect:h})}),fN=e=>e===gle.codecFor,pN=/*#__PURE__*/ new WeakMap,Ole=(e,t)=>{let n=fN(e),r=n?pN.get(t):void 0;if(r===void 0){let i=qM(t.successSchema);r={decode:Dx(e(t.payloadSchema)),encodeChunk:Ax(e(Qx(ji(i)?i.value.success:Hx))),encodeExit:Ax(e(QM(t)))},n&&pN.set(t,r)}return r};let kle;const mN=e=>({encodeDefectUnsafe:Nx(e(CS())),encodeUnknownRequestExit:Ax(e(IS(Vx,Vx,CS())))}),hN=e=>fN(e)?kle??=mN(e):mN(e),gN=/*#__PURE__*/ new WeakMap,Ale=(e,t)=>{let n=gN.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,gN.set(e,n));let r=n.get(t);return r===void 0&&(r=pa(e.context,t),n.set(t,r)),r},_N=(e,t,n)=>{for(let r of n.rpc.middlewares)t=ca(e,r)(t,n);return t},jle=/*#__PURE__*/ H(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*vN,{encodeDefectUnsafe:u,encodeUnknownRequestExit:d}=hN(n),f=yield*Ep(),p=yield*Sre(),m=yield*Dle(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(Wd(p));yield*$p(Wf({while:Mt,body:jt(B(dw(r),e=>(_.delete(e),m.disconnect(e)))),step:Ft}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=sa(f,e.key);t={tag:e._tag,...Ole(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=Sd(r)&&kd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):B(lp(kp(a?Np(r,VM,a):r,n.context),e=>tp(t=>{let r=ld(`Failed to encode response for RPC "${n.tag}": ${z_(e.issue)}`);return nd(t,r),s=!0,Zf(r)})),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return dp(c,r=>(e.schemas.delete(t),rp(b(e,t,n.encodeExit,pd(r)),s?Zf(r):m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))))},b=(e,t,n,r)=>dp(B(n(Ed(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,pd(t))),x=(e,t)=>dp(o(e.id,tN(u(t))),e=>mm(pm(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:HM()}:n);let a=r;return a.id=t,a.payload=i,a.headers=fg(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=eN(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 Sd(s)&&kd(s)?S(r,i,o,n,s.value):Tp(kp(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,z_(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return dp(o(r.id,mle),e=>x(r,pd(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:eN(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(_p(e=>lm(`BUG: RpcServer protocol crashed`,e)),Vp(e=>Yd(p,e)))});var vN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ xle()};const yN=/*#__PURE__*/ H(function*(e={}){let t=yield*iN,{encodeDefectUnsafe:n}=hN(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=ca(d.context,_M),p=ca(d.context,Hd),m=Object.entries(f.headers),h=yield*hp(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(tN(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?L:QC(_,e),end:iw(_)};yield*Gd(p,()=>(c.delete(g),l.delete(g),$C(a,g),_.state._tag===`Done`?L:rp(ow(_),Uf(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(eN(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(tN(n(e)))}if(yield*o(g,ple),!r){let e=yield*lw(_),n=v.encode(e);return _j(n===void 0?``:n,{contentType:t.contentType})}let S=yield*Mf(cw(_),()=>F([]));return _.state._tag===`Done`?hj(Mle(S),{contentType:t.contentType}):bj(OE(S).pipe(PE(kE(_))),{contentType:t.contentType})});return{protocol:yield*vN.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:qf,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),Mle=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},Nle={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return bN({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 bN({requests:t,annotations:$i(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return bN({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 bN({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return R(function*(){let n=yield*Ep(),r=Vf(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})}),$i(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 bN({requests:t,annotations:this.annotations})},toLayer(e){return df(this.toHandlers(e))},of:M,toLayerHandler(e,t){let n=this;return df(R(function*(){let r=yield*Ep(),i=Vf(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),$i(a)}))},accessHandler(e){return Dp(t=>{let n=this.requests.get(e),{handler:r,context:i}=sa(t,n.key);return F((e,t)=>{t.rpc=n;let a=r(e,t),o=$M(a)?a.value:a;return Vf(o)?Op(o,i):JE(o,i)})})},annotate(e,t){return bN({requests:this.requests,annotations:ia(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(ra(e,t))},annotateMerge(e){return bN({requests:this.requests,annotations:pa(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(pa(e,r.annotations)));return bN({requests:t,annotations:this.annotations})}},bN=e=>Object.assign(function(){},Nle,{requests:e.requests,annotations:e.annotations}),xN=(...e)=>bN({requests:new Map(e.map(e=>[e._tag,e])),annotations:na()}),Ple=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},Fle=/* @__PURE__ */ of(aO,/* @__PURE__ */ oO({randomBytes:it.randomBytes,digest:(e,t)=>ep({try:()=>Uint8Array.from(it.createHash(Ple(e)).update(t).digest()),catch:e=>IT({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),SN=e=>t=>LT({module:`FileSystem`,method:e,description:t.message??String(t)}),CN=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},wN=e=>Bi(Fi(e),Vm),TN=e=>BigInt.asUintN(64,e),EN=e=>zi(Fi(e),TN),DN=(e,t)=>ep({try:()=>CN(e,`position`),catch:SN(t)}),Ile=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.access,/*#__PURE__*/ Ck(`FileSystem`,`access`),/*#__PURE__*/ SN(`access`));return(t,n)=>{let r=Ct.constants.F_OK;return n?.readable&&(r|=Ct.constants.R_OK),n?.writable&&(r|=Ct.constants.W_OK),e(t,r)}})(),Lle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.cp,/*#__PURE__*/ Ck(`FileSystem`,`copy`),/*#__PURE__*/ SN(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),Rle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.copyFile,/*#__PURE__*/ Ck(`FileSystem`,`copyFile`),/*#__PURE__*/ SN(`copyFile`));return(t,n)=>e(t,n)})(),zle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.chmod,/*#__PURE__*/ Ck(`FileSystem`,`chmod`),/*#__PURE__*/ SN(`chmod`));return(t,n)=>e(t,n)})(),Ble=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.chown,/*#__PURE__*/ Ck(`FileSystem`,`chown`),/*#__PURE__*/ SN(`chown`));return(t,n,r)=>e(t,n,r)})(),Vle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.glob,/*#__PURE__*/ Ck(`FileSystem`,`glob`),/*#__PURE__*/ SN(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),Hle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.link,/*#__PURE__*/ Ck(`FileSystem`,`link`),/*#__PURE__*/ SN(`link`));return(t,n)=>e(t,n)})(),Ule=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.mkdir,/*#__PURE__*/ Ck(`FileSystem`,`makeDirectory`),/*#__PURE__*/ SN(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),ON=e=>{let t=hm(Ct.mkdtemp,Ck(`FileSystem`,e),SN(e));return e=>Jf(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?st.join(e.directory,`.`):ht.tmpdir();return t(n?st.join(r,n):r+`/`)})},Wle=/*#__PURE__*/ ON(`makeTempDirectory`),kN=e=>{let t=hm(Ct.rm,Ck(`FileSystem`,e),SN(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},Gle=/*#__PURE__*/ kN(`remove`),Kle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ON(`makeTempDirectoryScoped`),t=/*#__PURE__*/ kN(`makeTempDirectoryScoped`);return n=>Ip(e(n),e=>hp(t(e,{recursive:!0})))})(),qle=e=>{let{O_APPEND:t,O_CREAT:n,O_EXCL:r,O_RDONLY:i,O_RDWR:a,O_TRUNC:o,O_WRONLY:s}=Ct.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}},Jle=(e,t)=>Jf(()=>{let{O_NOFOLLOW:n}=Ct.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(qle(t)|n)}),Yle=/*#__PURE__*/ (e=>{let t=hm(Ct.open,Ck(`FileSystem`,e),SN(e)),n=hm(Ct.close,Ck(`FileSystem`,e),SN(e));return(r,i)=>It(Ip(i?.noFollow===!0?B(Jle(e,i.flag??`r`),e=>t(r,e,i.mode)):t(r,i?.flag??`r`,i?.mode),e=>hp(n(e))),V(e=>Xle(e,i?.flag?.startsWith(`a`)??!1)))})(`open`),AN=e=>LT({module:`FileSystem`,method:e,description:`Cannot read before the start of the file`}),Xle=/*#__PURE__*/ (()=>{let e=e=>hm(Ct.read,Ck(`FileSystem`,e),SN(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ hm(Ct.fstat,/*#__PURE__*/ Ck(`FileSystem`,`stat`),/*#__PURE__*/ SN(`stat`)),i=/*#__PURE__*/ hm(Ct.ftruncate,/*#__PURE__*/ Ck(`FileSystem`,`truncate`),/*#__PURE__*/ SN(`truncate`)),a=/*#__PURE__*/ hm(Ct.fsync,/*#__PURE__*/ Ck(`FileSystem`,`sync`),/*#__PURE__*/ SN(`sync`)),o=e=>hm(Ct.write,Ck(`FileSystem`,e),SN(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}),MN)}get sync(){return a(this.fd)}seek(e,t){return Jf(()=>{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 Jf(()=>{let r=n?.position;if(r!==void 0)return r<BigInt(0)?z(AN(`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 Jf(()=>{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(AN(`readAlloc`));let i=Buffer.allocUnsafeSlow(e),a=r??this.position;return V(n(this.fd,{buffer:i,position:a}),t=>{if(t===0)return Oi();if(r===void 0&&(this.position=a+BigInt(t)),t===e)return ki(i);let n=Buffer.allocUnsafeSlow(t);return i.copy(n,0,0,t),ki(n)})}catch(e){return z(SN(`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 Jf(()=>{let t=this.position;return B(this.append?F(void 0):DN(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 Jf(()=>{let t=this.position;return B(this.append?F(void 0):DN(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)})(),jN=e=>{let t=ON(e);return H(function*(e){let n=yield*t(e),r=it.randomBytes(6).toString(`hex`),i=st.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*PN(i,/* @__PURE__ */ new Uint8Array),i})},Zle=/*#__PURE__*/ jN(`makeTempFile`),Qle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ jN(`makeTempFileScoped`),t=/*#__PURE__*/ kN(`makeTempFileScoped`);return n=>Ip(e(n),e=>hp(t(st.dirname(e),{recursive:!0})))})(),$le=(e,t)=>Kf({try:()=>Ct.promises.readdir(e,t),catch:t=>Ck(`FileSystem`,`readDirectory`)(t,[e])}),eue=e=>Yf((t,n)=>{try{Ct.readFile(e,{signal:n},(n,r)=>{t(n?z(Ck(`FileSystem`,`readFile`)(n,[e])):F(r))})}catch(e){t(z(SN(`readFile`)(e)))}}),tue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.readlink,/*#__PURE__*/ Ck(`FileSystem`,`readLink`),/*#__PURE__*/ SN(`readLink`));return t=>e(t)})(),nue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.realpath,/*#__PURE__*/ Ck(`FileSystem`,`realPath`),/*#__PURE__*/ SN(`realPath`));return t=>e(t)})(),rue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.rename,/*#__PURE__*/ Ck(`FileSystem`,`rename`),/*#__PURE__*/ SN(`rename`));return(t,n)=>e(t,n)})(),MN=e=>ep({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:Fi(e.mtime),atime:Fi(e.atime),birthtime:Fi(e.birthtime),dev:TN(e.dev),rdev:EN(e.rdev),ino:EN(e.ino),mode:CN(e.mode,`mode`),nlink:EN(e.nlink),uid:wN(e.uid),gid:wN(e.gid),size:ah(e.size),blksize:e.blksize===void 0?Oi():ki(ah(e.blksize)),blocks:Fi(e.blocks)}),catch:SN(`stat`)}),NN=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.stat,/*#__PURE__*/ Ck(`FileSystem`,`stat`),/*#__PURE__*/ SN(`stat`));return t=>B(e(t,{bigint:!0}),MN)})(),iue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.symlink,/*#__PURE__*/ Ck(`FileSystem`,`symlink`),/*#__PURE__*/ SN(`symlink`));return(t,n)=>e(t,n)})(),aue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.truncate,/*#__PURE__*/ Ck(`FileSystem`,`truncate`),/*#__PURE__*/ SN(`truncate`));return(t,n)=>e(t,n)})(),oue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ hm(Ct.utimes,/*#__PURE__*/ Ck(`FileSystem`,`utime`),/*#__PURE__*/ SN(`utime`));return(t,n,r)=>e(t,n,r)})(),sue=(e,t,n)=>wE(r=>Ip(I(()=>{let i=t.type===`Directory`?e:st.dirname(e),a=Ct.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:nm(Tp(NN(st.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,cd(IT({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{aw(r)}),a}),e=>I(()=>e.close())).pipe(ip(()=>I(()=>n?.onReady?.())))),cue=(e,t,n)=>Hf([NN(t),jp(oD)]).pipe(V(([r,i])=>Pi(i,()=>e).pipe(Bi(e=>e.register(t,r,n)),Ni(()=>sue(t,r,n)))),jE),PN=(e,t,n)=>Yf((r,i)=>{try{Ct.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?z(Ck(`FileSystem`,`writeFile`)(t,[e])):L)})}catch(e){r(z(SN(`writeFile`)(e)))}}),lue=/*#__PURE__*/ V(/*#__PURE__*/ jp(oD),e=>iD({access:Ile,chmod:zle,chown:Ble,copy:Lle,copyFile:Rle,glob:Vle,link:Hle,makeDirectory:Ule,makeTempDirectory:Wle,makeTempDirectoryScoped:Kle,makeTempFile:Zle,makeTempFileScoped:Qle,open:Yle,readDirectory:$le,readFile:eue,readLink:tue,realPath:nue,remove:Gle,rename:rue,stat:NN,symlink:iue,truncate:aue,utimes:oue,watch(t,n){return cue(e,t,n)},writeFile:PN})),FN=/* @__PURE__ */ lf(rD)(lue),IN=/*#__PURE__*/ new TextDecoder;var uue=class extends $n{[NA];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[NA]=NA,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return fg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??Fi(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=V(this.arrayBuffer,e=>IN.decode(e)),this.textEffect}get textUnsafe(){return am(this.text)}get json(){return B(this.text,e=>ep({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return am(this.json)}get urlParamsBody(){return B(this.text,e=>ep({try:()=>Dg(new URLSearchParams(e)),catch:this.onError}))}get stream(){return Dk({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect||(this.arrayBufferEffect=tp(e=>jk(()=>this.source,{onError:this.onError,maxBytes:e.getRef(FA)})).pipe(Hp,am),this.textEffect=V(this.arrayBufferEffect,e=>IN.decode(e))),this.arrayBufferEffect}};const LN=/*#__PURE__*/ ha(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var RN=class extends (/*#__PURE__*/ P()(`effect/http/FetchHttpClient/RequestInit`)){};const zN=/*#__PURE__*/ Cse(/*#__PURE__*/ F(/* @__PURE__ */ gse((e,t,n,r)=>{let i=r.getRef(LN),a=oa(r.context,RN)??{},o=a.headers?gg(fg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=_g(o,`content-length`));let s=r=>V(Kf({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 lA({reason:new pA({request:e,cause:t})})}),t=>nse(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)}))),due=/*#__PURE__*/ new Set(typeof Tt.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),BN=(e,t)=>{let n={};return e!==void 0&&(n[Tt.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[Tt.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},VN=e=>e===void 0||e===3?void 0:{params:{[Tt.constants.ZSTD_c_compressionLevel]:e}},fue=(e,t,n)=>Yf(r=>{let i=(e,t)=>r(e===null?F(t):$f(e));switch(t){case`gzip`:Tt.gzip(e,{level:n?.level},i);break;case`deflate`:Tt.deflate(e,{level:n?.level},i);break;case`br`:Tt.brotliCompress(e,BN(n?.level,e.byteLength),i);break;case`zstd`:{let t=VN(n?.level);t===void 0?Tt.zstdCompress(e,i):Tt.zstdCompress(e,t,i);break}}}),pue=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?V(fue(i.body,n,r),e=>xj(Ej(t,Qk(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),HN=(e,t)=>{switch(e){case`gzip`:return Tt.createGzip({level:t?.level,flush:Tt.constants.Z_SYNC_FLUSH});case`deflate`:return Tt.createDeflate({level:t?.level,flush:Tt.constants.Z_SYNC_FLUSH});case`br`:return Tt.createBrotliCompress({...BN(t?.level),flush:Tt.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return Tt.createZstdCompress({...VN(t?.level),flush:Tt.constants.ZSTD_e_flush})}},UN=(e,t)=>{let n;return new yt({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)}})},WN=(e,t)=>Sj(Ej(e,t),`content-length`),mue=/*#__PURE__*/ ece({platform:`node`,compression:/* @__PURE__ */ pue({algorithms:due,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return F(WN(e,sA(Ak(r.stream,{evaluate:()=>HN(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof yt?r.body:void 0,a=UN(()=>{let e=HN(t,n);return i??=yt.fromWeb(new Response(r.body).body),bt(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return F(WN(e,Xk(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return F(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=UN(()=>o===BigInt(0)?yt.from([]):Ct.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return yj(s,{headers:{...r,"content-type":r[`content-type`]??Ni(jj(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return yj(UN(()=>yt.fromWeb(e.stream())),{headers:gg(r,pg({"content-type":r[`content-type`]??(e.type===``?Ni(jj(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),hue=/*#__PURE__*/ It(/*#__PURE__*/ lf(Mj)(mue),/*#__PURE__*/ yf(FN),/*#__PURE__*/ yf(zse));var gue=class extends _t{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=Ece({...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 vue(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 _ue=e=>new gue(e);var vue=class extends yt{_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 GN=(e,t)=>Nce(t).pipe(V(t=>Dk({evaluate(){let n=_ue(t);return e.pipe(n),n},onError:e=>Cue(e)})),jE,ME(bue)),yue=(e,t)=>Rce(GN(e,t),(e,t)=>Kf({try:n=>mee.pipeline(t.file,Ct.createWriteStream(e),{signal:n}),catch:e=>uM.fromReason(`InternalError`,e)})),bue=e=>e._tag===`Field`?new xue(e.info,e.value):new Sue(e);var KN=class extends $n{[cM];constructor(){super(),this[cM]=cM}},xue=class extends KN{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=Oce(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Sue=class extends KN{_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=Dk({evaluate:()=>e,onError:e=>uM.fromReason(`InternalError`,e)}),this.contentEffect=Mk(()=>e,{onError:e=>uM.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Cue(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return uM.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return uM.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return uM.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return uM.fromReason(`BodyTooLarge`,e)}default:return uM.fromReason(`Parse`,e)}}const qN=e=>({fromFileUrl:t=>ep({try:()=>ft.fileURLToPath(t,{windows:e}),catch:e=>new NT({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>ep({try:()=>ft.pathToFileURL(t,{windows:e}),catch:e=>new NT({module:`Path`,method:`toFileUrl`,cause:e})})});({...st.posix,.../*#__PURE__*/ qN(!1)}),{...st.win32,.../*#__PURE__*/ qN(!0)};const wue=/* @__PURE__ */ of(cD)(/*#__PURE__*/ lD({...st,.../*#__PURE__*/ qN(void 0)})),Tue=/* @__PURE__ */ of(JO,/*#__PURE__*/ YO({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=>wk({evaluate:()=>process.stdout,onError:e=>IT({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>wk({evaluate:()=>process.stderr,onError:e=>IT({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ Dk({evaluate:()=>process.stdin,onError:e=>IT({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),Eue=/*#__PURE__*/ lf($O,/*#__PURE__*/ (/* @__PURE__ */ H(function*(e=JN){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*Lp(()=>I(()=>t.off(`end`,o)));let s=yield*hE({acquire:Ip(I(()=>{let e=Et.createInterface({input:t,escapeCodeTimeout:50}),n=e=>$C(r,e),i=()=>{a=!1,aw(r)};return a=!0,Et.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:Ii(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*Lp(()=>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=Jf(()=>fw(r).pipe(B(Mi({onNone:()=>Fp(rp(gE(s),dw(r))),onSome:F})),mp(()=>new QO({}))));return ek({columns:c,rows:l,readInput:u,readLine:d,display:e=>qp(Yf(t=>{n.write(e,e=>en(e)?t(L):t(z(LT({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(JN));function JN(e){let t=e.key;return t.name===`escape`||t.ctrl&&(t.name===`c`||t.name===`d`)}const Due=/*#__PURE__*/ bf(Hk,/*#__PURE__*/ gf(FN,Fle,wue,Tue,Eue)),Oue=(e,t)=>{let n=Zce(e,Mue,t.middleware);return tp(e=>{let r=e.context;return F(function(i,a){let o=ia(r,_M,new kue(i,a)),s=rC(rm(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,Hj.annotation)})})})};var kue=class e extends uue{[gM];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new zj({reason:new Bj({request:this,cause:e})}),a),this[gM]=gM,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Zh(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||=am(Hp(yue(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return GN(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??z(new zj({reason:new Bj({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${Rg(this.url)})`}toJSON(){return IA(this,{_id:`HttpServerRequest`,method:this.method,url:Rg(this.originalUrl)})}};const Aue=/*#__PURE__*/ gf(hue,Bse,Due),jue=/*#__PURE__*/ pj({status:101}),Mue=(e,t)=>{if(e.upgraded)return F(jue);let n=e.resolvedResponse;if(n.writableEnded)return L;let r=t.headers;if(!Lh(t.cookies)){r={...r};let e=Xh(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),rp(Nue(t.body),Yf(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`?Kf({try:e=>hee(i.body,n,{signal:e,end:!0}),catch:n=>new zj({reason:new Vj({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(Gp,_p(YN(n,t))):Yf(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):Yf(e=>{n.end(i.text??i.body,()=>e(L))});case`FormData`:return Jf(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),Yf((r,i)=>{yt.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(z(new zj({reason:new Vj({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(L)})}).pipe(Gp,_p(YN(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)}),Gp,wp({onSuccess:()=>I(()=>n.end()),onFailure:YN(n,t)}))}}},Nue=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof yt?I(()=>t.destroy()):L},YN=(e,t)=>n=>B(Gj(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),Zf(a?sre(n,ld(t)):i)}),Pue={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},Fue=e=>Pue[e],XN=new TextEncoder,ZN=new TextDecoder,QN=new TextDecoder(`utf-8`,{fatal:!0}),$N=2**32;function eP(...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 tP(e,t,n){if(t<0||t>=$N)throw RangeError(`value must be >= 0 and <= ${$N-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function nP(e){let t=Math.floor(e/$N),n=e%$N,r=/* @__PURE__ */ new Uint8Array(8);return tP(r,t,0),tP(r,n,4),r}function rP(e){let t=/* @__PURE__ */ new Uint8Array(4);return tP(t,e),t}const Iue=/[^\x00-\x7f]/;function iP(e){if(typeof e==`string`&&e.length>=128){if(Iue.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return XN.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 Lue(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 Rue(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 aP(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var oP=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)}},sP=class extends oP{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}},cP=class extends oP{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}},lP=class extends oP{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},uP=class extends oP{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},dP=class extends oP{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},fP=class extends oP{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},pP=class extends oP{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},mP=class extends oP{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},hP=class extends oP{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},gP=class extends oP{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},_P=class extends oP{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)}},vP=class extends oP{[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)}},yP=class extends oP{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},zue=class extends oP{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function bP(e){try{return Rue(typeof e==`string`?e:ZN.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function xP(e){return Lue(typeof e==`string`?XN.encode(e):e,!0)}function SP(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function CP(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 wP(e){return CP(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(CP)}function TP(...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 EP(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function DP(e,t,n){try{return bP(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function OP(e,t,n){try{return iP(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function kP(e,t,n){let r;try{r=JSON.parse(QN.decode(bP(e)))}catch{throw new t(n)}if(!CP(r))throw new t(n);return r}const AP={__proto__:null,b64:!0},jP={__proto__:null};function MP(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 NP(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 PP(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 uP(`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 FP(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new pP(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function IP(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(!CP(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}const Bue=e=>e[Symbol.toStringTag],Vue=(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 LP(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(CP(t)){if(o=ZP(t),typeof o.kty!=`string`)throw GP(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(Vue(e,o,n),o.kty===`oct`)return bP(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!HP(t))throw GP(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Bue(t)} instances must be of type "${e}" for the ${r} algorithm`);if(BP(t))return t;if(s=t,s.type===`secret`)return s.export()}RP||=/* @__PURE__ */ new WeakMap;let c=t,l=RP.get(c);if(l?.[r])return l[r];if(l||RP.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Hue[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 $P(e,o)}let RP;const Hue={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function zP(e){if(!BP(e))throw Error(`CryptoKey instance expected`)}const BP=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},VP=e=>e?.[Symbol.toStringTag]===`KeyObject`,HP=e=>BP(e)||VP(e);function UP(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 WP=(e,...t)=>UP(`Key must be `,e,...t);function GP(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(UP(`Key for the ${e} algorithm must be `,t,...r))}const KP=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function qP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function JP(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 YP(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw KP(t.name);if(t.hash&&r.hash?.name!==t.hash)throw KP(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw KP(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw KP(t.length,`algorithm.length`);qP(e,n)}function XP(e){return{__proto__:null,...e}}function ZP(e){let t=XP(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 $P(e,t,n){if(!e.kty.includes(t.kty))throw new uP(`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 eF(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),YP(e,t,n),e}const tF=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function nF(e,t){let n=e.byteLength<<3;if(n!==t)throw new fP(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}const Uue=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function rF(e,t){if(t.length<<3!==e.ivBits)throw new fP(`Invalid Initialization Vector length`)}async function iF(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(WP(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 aF(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function Wue(e,t,n,r,i){let[a,o,s]=await iF(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await aF(o,eP(i,r,c,nP(i.length*8)),s),iv:r}}async function Gue(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 Kue(e,t,n,r,i,a){let[o,s,c]=await iF(e,t,`decrypt`),l=await aF(s,eP(a,r,n,nP(a.length*8)),c);try{if(await Gue(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new dP}async function oF(e,t,n,r,i){if(!BP(n)&&!(n instanceof Uint8Array))throw TypeError(WP(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?rF(e,r):r=Uue(e),n instanceof Uint8Array&&nF(n,e.cekBits),e.cbc)return Wue(e,t,n,r,i);let a=await eF(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 sF(e,t,n,r,i,a){if(!BP(t)&&!(t instanceof Uint8Array))throw TypeError(WP(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new fP(`JWE Initialization Vector missing`);if(!i)throw new fP(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new fP(`Invalid Authentication Tag length`);if(rF(e,r),t instanceof Uint8Array&&nF(t,e.cekBits),e.cbc)return Kue(e,t,n,r,i,a);let o=await eF(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,eP(n,i)))}catch{throw new dP}}function cF(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const que=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],Jue=[[],[`deriveBits`]],lF=[[],[]];function uF(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:que,ops:[`wrapKey`,`unwrapKey`]}}function dF(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 uP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:Jue,ops:[void 0,`deriveBits`]}}function fF(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:lF,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function pF(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:lF,ops:[`deriveBits`,`deriveBits`]}}const mF=cF({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:lF,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":uF(1),"RSA-OAEP-256":uF(256),"RSA-OAEP-384":uF(384),"RSA-OAEP-512":uF(512),"ECDH-ES":dF(`direct-key-agreement`),"ECDH-ES+A128KW":dF(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":dF(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":dF(`key-agreement-with-key-wrapping`),A128KW:fF(128),A192KW:fF(192),A256KW:fF(256),A128GCMKW:fF(128,!0),A192GCMKW:fF(192,!0),A256GCMKW:fF(256,!0),"PBES2-HS256+A128KW":pF(),"PBES2-HS384+A192KW":pF(),"PBES2-HS512+A256KW":pF()}),Yue=[`encrypt`,`decrypt`];function hF(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:lF,ops:Yue,cekBits:e,ivBits:t?128:96,cbc:t}}const Xue=cF({A128GCM:hF(128),A192GCM:hF(192),A256GCM:hF(256),"A128CBC-HS256":hF(256,!0),"A192CBC-HS384":hF(384,!0),"A256CBC-HS512":hF(512,!0)});function gF(e,t){throw new uP(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function _F(e){return(typeof e==`string`?mF[e]:void 0)??gF(`alg`,`Algorithm`)}function vF(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function yF(e){return(typeof e==`string`?Xue[e]:void 0)??gF(`enc`,`Encryption Algorithm`)}function bF(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`);qP(e,t)}async function Zue(e,t,n){let r=await eF(t,_F(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 Que(e,t,n){let r=await eF(t,_F(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 xF(e,t,n){YP(t,_F(e).subtle,n),JP(e,t)}async function SF(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new fP(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new fP(`PBES2 Count Input must be a positive integer`);let i=eP(iP(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 eF(r,_F(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function CF(e){return eP(rP(e.length),e)}async function $ue(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 aP(`sha256`,eP(rP(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function wF(e,t,n,r,i=/* @__PURE__ */ new Uint8Array,a=/* @__PURE__ */ new Uint8Array){bF(e),bF(t,`deriveBits`);let o=eP(CF(iP(n)),CF(i),CF(a),rP(r));return $ue(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 TF(e){zP(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new uP(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function EF(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new fP(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return DP(n,t,fP)}}function DF(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 fP(`JOSE Header "apu" and "apv" values must be distinct`)}}function ede(e){if(e===void 0)throw new fP(`JWE Encrypted Key missing`)}function OF(e){if(e!==void 0)throw new fP(`Encountered unexpected JWE Encrypted Key`)}function tde(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 nde(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return OF(r),n;let c=s===`direct-key-agreement`;switch(c?OF(r):ede(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!CP(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new fP(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);TF(n);let a=await $P(e,r),s=EF(i,`apu`),l=EF(i,`apv`);DF(s,l);let u=await wF(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 zP(n),xF(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new fP(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);tde(a);let e=a??1e4;if(i.p2c>e)throw new fP(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new fP(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await SF(DP(i.p2s,`p2s`,fP),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new fP(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new fP(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=DP(i.iv,`iv`,fP),t=DP(i.tag,`tag`,fP);if(e.byteLength!==12)throw new fP(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new fP(`Invalid Authentication Tag length`);return sF(yF(o.slice(0,-2)),n,r,e,t,/* @__PURE__ */ new Uint8Array)}}return Que(o.slice(-6),n,r)}async function rde(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=vF(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await LP(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??tF(t):void 0;u&&nF(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{TF(l);let{apu:n,apv:i}=a;n!==void 0&&SP(n,`"apu"`),i!==void 0&&SP(i,`"apv"`);let c=n??EF(r,`apu`),u=i??EF(r,`apv`);DF(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await LP(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 wF(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=xP(n)),i!==void 0&&(f.apv=xP(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:zP(l),xF(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 SF(t,o,e,l),f={p2c:e,p2s:xP(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 oF(yF(o.slice(0,-2)),u,l,e,/* @__PURE__ */ new Uint8Array);d=t.ciphertext,f={iv:xP(t.iv),tag:xP(t.tag)}}}if(d??=await Zue(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 kF(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new uP(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new fP(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function AF(e){if(typeof globalThis[e]>`u`)throw new uP(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function jF(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 fP(`Decompressed plaintext exceeded the configured limit`)}return eP(...i)}async function ide(e){return AF(`CompressionStream`),jF(new CompressionStream(`deflate-raw`),e)}async function ade(e,t){return AF(`DecompressionStream`),jF(new DecompressionStream(`deflate-raw`),e,t)}function ode(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=kP(t,fP,`JWE Protected Header is invalid`)),[o,DP(n,`ciphertext`,fP),r===void 0?void 0:DP(r,`iv`,fP),i===void 0?void 0:DP(i,`tag`,fP),OP((t??``)+(a===void 0?``:`.${a}`),`aad`,fP)]}function sde(e){return[e&&MP(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&MP(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function cde(e,t,n,r=ode(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!TP(i,l,u))throw new fP(`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;PP(fP,jP,h,i,f),kF(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new fP(`missing JWE Algorithm (alg) in JWE Header`);let x=mF[y];if(v===``&&(!x||!vF(x)))throw new fP(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new fP(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new lP(`"alg" (Algorithm) Header Parameter value not allowed`);let ee;if(S){if(b!==void 0)throw new fP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new fP(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new fP(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new lP(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);ee=yF(b)}let C;if(v!==void 0)try{C=DP(v,`encrypted_key`,fP)}catch(e){if(!x||!vF(x))throw e;C=/* @__PURE__ */ new Uint8Array}let te=!1;typeof n==`function`&&(n=await n(i,e),te=!0);let ne=x??_F(y);vF(ne)&&C===void 0&&(C=/* @__PURE__ */ new Uint8Array);let w=await LP(ne.mode===`direct-encryption`?ee:ne,n,`decrypt`),T;if(ne.mode===`integrated-encryption`)T=await ne.decrypt(w,C,a,c,i,f);else{let e=ee,t;try{t=await nde(ne,e,w,C,f,g),vF(ne)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=tF(e))}catch(n){if(n instanceof TypeError||n instanceof fP||n instanceof uP)throw n;t=tF(e)}T=await sF(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new uP(`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 ade(T,e).catch(e=>{throw e instanceof fP?e:new fP(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:DP(d,`aad`,fP)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...te&&{key:w}}}async function lde(e,t,n){if(e instanceof Uint8Array&&(e=ZN.decode(e)),typeof e!=`string`)throw new fP(`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 fP(`Invalid Compact JWE`);return cde({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function MF(e,t,n){if(!TP(e,t,n))throw new fP(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function ude(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new fP(`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&&SP(o,`JWE Additional Authenticated Data`),s!==void 0&&SP(s,`JWE Content Encryption Key`),c!==void 0&&SP(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=IP(fP,r)[0],e[1]=r),i!==void 0&&(i=IP(fP,i)[0],e[2]=i),!n&&a!==void 0&&(a=IP(fP,a)[0],e[3]=a),l!==void 0&&!CP(l))throw TypeError(`JWE Key Management Parameters must be an object`);MF(r,i,a);let d={...r,...i,...a};NP(fP,r),PP(fP,jP,u,r,d),kF(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new fP(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=mF[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new fP(`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 fP(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,yF(p),m]}async function dde(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??_F(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await LP(_,n,`encrypt`):[b,v,y]=await rde(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,MF(h,g,l));let x=h?xP(JSON.stringify(h)):``,S=u?.byteLength?xP(u):void 0,ee=iP(S?`${x}.${S}`:x),C=o;r.zip===`DEF`&&(C=await ide(C).catch(e=>{throw new fP(`Failed to compress plaintext`,{cause:e})}));let te,ne,w;_.mode===`integrated-encryption`?[v,te]=await _.encrypt(b,C,ee,h,r,p):{ciphertext:te,tag:ne,iv:w}=await oF(i,C,b,f,ee);let T={ciphertext:xP(te)};return w&&(T.iv=xP(w)),ne&&(T.tag=xP(ne)),v?.byteLength&&(T.encrypted_key=xP(v)),S&&(T.aad=S),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function fde(e,t,n){return dde(e,ude(e,n),t)}function pde(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}const NF=[[`verify`],[`sign`]];function PF(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:NF}}function FF(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:NF,minRsaBits:2048}}function IF(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:NF}}function LF(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:NF}}function RF(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:NF}}const zF=cF({HS256:PF(256),HS384:PF(384),HS512:PF(512),RS256:FF(256),RS384:FF(384),RS512:FF(512),PS256:FF(256,32),PS384:FF(384,48),PS512:FF(512,64),ES256:IF(`P-256`,256),ES384:IF(`P-384`,384),ES512:IF(`P-521`,512),EdDSA:LF(),Ed25519:LF(),"ML-DSA-44":RF(44),"ML-DSA-65":RF(65),"ML-DSA-87":RF(87)});function BF(e){let t=typeof e==`string`?zF[e]:void 0;if(!t)throw new uP(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function VF(e){return[e&&MP(`algorithms`,e.algorithms),e?.crit]}function mde(e){return e===void 0?{}:kP(e,pP,`JWS Protected Header is invalid`)}function hde(e){try{return iP(e)}catch{throw new pP(`JWS Compact Serialization payload must use only ASCII characters`)}}async function gde(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??mde(a);if(!TP(c,o))throw new pP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=FP(c,PP(pP,AP,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new pP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new lP(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new pP(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new pP(`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=BF(d),h=eP(a===void 0?/* @__PURE__ */ new Uint8Array:iP(a),iP(`.`),typeof f==`string`?t[2]??=OP(f,`payload`,pP):f),g=DP(e.signature,`signature`,pP),_=await LP(m,n,`verify`),v=await eF(_,m.subtle,`verify`);m.minRsaBits&&JP(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new zue;let b={payload:typeof f==`string`?DP(f,`payload`,pP):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function HF(e,t,n){if(e instanceof Uint8Array&&(e=ZN.decode(e)),typeof e!=`string`)throw new pP(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new pP(`Invalid Compact JWS`);return gde({payload:i,protected:r,signature:a},t,n,hde)}async function UF(e,t,n){let[r]=await HF(e,VF(n),t);return r}const WF=e=>Math.floor(e.getTime()/1e3),_de={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},vde=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,GF=`check_failed`;function KF(){throw TypeError(`Invalid time period format`)}function qF(e){typeof e!=`string`&&KF();let t=vde.exec(e);(!t||t[4]&&t[1])&&KF();let n=parseFloat(t[2]),r=Math.round(n*_de[t[3][0].toLowerCase()]);return Number.isFinite(r)||KF(),t[1]===`-`||t[4]===`ago`?-r:r}function JF(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function YF(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function yde(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 XF(e,t){return typeof e==`number`?JF(t,e):e instanceof Date?JF(t,WF(e)):WF(/* @__PURE__ */ new Date)+qF(e)}const ZF=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},bde=(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 sP(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function $F(e,t){throw new sP(`unexpected "${t}" claim value`,e,t,GF)}function eI(e,t,n={}){let r;try{r=JSON.parse(QN.decode(t))}catch{}if(!CP(r))throw new mP(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||ZF(e.typ)!==ZF(i)))throw new sP(`unexpected "typ" JWT header value`,r,`typ`,GF);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 sP(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&$F(r,`iss`),s!==void 0&&r.sub!==s&&$F(r,`sub`),c!==void 0&&!bde(r.aud,typeof c==`string`?[c]:c)&&$F(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=qF(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}JF(`clockTolerance option`,f);let{currentDate:p}=n,m=JF(`currentDate option`,WF(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 sP(`"nbf" claim timestamp check failed`,r,`nbf`,GF);let _=QF(r,`exp`);if(_!==void 0&&_<=m-f)throw new cP(`"exp" claim timestamp check failed`,r,`exp`,GF);if(l!==void 0){let e=m-h,t=JF(`maxTokenAge option`,typeof l==`number`?l:qF(l));if(e-f>t)throw new cP(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,GF);if(e<-f)throw new sP(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,GF)}return r}let tI;function nI(e){return tI.get(e)}function rI(e){let t=nI(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 XN.encode(JSON.stringify(t))}function iI(e,t){return nI(e)[t]}var aI=class{constructor(e={}){if(!CP(e))throw TypeError(`JWT Claims Set MUST be an object`);(tI||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return YF(`iss`,e),nI(this).iss=e,this}setSubject(e){return YF(`sub`,e),nI(this).sub=e,this}setAudience(e){return yde(e),nI(this).aud=e,this}setJti(e){return YF(`jti`,e),nI(this).jti=e,this}setNotBefore(e){return nI(this).nbf=XF(e,`setNotBefore`),this}setExpirationTime(e){return nI(this).exp=XF(e,`setExpirationTime`),this}setIssuedAt(e){let t=nI(this);return t.iat=e===void 0?WF(/* @__PURE__ */ new Date):typeof e==`string`?JF(`setIssuedAt`,WF(/* @__PURE__ */ new Date)+qF(e)):XF(e,`setIssuedAt`),this}};async function oI(e,t,n){let[r,i]=await HF(e,VF(n),t);if(!i)throw new mP(`JWTs MUST NOT use unencoded payload`);let a=eI(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function sI(e,t,n){let{plaintext:r,...i}=await lde(e,sde(n),t),{protectedHeader:a}=i,o=eI(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 sP(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function xde(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=IP(pP,i);i=e[0],s=xP(e[1])}if(a!==void 0&&(a=IP(pP,a)[0]),!i&&!a)throw new pP(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!TP(i,a))throw new pP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};NP(pP,i);let l=FP(i,PP(pP,AP,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new pP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=BF(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=xP(r),p=t[1]??=iP(f)):(f=xP(r),m=XN.encode(`${s}.${f}`))}m??=eP(iP(s),iP(`.`),p);let h=await eF(await LP(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&JP(d.alg,h);let g={signature:xP(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 Sde(e,t,n,r,i){let[a]=await xde([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const Cde=aI;var cI=class extends Cde{#e;setProtectedHeader(e){return EP(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Sde(rI(this),this.#e,t?.crit,e,()=>{throw new mP(`JWTs MUST NOT use unencoded payload`)})}};const wde=aI;var Tde=class extends wde{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return EP(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return EP(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return EP(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return EP(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=rI(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?iI(this,`iss`):void 0,sub:this.#n?iI(this,`sub`):void 0,aud:this.#r?iI(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,pde(await fde(r,e,t))}};function lI(e=`JWK "alg" (Algorithm) Parameter`){throw new uP(`Invalid or unsupported ${e} value`)}function uI(e,t){return(typeof e==`string`?zF[e]??mF[e]:void 0)??lI(t)}async function dI(e){if(VP(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:xP(e)};if(!BP(e))throw TypeError(WP(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 fI=(e,t)=>{if(typeof e!=`string`||!e)throw new hP(`${t} missing or invalid`)};async function pI(e,t){let n;if(CP(e)){if(n=XP(e),typeof n.kty!=`string`)throw TypeError(WP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(HP(e))n=XP(await dI(e));else throw TypeError(WP(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`:fI(n.alg,`"alg" (Algorithm) Parameter`),fI(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:fI(n.crv,`"crv" (Curve) Parameter`),fI(n.x,`"x" (X Coordinate) Parameter`),fI(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:fI(n.crv,`"crv" (Subtype of Key Pair) Parameter`),fI(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:fI(n.e,`"e" (Exponent) Parameter`),fI(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 hP(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new uP(`"kty" (Key Type) Parameter missing or unsupported`)}let i=iP(JSON.stringify(r));return xP(await aP(t,i))}function Ede(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 mI(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=$P(n,t,!0).then(e=>{if(e.type!==`public`)throw new gP(`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 hI(e){let t;try{t=structuredClone(e)}catch{}if(!wP(t))throw new gP(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=XP(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`?zF[a]:void 0;if(!s||s.secret)throw new uP(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Ede(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new _P;if(u!==1){let e=new vP;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await mI(r,e,s)}catch{}},e}return mI(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Dde(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let gI;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(gI=`jose/v6.2.12`);const Ode=/* @__PURE__ */ Symbol();async function kde(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 yP:e});if(i.status!==200)throw new oP(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new oP(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Ade=/* @__PURE__ */ Symbol();function _I(e,t){return Number.isFinite(e)&&Date.now()<e+t}function vI(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function jde(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=vI(r.cooldownDuration,3e4,`cooldownDuration`),s=vI(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);gI&&!c.has(`User-Agent`)&&c.set(`User-Agent`,gI),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[Ode],u=r[Ade],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;_I(e,s)&&wP(t)&&(d=e,h=hI(t))}let g=async()=>{if(f&&Dde()&&(f=void 0),!f){let e=++p,t=f=kde(n,c,AbortSignal.timeout(a),l).then(t=>{let n=hI(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||!_I(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof _P&&!_I(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>_I(d,o),enumerable:!0},fresh:{get:()=>_I(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function yI(e,t,n){if(!CP(e))throw TypeError(`JWK must be an object`);let r=ZP(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 bP(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 $P(uI(t),r,i);case`RSA`:case`EC`:case`OKP`:return $P(uI(t),r,i);default:throw new uP(`Unsupported "kty" (Key Type) Parameter value`)}}function bI(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 kP(t,TypeError,n)}function xI(e){if(typeof e!=`string`)throw new mP(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new mP(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new mP(`Invalid JWT`);if(!t)throw new mP(`JWTs must contain a payload`);let r;try{r=bP(t)}catch{throw new mP(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(QN.decode(r))}catch{throw new mP(`Failed to parse the decoded payload as JSON`)}if(!CP(i))throw new mP(`Invalid JWT Claims Set`);return i}function Mde(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new uP(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Nde(e,t){let n=QP(t?.extractable),r=uI(e,`"alg" (Algorithm)`);r.secret&&lI(`"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 uP(`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 uP(`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:Mde(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}const SI=`key-list+jwt`,Pde=W({keys:G(W({id:U,sealed:U}))}),CI=wS(W({keyId:xS,ownerId:xS,scopes:G(xS),expiresAt:tS(fS)})),wI=new TextEncoder,Fde=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,wI.encode(e))),TI=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:wI.encode(`clankerauth key list\0${t}`)},n,512));return{id:xP(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},Ide=async(e,t,n)=>{let{id:r,key:i}=await TI(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,wI.encode(Nx(CI)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:xP(s)}},Lde=async(e,t,n)=>{let r=await TI(await Fde(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(bP(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return kx(CI)(new TextDecoder().decode(o))},EI=Symbol.for(`@gjermundgaraba/effect-actions/Anyone`),DI=(e,t)=>{for(let n of e)if(n.caller!==EI&&(t===void 0||n.caller.key!==t.identity.key))throw Error(`Protected action '${n.name}' requires its matching authentication descriptor`)},OI=e=>U.pipe(iS(F(e))),Rde=W({path:G(K([U,fS])),message:U}),zde=M_();var kI=class e extends qS()(`InvalidInput`,{message:OI(`The input does not match the action's input.`),issues:G(Rde).pipe(iS(F([])))},{httpApiStatus:400}){static fromSchemaError=({issue:t,message:n})=>new e({message:n,issues:zde(t).issues.map(e=>({path:(e.path??[]).map(e=>{let t=Yt(e)?e:e.key;return Jt(t)?String(t):t}),message:e.message}))})},AI=class extends qS()(`Unauthenticated`,{message:OI(`Authentication is required.`)},{httpApiStatus:401}){};const jI=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Bde=U.check(dS(jI));var MI=class extends qS()(`Forbidden`,{message:OI(`Not allowed.`),scopes:Ix(Qx(Bde))},{httpApiStatus:403}){};const NI=[AI,MI],Vde=K(NI),PI=[kI,...NI];K(PI);const Hde=/^[A-Za-z0-9_-]{1,128}$/,Ude=(e,t)=>{if(!Hde.test(t)||t===`then`)throw Error(`Invalid ${e}: ${t}`)},FI=(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)}},II=(e,t)=>FI(e,t,e=>e.name),Wde=(e,t,n)=>{let r=t.filter(e=>!n.includes(e));if(r.length>0)throw Error(`Unknown ${e}: ${r.join(`, `)}`)},LI=e=>Av(e)?LI(e.thunk()):e,RI=e=>{let t=LI(e);return kv(t)?t.types.flatMap(RI):[t]},Gde=e=>Tv(e)?[e.literal]:Oie(e)?e.enums.map(([,e])=>e):[void 0],zI=e=>e===void 0?[]:Fx(e)?[e]:e,BI=(e,t=[])=>[.../* @__PURE__ */ new Set([...PI,...e.error,...t])],Kde=(e,t)=>BI(e,e.caller===EI||t.authentication===void 0?t.error:[...t.error,...t.authentication.error]),VI=e=>RI(Qy(e)).flatMap(e=>{let t=Ov(e)?e.propertySignatures.find(e=>e.name===`_tag`)?.type:void 0;return t===void 0?[]:RI(t).flatMap(Gde).filter(Gt)}),qde=new Set(PI.flatMap(e=>VI(e.ast))),HI=(e,t)=>{let n=t.flatMap(e=>VI(e.ast)).find(e=>qde.has(e));if(n!==void 0)throw Error(`${e}: error _tag "${n}" is built in, and declared on every surface`)},Jde=(e,t,n)=>{II(`action`,t);let r=zI(n.error);return HI(e,r),DI(t,n.authentication),{error:r,authentication:n.authentication}},Yde=()=>Math.random().toString(36).slice(2),UI=e=>{let t=P(`effect-actions/Implementation/${Yde()}`);return{key:t,layer:lf(t,e)}};var WI=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!==EI)?_f(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!==EI)?yield*r.#t.key:()=>L;return n.flatMap(n=>e.flatMap(([e,r])=>e===n?[[n,Qde(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 GI=e=>Oa(e),KI=(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(`, `)}`)}},qI=(e,t)=>t===void 0?e:(KI(`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]:[WI.share(n,e)]})),Xde=(e,t,n,r)=>{r!==void 0&&KI(`the binding does not hold it`,r,t);let i=n.flatMap(e=>e.actions),a=qI(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 II(`served action`,o),a},Zde=(e,t,n,r)=>{let i=Xde(e,t.actions,GI(n),r.actions),a=i.flatMap(e=>e.actions);return DI(a,t.authentication),FI(`middleware`,r.middleware??[],e=>e.key),{apps:i,actions:a,authentication:a.some(e=>e.caller!==EI)?t.authentication:void 0}},JI=e=>t=>{let[n,...r]=e.map(e=>WI.layerOf(e));return n===void 0?t:yf(t,gf(n,...r))},YI=e=>V(Uf(e,e=>WI.boundOf(e)),e=>e.flat()),Qde=(e,t,n)=>{let r={"action.name":e.name,"action.read_only":e.readOnly},i=e.caller===EI?L:B(jp(e.caller),e=>ji(e)?L:z(new AI)),a=e.caller===EI?L:Jf(()=>n(e)),o=Dx(Rx(K(BI(e)))),s=(e,t)=>{let n=$i(e.annotations);return[dd(e.error).annotate(n),dd(pd(t)).annotate(n)]},c=H(function*(e){let t=[];for(let n of e.reasons)if(ad(n)){let e=yield*op(o(n.error));t.push(...kd(e)?[n]:s(n,e.cause))}else t.push(n);return yield*Zf(sd(t))});return n=>Fp(i.pipe(rp(a),rp(Jf(()=>t(n))),dp(c))).pipe(mm(r),Zp(e.name,{attributes:r},{captureStackTrace:!1}))},XI={errors:`all`,onExcessProperty:`error`},ZI=`effect-actions/media`,QI=W({data:DS,mimeType:U});QI.annotate({[ZI]:`image`});const $I=e=>e.annotations?.[ZI]===`image`,eL=e=>$I(e)&&e.encoding===void 0?`image`:void 0,$de=Yx(U,Vx),tL=e=>Fx(e)?e:Reflect.ownKeys(e).length===0?$de:W(e);function nL(e,t){Ude(`action name`,e);let{caller:n,readOnly:r}=t;if(n!==EI&&!Qee(n))throw Error(`Missing caller: declare Action.Anyone or an identity service key`);if(n!==EI&&ta(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:tL(t.input??{}),success:t.success===void 0?Kx:tL(t.success),error:zI(t.error),readOnly:r,mcp:{...t.mcp}};return HI(`Action "${i.name}"`,i.error),i}const efe=()=>L,rL=e=>{if(!Xt(e))throw Error(`Missing authorize: pass an authorization function, or Action.allowAll`);return e},tfe=e=>{if(e===void 0)throw Error(`Protected actions require authorize, or Action.allowAll`);return e},nfe=e=>{if(e!==void 0)throw Error(`A public-only target takes no authorize`);return efe},rfe=e=>UI(Vf(e)?V(e,rL):F(rL(e)));function iL(e,t,n){let r=Oa(e),i=r.map(e=>e.name);II(`action`,r);let a=rfe(r.some(e=>e.caller!==EI)?tfe(n?.authorize):nfe(n?.authorize)),o=t=>{let n=Xt(t)?Object.fromEntries(Array.isArray(e)?[]:r.map(({name:e})=>[e,t])):t;Wde(`handlers`,Object.keys(n),i);let a=r.flatMap(e=>{let t=Object.hasOwn(n,e.name)?n[e.name]:void 0;return Xt(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=Vf(t)?V(t,o):F(o(t));return new WI(r,UI(s),a)}const aL=e=>B(Ap(e[`~provider`]),t=>t.descriptor===e?F(t):$f(/* @__PURE__ */ Error(`Authentication "${e.name}": the binding's descriptor is not its provider's; build both from one descriptor`))),ife=(e,t)=>B(jp(e[`~verified`]),n=>ji(n)?Np(t,e.identity,n.value):z(new AI)),oL=ub(`httpApiStatus`),sL=e=>oL(e)??(Av(e)?sL(e.thunk()):void 0),cL=e=>{let t=sL(e.ast);if(t!==void 0)return[oL(e.ast)===void 0?e.annotate({httpApiStatus:t}):e];let n=LI(e.ast);return kv(n)&&n.checks===void 0&&n.encoding===void 0?n.types.flatMap(e=>cL(Px(e))):[e.annotate({httpApiStatus:422})]},afe={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: ${uo(e.duration)}\n\n`}}};function lL(e){let t=typeof e==`string`?Fue(e):e;return e=>e.annotate({httpApiStatus:t})}const ofe=/*#__PURE__*/ (e=>Kx.pipe(lL(e)))(204),uL=e=>Fx(e)&&N(e,`~effect/http-api/HttpApiSchema/Stream`),dL=e=>uL(e)&&e._tag===`StreamSse`,sfe=e=>uL(e)&&e._tag===`StreamUint8Array`,fL=`~effect/http-api/HttpApiSchema/WithHeaders`,cfe=e=>N(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),pL=e=>Fx(e)&&N(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function lfe(e,t,n){return Px(e.ast,{[fL]:fL,schema:t,headers:n})}function mL(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??ufe(t._tag)}})}function ufe(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 dfe(e){return t=>mL(t,{_tag:`Json`,...e})}function ffe(e){return t=>mL(t,{_tag:`FormUrlEncoded`,...e})}const hL=e=>{if(wv(e))return!0;let t=Qy(e);if(wv(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&wv(n)},gL=/*#__PURE__*/ ub(`~httpApiEncoding`),_L=/*#__PURE__*/ ub(`~httpApiWithHeaders`),vL=/*#__PURE__*/ ub(`httpApiStatus`),yL={_tag:`Json`,contentType:`application/json`},bL={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function xL(e){return gL(e)??yL}function SL(e,t){return gL(e)||(vA(t)?yL:bL)}function CL(e){let t=xL(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function wL(e){return vL(e)??200}function TL(e){return pL(e)?vL(e.ast)??wL(e.schema.ast):wL(e.ast)}function EL(e){return pL(e)&&gL(e.ast)===void 0?CL(e.schema.ast):CL(e.ast)}function DL(e){return vL(e)??500}function OL(e){return pL(e)?vL(e.ast)??DL(e.schema.ast):DL(e.ast)}function kL(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const AL=`~effect/http-api/HttpApiEndpoint`;function jL(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function ML(e){let t=Array.from(e.success);return Aa(t)?t:[ofe]}function NL(e){let t=new Set(e.error),n=e.disableCodecs?M:HL;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const PL={[AL]:AL,pipe(){return Ot(this,arguments)},prefix(e){return IL({...FL(this),path:FM(this.path,e)})},middleware(e){return IL({...FL(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return IL({...FL(this),annotations:ia(this.annotations,e,t)})},annotateMerge(e){return IL({...FL(this),annotations:pa(this.annotations,e)})}},FL=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function IL(e){function t(){}return Object.setPrototypeOf(t,PL),Object.assign(t,e)}const LL=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?M:XS;return IL({identifier:t,path:n,method:e,params:RL(r?.params,a),query:RL(r?.query,a),headers:RL(r?.headers,a),payload:zL(r?.payload,e,i),success:VL(r?.success,e,i),error:UL(r?.error,i),annotations:na(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function RL(e,t){if(e!==void 0)return Fx(e)?t(e):t(W(e))}function zL(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:Fx(e)?[e]:[W(e).pipe(ffe())],a=n?M:$L;for(let e of i){let n=SL(e.ast,t),i=kL(n.contentType),o=r.get(i);if(o){if(o.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(o.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);o.schemas.push(a(e,t))}else r.set(i,{encoding:n,schemas:[a(e,t)]})}return r}const BL=`effect/http-api/stream/failure`;function VL(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Oa(e);return WL(r,t),new Set(n?r:r.map(HL))}const HL=/*#__PURE__*/ Rt(e=>uL(e)?e:pL(e)?lfe(e,uL(e.schema)?e.schema:QL(e.schema,EL(e)),XS(e.headers)):ZL(e));function UL(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Oa(e);for(let e of n){let t=pL(e)?e.schema:e;if(uL(t))throw Error(`Streaming schemas are not supported in error responses`)}return KL(n,OL),new Set(t?n:n.map(HL))}function WL(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=pL(i)?i.schema:i,a=TL(i);if(uL(e)){if(qL(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=GL(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(kL(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);r.set(a,{...i,stream:e})}else{let t=GL(r,a),n=hL(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=EL(i);if(kL(e.contentType)===kL(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(kL(EL(i).contentType)),t.noContent=t.noContent||n}}KL(e,TL)}function GL(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function KL(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=_L(r.ast),a=pL(r)?r.schema:i?.body??r,o=hL(a.ast)?``:kL(uL(a)?a.contentType:EL(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:/* @__PURE__ */ new Set},n.set(e,s));let c=()=>/* @__PURE__ */ Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(pL(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function qL(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(dL(e)&&JL(e.events.ast))throw Error(`SSE event name is reserved: ${BL}`)}function JL(e){return YL(Qy(e),/* @__PURE__ */ new Set)}function YL(e,t){if(t.has(e))return!1;if(t.add(e),kv(e))return e.types.some(e=>YL(e,t));if(Av(e))return YL(e.thunk(),t);if(!Ov(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&XL(n.type,t)}function XL(e,t){if(t.has(e))return!1;t.add(e);let n=Qy(e);return n===e?Tv(e)?e.literal===BL:kv(e)?e.types.some(e=>XL(e,t)):Av(e)?XL(e.thunk(),t):!1:XL(n,t)}function ZL(e){let t=CL(e.ast),n=_L(e.ast);return n===void 0?QL(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:QL(n.body,t),headersCodec:XS(n.headers)}})}function QL(e,t){switch(t._tag){case`Json`:return YS(e);case`FormUrlEncoded`:return XS(e);case`Text`:case`Uint8Array`:return e}}function $L(e,t){switch(SL(e.ast,t)._tag){case`Json`:return YS(e);case`FormUrlEncoded`:return XS(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const eR=/*#__PURE__*/ LL(`POST`),tR=`~effect/http-api/HttpApi`,nR={[tR]:tR,pipe(){return Ot(this,arguments)},add(...e){let t={...this.groups};for(let n of e)ir(t,n.identifier,n);return iR({...rR(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];ir(t,n,r.annotateMerge(pa(e.annotations,r.annotations)))}return iR({...rR(this),groups:t})},prefix(e){return iR({...rR(this),groups:wa(this.groups,t=>t.prefix(e))})},middleware(e){return iR({...rR(this),groups:wa(this.groups,t=>t.middleware(e))})},annotate(e,t){return iR({...rR(this),annotations:ia(this.annotations,e,t)})},annotateMerge(e){return iR({...rR(this),annotations:pa(this.annotations,e)})}},rR=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),iR=e=>{function t(){}return Object.setPrototypeOf(t,nR),Object.assign(t,e)},aR=e=>iR({identifier:e,groups:{},annotations:na()}),oR=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=pa(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:pa(n,e.annotations),successes:sR(ML(e),TL),errors:sR(NL(e),OL)})}},sR=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=pL(e)?e.schema:e;if(uL(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var cR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/AdditionalSchemas`)){},lR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParseOptions`)){},uR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParamsParseOptions`)){},dR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/QueryParseOptions`)){},fR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/HeadersParseOptions`)){},pR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/PayloadParseOptions`)){},mR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/SuccessParseOptions`)){},hR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const gR=e=>{let t=oa(e,lR);return{params:oa(e,uR)??t,query:oa(e,dR)??t,headers:oa(e,fR)??t,payload:oa(e,pR)??t,success:oa(e,mR)??t,error:oa(e,hR)??t}},_R=/*#__PURE__*/ pj({status:400}),vR=/*#__PURE__*/ pj({status:500}),yR=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var bR=class e extends (/*#__PURE__*/ Ao(`HttpApiSchemaError`)){[yR]=yR;get[lO](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return N(e,yR)}static wrap(t,n){return _m(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[Ij](){return F(this[`~effect/ErrorReporter/ignore`]?_R:vR)}};const xR=`~effect/http-api/HttpApiMiddleware`,SR=`~effect/http-api/HttpApiMiddleware/Security`,CR=e=>N(e,SR),wR=()=>(e,t)=>{let n=er(),r;n!==0&&(tr(2),r=new globalThis.Error,tr(n));class i extends P()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[xR]=xR,a.error=TR(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[SR]=SR,a.security=t.security}return a};function TR(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const ER=(e,t)=>of(e,(e,n)=>lp(e,e=>bR.is(e)?t(e,n):z(e))),DR=/*#__PURE__*/ new Set;function OR(e){if(e===void 0)return DR;let t=Iy(e.ast);return Ov(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function kR(e,t){if(t===void 0||!e.includes(`:`))return e;let n=OR(t);if(n===void 0)return e;let r=``,i=0,a=-1;for(let t=0;t<e.length;t++){let o=e[t];if(i>0||t===a){r+=o,o===`\\`?r+=e[++t]??``:o===`(`?i++:o===`)`&&i--;continue}if(o!==`:`){r+=o;continue}if(e[t+1]===`:`){r+=`::`,t++;continue}let s=/^:(\w+)/.exec(e.slice(t));if(s!==null&&n.has(s[1])){r+=s[0],t+=s[0].length-1;let n=e[t+1];n===`(`?a=t+1:n!==void 0&&!`/.-?`.includes(n)&&(r+=`(.*?)`)}else r+=`::`}return r}var AR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Identifier`)){},jR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Title`)){},MR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Version`)){},NR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Description`)){},PR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/License`)){},FR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/ExternalDocs`)){},IR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Servers`)){},LR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Format`)){},RR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Summary`)){},zR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Deprecated`)){},BR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Override`)){};const VR=/*#__PURE__*/ ha(`effect/http-api/OpenApi/Exclude`,{defaultValue:Nt});var HR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Transform`)){};const UR={},WR=/*#__PURE__*/ new WeakMap,GR=e=>{if(Array.isArray(e))return e.map(GR);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))ir(t,n,GR(e[n]));return t}return e};function KR(e,t,n){let r=fa(e,t);ji(r)&&n(r.value)}function qR(e,t){let n=t??UR,r=WR.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,WR.set(n,r));let i=r.get(e);if(i!==void 0)return GR(i);let a=JR(e,n);return r.set(e,GR(a)),a}function JR(e,t){let n={openapi:`3.1.0`,info:{title:`Api`,version:`0.0.1`},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]},r=[],i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[];function s(e,t=`Json`){let n=t===`Text`?{type:`string`}:{};return r.push({_tag:`schema`,ast:iz(e,t),target:n}),n}KR(e.annotations,jR,e=>{n.info.title=e}),KR(e.annotations,MR,e=>{n.info.version=e}),KR(e.annotations,NR,e=>{n.info.description=e}),KR(e.annotations,PR,e=>{n.info.license=e}),KR(e.annotations,RR,e=>{n.info.summary=e}),KR(e.annotations,IR,e=>{n.servers=[...e]}),oR(e,{onGroup({group:e}){if(la(e.annotations,VR))return;let t={name:aa(e.annotations,jR,()=>e.identifier)};KR(e.annotations,NR,e=>{t.description=e}),KR(e.annotations,FR,e=>{t.externalDocs=e}),KR(e.annotations,BR,e=>{for(let[n,r]of Object.entries(e))ir(t,n,r)}),KR(e.annotations,HR,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(la(c,VR))return;let u={tags:[aa(t.annotations,jR,()=>t.identifier)],operationId:aa(e.annotations,AR,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=OR(e.params),f=e.path.replace(/:(\w+)\??/g,(e,t)=>d===void 0||d.has(t)?`{${t}}`:e),p=e.method.toLowerCase(),m=p===`query`,h=m?`QUERY`:p;function g(e,t){for(let[n,{content:i,descriptions:a,headers:o,streamContent:c}]of e){let e=a.size>0?Array.from(a).join(` | `):t();ir(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??={},ir(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,ly),a=i.length===1?i[0]:new yy(i);u.responses[n].content??={},ir(u.responses[n].content,r,{schema:s(a,t)})})}),c!==void 0&&c.forEach((e,t)=>{u.responses[n].content??={},dL(e)?ir(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(AS(e.error,CS()).ast),errorSchema:s(e.error.ast),failureEvent:$R}}):ir(u.responses[n].content,t,{schema:{type:`string`,format:`binary`},"x-effect-stream":{encoding:`uint8array`}})})}}function _(e,t){e&&r.push({_tag:`properties`,ast:e.ast,apply(e,n){u.parameters.push({name:String(e.name),in:t,schema:n,required:t===`path`||!e.isOptional})}})}KR(e.annotations,NR,e=>{u.description=e}),KR(e.annotations,RR,e=>{u.summary=e}),KR(e.annotations,zR,e=>{u.deprecated=e}),KR(e.annotations,FR,e=>{u.externalDocs=e}),l.forEach(e=>{if(CR(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=oz(t);if(!Object.hasOwn(n.components.securitySchemes,e))ir(n.components.securitySchemes,e,r);else if(!Dn(sz(n.components.securitySchemes[e]),sz(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=vA(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of jL(e)){if(hL(n.ast))continue;let r=SL(n.ast,e.method),i=t.get(r.contentType);i===void 0?t.set(r.contentType,{encoding:r,schemas:[n]}):i.schemas.push(n)}if(t.size>0){let e={};for(let[n,{encoding:r,schemas:i}]of t){let t=i.map(ly);ir(e,n,{schema:s(t.length===1?t[0]:new yy(t),r._tag)})}u.requestBody={content:e,required:!0}}}if(_(e.params,`path`),!y&&e.payload.size===1){let t=e.payload.values().next().value;_(t.schemas[0],`query`)}_(e.headers,`header`),_(e.query,`query`),g(ez(e),()=>`Success`),g(tz(NL(e),OL,nz),()=>`Error`);let b=`${p} ${f.replace(/\{[^}]+\}/g,`{}`)}`;if(i.has(b))throw new globalThis.Error(`Duplicate OpenAPI operation for ${e.method} ${f}`);i.add(b),Object.hasOwn(n.paths,f)||ir(n.paths,f,{});let x=()=>{let e=n.paths[f];return m?e[`x-oai-additionalOperations`]??={}:e};x()[h]=u,o.push(()=>{let t=x(),n=t[h];KR(e.annotations,BR,e=>{for(let[t,r]of Object.entries(e))ir(n,t,r)}),KR(e.annotations,HR,e=>{n=e(n)});let r=n.operationId;if(r!==void 0){if(a.has(r))throw new globalThis.Error(`Duplicate OpenAPI operationId: ${r}`);a.add(r)}t[h]=n})}}),KR(e.annotations,cR,e=>{e.forEach(e=>{let t=db(e.ast);if(t!==void 0){if(Object.hasOwn(n.components.schemas,t))throw new globalThis.Error(`Duplicate component schema identifier: ${t}`);ir(n.components.schemas,t,s(e.ast))}})}),YR(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!Ub.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),KR(e.annotations,BR,e=>{for(let[t,r]of Object.entries(e))ir(n,t,r)}),KR(e.annotations,HR,e=>{n=e(n)}),n}function YR(e,t,n){if(!Aa(e))return;let r=hx(Pa(e,e=>e.ast),t),i=Pa(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:XR(t,r.references,i.select)}),a=Lae(soe({representations:i,references:QR(i,r.references)},{onExcessProperty:`error`}));for(let t=0;t<e.length;t++){let n=e[t],r=a.schemas[t];if(n._tag===`schema`){ar(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))ir(n,e,t)}function XR(e,t,n){let r=ZR(e,t);return{_tag:`Objects`,propertySignatures:r._tag===`Objects`?r.propertySignatures.filter(e=>n?.(e)??!0).map(e=>({...e,name:String(e.name)})):[],indexSignatures:[],checks:[]}}function ZR(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return ZR(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:ZR(r,t,new Set(n).add(e.$ref))}function QR(e,t){let n={},r=/* @__PURE__ */ new WeakSet,i=[...e];function a(e){for(let t of e)t.representation?.schemas!==void 0&&i.push(...t.representation.schemas),t._tag===`FilterGroup`&&a(t.checks)}for(;i.length>0;){let e=i.pop();if(!r.has(e)){if(r.add(e),e._tag===`Reference`){if(Object.hasOwn(n,e.$ref))continue;let r=t[e.$ref];if(r===void 0)continue;ir(n,e.$ref,r),i.push(r)}else switch(a(e.checks),e._tag){case`Declaration`:i.push(...e.typeParameters);break;case`Suspend`:i.push(e.thunk);break;case`TemplateLiteral`:i.push(...e.parts);break;case`Arrays`:for(let t of e.elements)i.push(t.type);i.push(...e.rest);break;case`Objects`:for(let t of e.propertySignatures)i.push(t.type);for(let t of e.indexSignatures)i.push(t.parameter,t.type);break;case`Union`:i.push(...e.types)}}}return n}const $R=`effect/http-api/stream/failure`;function ez(e){return tz(ML(e),TL,nz)}function tz(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=_L(e.ast),c=pL(e)?e.schema:i?.body??e,l=pL(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;uL(c)?s(c,u):hL(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,EL(e),n(e.ast)??n(d)),l!==void 0&&r.get(u).headers.push(l)}function a(e,t){let n=r.get(e);n===void 0?r.set(e,{descriptions:/* @__PURE__ */ new Set([t]),content:void 0,headers:[],streamContent:void 0}):t!==void 0&&n.descriptions.add(t)}function o(e,t,n,i){let a=r.get(t),{_tag:o,contentType:s}=n;if(a===void 0)r.set(t,{descriptions:new Set(i===void 0?[]:[i]),content:/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]),headers:[],streamContent:void 0});else if(i!==void 0&&a.descriptions.add(i),a.content===void 0)a.content=/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]);else{let t=a.content.get(o);if(t===void 0)a.content.set(o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]]));else{let n=t.get(s);n===void 0?t.set(s,/* @__PURE__ */ new Set([e])):n.add(e)}}}function s(e,t){let n=r.get(t);n===void 0?r.set(t,{descriptions:/* @__PURE__ */ new Set,content:void 0,headers:[],streamContent:/* @__PURE__ */ new Map([[e.contentType,e]])}):n.streamContent===void 0?n.streamContent=/* @__PURE__ */ new Map([[e.contentType,e]]):n.streamContent.set(e.contentType,e)}}function nz(e){return uae(e)??db(e)}const rz=/*#__PURE__*/ U.annotate({format:`binary`});function iz(e,t){switch(t){case`Uint8Array`:return rz.ast;case`Text`:return Cv(e)&&e.encoding===void 0?U.ast:e;case`Multipart`:e=az(e)}return Yb(e)}function az(e){return Cv(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?rz.ast:typeof e?.recur==`function`?e.recur(az):e}const oz=e=>{let t={};switch(KR(e.annotations,NR,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=fa(e.annotations,LR).pipe(zi(e=>({bearerFormat:e})),Li);return{...t,type:`http`,scheme:e.scheme,...n}}case`ApiKey`:return{...t,type:`apiKey`,name:e.key,in:e.in}}},sz=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,cz=(e,t)=>kM(H(function*(n){let r=yield*Ep(),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*$f(`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=Rt(e=>vj(qR(e)));yield*n.add(`GET`,t.openapiPath,I(()=>r(e)))}})),lz=(e,t,n)=>df(R(function*(){let r=(yield*Ep()).pipe(ma(Hd)),i=e.groups[t],a=n(gz(i)),o=Vf(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(bz(e,i,t,r));return $i(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),uz=`~effect/http-api/HttpApiBuilder/Handlers`,dz=e=>{switch(e._tag){case`Http`:return V(_M,t=>rg(pz(t.headers.authorization,e.scheme)??``));case`ApiKey`:{let t=e.in===`header`?e.key.toLowerCase():e.key,n=W({[t]:U}),r=e.in===`query`?Hce(n):e.in===`cookie`?Bce(n):Vce(n);return Cp(r,{onFailure:()=>rg(``),onSuccess:e=>rg(e[t])})}case`Basic`:{let e={username:``,password:rg(``)};return V(_M,t=>{let n=pz(t.headers.authorization,fz);if(n===void 0)return e;let r=ote(_h(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:rg(r.slice(i+1))}})}}},fz=`Basic`;function pz(e,t){let n=t.length;if(e===void 0||e.length<=n||e.charCodeAt(n)!==32||e.slice(0,n).toLowerCase()!==t.toLowerCase())return;let r=n+1;for(;e.charCodeAt(r)===32;)r++;return r===e.length?void 0:e.slice(r)}const mz=(e,t,n,r,i)=>{if(!Object.hasOwn(e.group.endpoints,t))throw Error(`HttpApiEndpoint "${t}" not found in HttpApiGroup "${e.group.identifier}"`);if(e.handlers.has(t))throw Error(`Handler for HttpApiEndpoint "${t}" is already registered in HttpApiGroup "${e.group.identifier}"`);let a=e.group.endpoints[t];return e.handlers.set(t,{endpoint:a,handler:n,isRaw:r,uninterruptible:i?.uninterruptible??!1}),e},hz={[uz]:uz,pipe(){return Ot(this,arguments)},handle(e,t,n){return mz(this,e,t,!1,n)},handleAll(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`function`?n:n.handler,r=typeof n==`function`?void 0:n.options;mz(this,t,e,!1,r)}return this},handleRaw(e,t,n){return mz(this,e,t,!0,n)}},gz=e=>{let t=Object.create(hz);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function _z(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=K(r),o=Dx(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=>Tie(Qy(e.ast)))})}),n}function vz(e,t,n){let r=vA(t.method),i=r?kL(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return _j(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=hp(t.multipart);return a.limits&&(e=kp(e,dM(a.limits))),B(e,s)}return F(a.limits?JE(t.multipartStream,dM(a.limits)):t.multipartStream);case`Json`:return B(hp(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return z(new Cx(new S_({message:`Expected a valid JSON body`})))}});case`Text`:return B(hp(t.text),s);case`FormUrlEncoded`:{let e=r?V(hp(t.urlParamsBody),Fg):F(n);return B(e,s)}case`Uint8Array`:return B(V(hp(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function yz(e,t,n,r,i,a){let o=pa(pa(e.annotations,t.annotations),n.annotations),s=gR(o),c=Ax(Bz(n,s.headers),s.success),l=Ax(Vz(n,s.headers),s.error),u=KO(n.params,e=>Dx(e,s.params)),d=KO(n.headers,e=>Dx(e,s.headers)),f=KO(n.query,e=>Dx(ZS(e),s.query)),p=kz(n,s.success),m=Oz(n,s.success,s.headers),h=n.payload.size>0&&!a?_z(n.payload,s.payload):void 0;return xz(t,n,r,R(function*(){let e=nC().context,r=ca(e,_M),a=ca(e,OM),o=ca(e,vM),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*bR.wrap(`Params`,u(a.params))),d&&(s.headers=yield*bR.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*bR.wrap(`Query`,f(o))),h){let e=vz(h,r,o);if(fj(e))return e;e!==void 0&&(s.payload=yield*bR.wrap(`Payload`,e))}let l=yield*i(s);if(fj(l))return l;let g;m!==void 0&&cfe(l)&&(g=l.headers,l=l.body);let _=yield*bR.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*bR.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return Cj(_,v)})).pipe(iie,lp(e=>bR.is(e)?$f(e):hp(l(e))),kp(r))}function bz(e,t,n,r){let i=n.endpoint;return NM(i.method,kR(i.path,i.params),yz(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const xz=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=ca(n,t);r=(CR(t)?Cz(t,a):a)(r,i)}return r},Sz=/*#__PURE__*/ new WeakMap,Cz=(e,t)=>{let n=Sz.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:dz(n),middleware:t[e]}));if(r.length===0)return M;let i=H(function*(e,t){e=mp(e,e=>new Tz(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*ap(B(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(xa(s)){if(Ez(s.failure))return yield*z(s.failure.error);n=s}else return s.success}return yield*np(n)});return Sz.set(t,i),i},wz=`~effect/http-api/HttpApiBuilder/HandlerError`;var Tz=class{[wz]=wz;error;constructor(e){this.error=e}};const Ez=e=>N(e,wz),Dz=/*#__PURE__*/ Sx(fj);function Oz(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)pL(t)&&(r.set(TL(t),Ax(t.headers,n)),uL(t.schema)||i.push(Lz(t,n)));return r.size===0?void 0:{encodeBody:Ax(i.length===0?Vx:i.length===1?i[0]:K(i),t),encodeHeaders:r}}function kz(e,t){let n=Az(e);if(n===void 0)return;let r=n.body,i=jz(e),a=TL(n.schema),o=r.contentType;if(sfe(r))return(e,t)=>_E(e)?F(bj(JE(e,t),{status:a,contentType:o})):i?void 0:new Cx(new S_({message:`Expected a streaming response`}));let s=Mz(r,t);return(e,t)=>_E(e)?F(bj(JE(Nz(e,s),t),{status:a,contentType:o})):i?void 0:new Cx(new S_({message:`Expected a streaming response`}))}function Az(e){for(let t of e.success){let e=pL(t)?t.schema:t;if(uL(e))return{schema:t,body:e}}}function jz(e){for(let t of e.success){let e=pL(t)?t.schema:t;if(Fx(e)&&!uL(e))return!0}return e.success.size===0}function Mz(e,t){let n=YS(AS(e.error,CS()));return{sseMode:e.sseMode,encodeEvents:Ax(G(e.events),t),encodeCause:Ax(wS(n),t)}}function Nz(e,t){return e.pipe(t.sseMode===`data`?ME(e=>({id:void 0,event:`message`,data:e})):M,NE(e=>hp(t.encodeEvents(e))),RE(e=>yE(Pz(e,t))),ME(Iz),GE)}function Pz(e,t){return t.encodeCause(e).pipe(hp,V(e=>({id:void 0,event:Fz,data:e})))}const Fz=`effect/http-api/stream/failure`;function Iz(e){return afe.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const Lz=/*#__PURE__*/ Hz(TL),Rz=/*#__PURE__*/ Hz(OL);function zz(e,t){return pL(e)?Wz({schema:e,status:OL(e),encoding:EL(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):Rz(e,t)}function Bz(e,t){let n=ML(e).map(e=>Lz(e,t));return n.length===1?n[0]:K(n)}function Vz(e,t){let n=NL(e).map(e=>zz(e,t));return n.length===0?Vx:n.length===1?n[0]:K(n)}function Hz(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=_L(n.ast);if(i!==void 0)return Wz({schema:Rx(n),status:e(i.body),encoding:CL(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=pL(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=pL(n)?n.schema:n,c=Dz.pipe(rS(s,Uz(e,n)));return t.set(a,c),c}}function Uz(e,t){let n=pL(t)?t.schema:t;return gv({decode:(e,t)=>z(new w_({message:`Encode only schema`},e,t)),encode:Gz(e(t),EL(t),hL(n.ast))})}function Wz(e){let t=Ax(e.body),n=Ax(e.headers,e.headersOptions),r=Gz(e.status,e.encoding,hL(e.body.ast)),i=e=>e.issue,a=gv({decode:(e,t)=>z(new w_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(mp(i),B(e=>r(e,o)),B(e=>V(mp(n(s.headers),i),t=>Cj(e,t))))}});return Dz.pipe(rS(e.schema,a))}function Gz(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return F(pj({status:e}));try{let n=JSON.stringify(r);return F(_j(n,{status:e,contentType:t.contentType}))}catch{return z(new S_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>F(_j(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>F(hj(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>F(Wse(n,{status:e}).pipe(xj(`content-type`,t.contentType)))}}const Kz=`~effect/http-api/HttpApiGroup`,qz={[Kz]:Kz,add(...e){let t={...this.endpoints};for(let n of e)ir(t,n.identifier,n);return Yz({...Jz(this),endpoints:t})},prefix(e){return Yz({...Jz(this),endpoints:wa(this.endpoints,t=>t.prefix(e))})},middleware(e){return Yz({...Jz(this),endpoints:wa(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return Yz({...Jz(this),annotations:pa(this.annotations,e)})},annotate(e,t){return Yz({...Jz(this),annotations:ia(this.annotations,e,t)})},annotateEndpointsMerge(e){return Yz({...Jz(this),endpoints:wa(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return Yz({...Jz(this),endpoints:wa(this.endpoints,n=>n.annotate(e,t))})},pipe(){return Ot(this,arguments)}},Jz=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),Yz=e=>{function t(){}return Object.setPrototypeOf(t,qz),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},Xz=(e,t)=>Yz({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:na()}),Zz=`~effect/http-api/HttpApiSecurity`,Qz={[Zz]:Zz,pipe(){return Ot(this,arguments)}},$z=/*#__PURE__*/ (e=>Object.assign(Object.create(Qz),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:na()}))({scheme:`Bearer`}),eB=e=>Object.assign(Object.create(Qz),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:na()}),tB=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var nB=class extends wR()(`effect-actions/http/SchemaErrors`,{error:[kI]}){};const rB=()=>ER(nB,e=>z(tB.has(e.kind)?e:kI.fromSchemaError(e.cause))),iB=e=>(e??`/api`).split(`/`).filter(e=>e!==``),aB=e=>`/${e.join(`/`)}`,oB=e=>e.join(`/`)||`/`,sB=(e,t)=>{let n=Xz(e,{topLevel:!0}),[r,...i]=t;return aR(`actions`).annotate(lR,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},cB=(e,t,n)=>eR(e.name,t,{payload:e.input.pipe(dfe()),success:e.success,error:n.flatMap(cL)}),lB=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function uB(e,t={}){let n=Jde(`ActionHttp binding`,e,t),r=iB(t.prefix),i=n.authentication?.[`~middleware`],a=e.map(e=>{let t=i===void 0||e.caller===EI,a=cB(e,aB([...r,e.name]),Kde(e,n)).annotate(NR,e.description);return t?a:a.middleware(i)}),o=sB(oB(r),a);return{actions:e,...n,prefix:aB(r),api:o}}const dB=e=>ef((t,n)=>uie(af(e,t,n),na())),fB=()=>IM(V(Ep(),e=>{let t=ma(Hd)(e);return e=>Mp(e,e=>pa(t,e))})).layer;var pB=class extends wR()(`effect-actions/ActionHttp/StepUp`){},mB=class extends wR()(`effect-actions/ActionHttp/JsonContentType`){};const hB=()=>of(mB,e=>B(_M,t=>t.headers[`content-type`]===void 0?F(_j(`Unsupported content-type: none`,{status:415})):e));function gB(e,t,n={}){let{apps:r,actions:i,authentication:a}=Zde(`HTTP binding`,e,t,n),o=iB(e.prefix),s=oB(o),c=sB(s,i.map(t=>{let r=lB(cB(t,aB([...o,t.name]),BI(t,e.error)).middleware(mB).middleware(nB),n.middleware);return t.caller===EI||a===void 0?r:r.middleware(pB).middleware(a[`~middleware`])})).annotate(pR,XI),l=mf(R(function*(){let e=yield*YI(r),t=a===void 0?cf:yield*V(aL(a),e=>gf(of(a[`~middleware`],e.middleware),of(pB,e.stepUp))),i=yield*Uf(n.middleware??[],e=>V(Ap(e),t=>of(e,t))),o=Object.fromEntries(e.map(([e,t])=>[e.name,e=>t(e.payload)]));return lz(c,s,e=>e.handleAll(o)).pipe(yf([rB(),hB(),t,...i]),dB)})).pipe(JI(r));return cz(c).pipe(yf(l),yf(fB()))}const _B=(e,t)=>vj(Mx(YS(e))(t),{status:oL(e.ast)??422}),vB=(e,t)=>{let n=e.flatMap(cL).find(e=>Ex(e)(t));return n===void 0?void 0:_B(n,t)},yB=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,bB=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},xB=e=>bB(`Bearer`,e),SB=Ex(Vde),CB=(e,t)=>on(e,`Forbidden`)&&e.scopes!==void 0?xB([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,yB.test(e.message)?e.message:void 0]]):void 0,wB={Unauthenticated:AI,Forbidden:MI},TB=e=>_B(wB[e._tag],e),EB=(e,t)=>{let n=TB(e),r=CB(e,t);return r===void 0?n:xj(n,`www-authenticate`,r)};var DB=class extends P()(`effect-actions/SteppedUp`){};const OB=e=>SB(e)&&(!on(e,`Forbidden`)||e.scopes!==void 0),kB=e=>gp(e,e=>OB(e)?B(jp(DB),t=>ji(t)?WO(t.value,ki(e)):L):L),AB=(e,t)=>R(function*(){let n=yield*HO(Oi()),r=yield*op(Np(e,DB,n)),i=yield*UO(n),a=Ad(r)&&(md(r.cause)||hd(r.cause));return ji(i)&&!a?EB(i.value,t):yield*r}),jB=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,MB=e=>zi(Fi(jB.exec(e??``)?.[1]),e=>rg(e)),NB=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},PB=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:NB(e).href}),FB=e=>ji(MB(e)),IB=(e,t)=>xB([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),LB=(e,t)=>{if(t!==void 0){if(!e)throw Error(`A protected resource is published only for a Bearer scheme`);if(!Vf(t)){for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!jI.test(e));if(n!==void 0)throw Error(`Invalid scope in ${e}: "${n}"`)}if(new URL(t.resource).href.includes(`#`))throw Error(`A protected resource has no fragment: ${t.resource}`)}}},RB=(e,t)=>Cj(e,{...e.headers[`cache-control`]===void 0?{"cache-control":`no-store`}:{},...t!==void 0&&e.status===401&&e.headers[`www-authenticate`]===void 0?{"www-authenticate":t}:{}}),zB=(e,t)=>{let n=t?.authentication,r=n===void 0||UB(n.security);LB(r,t?.protectedResource);let i=PB(t?.protectedResource),a=n!==void 0&&!r?GB(n.security,n.name):IB(i,FB(t?.authorization));if(!SB(e)){let t=vB(n?.error??[],e);if(t===void 0)throw Error(`Not a refusal, nor an error the authentication declares`);return RB(t,a)}return RB(r?EB(e,i.metadataUrl):TB(e),a)},BB=/\.well-known|[\t\n\r]/,VB=e=>{let t=NB(e),n=t.href.slice(t.origin.length),r=vj({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 pj({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(_M,a=>{let o=BB.test(a.url)&&URL.canParse(a.url,t.origin)&&new URL(a.url,t.origin).href.slice(t.origin.length)===n;return o&&(a.method===`GET`||a.method===`HEAD`)?F(r):o&&a.method===`OPTIONS`?F(i(a)):e})},HB=e=>{let t=PB(e);return{metadataUrl:t.metadataUrl,invalid:IB(t,!0),anonymous:IB(t,!1),published:e===void 0?void 0:VB(e)}},UB=e=>on(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,WB=/^[\w.-]+$/,GB=(e,t)=>AO(e).pipe(MO(`Http`,({scheme:e})=>bB(e,[])),MO(`Basic`,()=>bB(`Basic`,[[`realm`,t]])),MO(`ApiKey`,()=>void 0),zO),KB=(e,t,...n)=>{let r=n[0]?.security??$z,i=zI(n[0]?.error);if(!WB.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key`);if(HI(`Authentication "${e}"`,i),!on(r,`Http`)&&!on(r,`ApiKey`)&&!on(r,`Basic`))throw Error(`Authentication takes one native HttpApiSecurity scheme`);return{name:e,identity:t,security:r,error:i,"~provider":P(`effect-actions/Authentication/Provider/${e}`),"~middleware":wR()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":P(`effect-actions/Authentication/Verified/${e}`)}},qB=e=>ng(e)?ag(e)!==``:e.username!==``||ag(e.password)!==``;function JB(e,t,n={}){let{security:r}=e,i=UB(r),a=n.protectedResource;LB(i,a);let o=Vf(a)?V(a,e=>(LB(i,e),HB(e))):F(HB(a)),s=new AI({message:i?`A bearer token is required.`:`A credential is required.`});return lf(e[`~provider`],R(function*(){let{metadataUrl:n,invalid:a,anonymous:c,published:l}=yield*o;l!==void 0&&(yield*(yield*DM).addGlobalMiddleware(l));let u=Vf(t)?yield*t:t;if(!Xt(u))return yield*$f(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let d=e=>qB(e)?u(e):z(s),f=Qce((e,t)=>F(xj(t,`cache-control`,`no-store`))),p=t=>i?qB(t)?a:c:GB(r,e.name),m=t=>SB(t)?F(i?EB(t,n):TB(t)):Jf(()=>{let n=vB(e.error,t);return n===void 0?$f(t):F(n)}),h=(e,t,n)=>{let r=p(e);return Tp(d(e),{onFailure:m,onSuccess:e=>Np(t,n,e)}).pipe(zp(()=>f),$ce((e,t)=>F(RB(t,r))))};return{descriptor:e,authenticate:d,middleware:{[e.name]:(t,{credential:n})=>h(n,t,e.identity)},stepUp:e=>i?pp(e,OB,e=>F(EB(e,n))):e,http:((t,a)=>B(dz(r),r=>a&&!qB(r)?t:h(r,i?AB(t,n):t,e[`~verified`]))),route:(t=>B(dz(r),n=>h(n,pp(t,SB,m),e.identity)))}}))}var YB=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}},XB=class extends qS()(`ServiceUnavailable`,{message:U},{httpApiStatus:503}){},ZB=class e extends qS()(`ClientNotFound`,{clientId:U,message:U},{httpApiStatus:404}){static of=t=>new e({clientId:t,message:`No client ${t} is registered`})},QB=class e extends qS()(`ResourceNotFound`,{identifier:U,message:U},{httpApiStatus:404}){static of=t=>new e({identifier:t,message:`No resource ${t} exists`})},$B=class e extends qS()(`ApiKeyNotFound`,{keyId:U,message:U},{httpApiStatus:404}){static of=t=>new e({keyId:t,message:`No API key ${t} exists`})},eV=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`})},tV=class e extends qS()(`OwnerExists`,{message:U},{httpApiStatus:409}){static of=()=>new e({message:`Setup already completed`})},nV=class extends qS()(`ProviderRefused`,{message:U},{httpApiStatus:400}){},rV=class extends qS()(`UnreadableRequest`,{message:U},{httpApiStatus:400}){};const iV=[XB,YB];var aV=class extends P()(`clankerauth/CurrentOwner`){};const oV=e=>KB(`clankerauth.OwnerSession`,aV,{security:eB({in:`cookie`,key:e}),error:iV}),sV=oV(`better-auth.session_token`),cV=KB(`clankerauth.OwnerToken`,aV,{error:iV}),lV=e=>new URL(`/`,e).href,uV={read:`clankerauth:read`,write:`clankerauth:write`},dV=`Passwords have 8 to 128 characters`,fV=W({email:U.check(dS(/\S/u,{message:`Setup requires an email`})),password:U.check(gS(8,{message:dV}),vS(128,{message:dV}))}),pV=eS([`none`,`client_secret_basic`,`client_secret_post`]),mV=eS([`web`,`native`]),hV=G(U).check(bS({message:`Choose unique Resources`})),gV=W({client_name:U,redirect_uris:G(U),resources:hV,token_endpoint_auth_method:pV,application_type:mV}),_V=W({client_id:U,client_name:U,redirect_uris:G(U),application_type:mV}),vV=W({client_id:U}),yV=W({client_id:U,resource:Lx(U)}),bV=W({client_id:U,blocked:Gx}),xV=W({onboarding:Lx(eS([`managed`,`dcr`,`cimd`])),blocked:Lx(Gx),client_id:U,client_name:Lx(U),redirect_uris:G(U),token_endpoint_auth_method:Lx(U),application_type:Lx(tS(U)),scope:Lx(U),grant_types:Lx(G(U))}),SV=xV.pipe(Jx({client_secret:Lx(U),client_secret_expires_at:Lx(Wx)})),CV=W({identifier:U,name:U,scopes:G(U)}),wV=CV.pipe(Jx({builtIn:Gx})),TV=W({identifier:U,name:U.check(dS(/\S/u,{message:`Resources require a name`})),scopes:G(U.check(dS(/^\s*[\x21\x23-\x5B\x5D-\x7E]+\s*$/u,{message:`Resources require well-formed custom scopes`})))}),EV=W({identifier:U}),DV=W({resource:CV,created:Gx}),OV=W({client_id:U,resource:U}),kV=W({client_id:U,resources:hV}),AV=W({clientAccess:G(OV)}),jV=Yx(U,G(U)),MV=Yx(U,G(U).check(gS(1,{message:`Select explicitly granted, currently available Resource scopes`}),bS({message:`Select explicitly granted, currently available Resource scopes`}))).check(zoe(1,{message:`Select at least one Resource and scope`})),NV=U.check(vS(100,{message:`Key names require 1–100 characters`}),dS(/\S/u,{message:`Key names require 1–100 characters`})),PV=FS,FV=W({client_id:U,resource:U,scopes:G(U),approvedAt:tS(PV),refreshedAt:tS(PV)}),IV=W({name:NV,permissions:MV,expiresAt:tS(PV)}),LV=W({keyId:U}),RV=W({keyId:U,name:Lx(NV),permissions:Lx(MV),enabled:Lx(Gx)}),zV=W({keyId:U,name:U,enabled:Gx,permissions:jV,expiresAt:tS(PV),createdAt:PV}),BV={caller:EI},VV={caller:aV},HV=[nL(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...BV,error:[YB],success:W({required:Gx})}),nL(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...BV,error:[tV,nV,YB],input:fV,success:W({created:Gx}).pipe(lL(201))}),nL(`keyList`,{description:`The signed list a resource server verifies API keys against: one sealed entry per key granted on the resource, readable only with that key.`,readOnly:!0,...BV,error:[YB],input:W({resource:U}),success:W({list:U})})],UV=W({clients:G(xV),resources:G(wV),clientAccess:G(OV),connections:G(FV),email:U,issuer:U}),WV=[nL(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...VV,error:[YB],success:UV}),nL(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...VV,error:[nV,YB],input:gV,success:SV.pipe(lL(201))}),nL(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...VV,error:[ZB,eV,nV,YB],input:_V,success:xV}),nL(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...VV,error:[ZB,YB],input:vV,success:W({deleted:Gx})}),nL(`revokeClient`,{description:`Revoke a client’s stored authorization, for one resource or all. It must authorize again; an automatic client asks for consent.`,readOnly:!1,...VV,error:[ZB,YB],input:yV,success:W({revoked:Gx})}),nL(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...VV,error:[ZB,YB],input:bV,success:W({blocked:Gx})}),nL(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...VV,error:[ZB,eV,nV,YB],input:vV,success:SV}),nL(`setClientAccess`,{description:`Set the resources a managed client may obtain. Removing one revokes its authorization for it. Automatic clients may ask for any resource with consent.`,readOnly:!1,...VV,error:[ZB,eV,YB],input:kV,success:AV}),nL(`getResource`,{description:`Get one resource and its scopes by identifier.`,readOnly:!0,...VV,error:[QB,YB],input:EV,success:wV}),nL(`putResource`,{description:`Create an OAuth resource, or update the one with its identifier, to exactly these name and scopes.`,readOnly:!1,...VV,error:[nV,YB],input:TV,success:DV}),nL(`deleteResource`,{description:`Delete a resource, its client access and every client’s authorization for it. API-key permissions are retained; recreating the resource restores them.`,readOnly:!1,...VV,error:[QB,YB],input:EV,success:W({deleted:Gx})}),nL(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...VV,error:[YB],success:W({keys:G(zV)})}),nL(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...VV,error:[nV,YB],input:IV,success:zV.pipe(Jx({key:U}),lL(201))}),nL(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...VV,error:[$B,nV,YB],input:RV,success:zV}),nL(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...VV,error:[$B,YB],input:LV,success:W({deleted:Gx})})],GV=[.../* @__PURE__ */ new Set([...[...HV,...WV].flatMap(e=>e.error),...iV,rV])],KV=e=>uB([...WV,...HV],{authentication:e});KV(sV);const qV=uB(WV,{prefix:`/api/owner`,authentication:cV});var JV=/* @__PURE__ */ e({NodeSqliteDialect:()=>eH}),YV=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},XV=class{#e;#t=new QV;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new ZV(this.#n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#r)}async acquireConnection(){return await this.#t.lock(),this.#r}async beginTransaction(e){await e.executeQuery(d.raw(`begin`))}async commitTransaction(e){await e.executeQuery(d.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(d.raw(`rollback`))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#n?.close()}},ZV=class{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t),i=n;if(r.columns().length>0)return Promise.resolve({rows:r.all(...i)});let{changes:a,lastInsertRowid:o}=r.run(...i);return Promise.resolve({rows:[],numAffectedRows:BigInt(a),insertId:typeof o==`bigint`?o:BigInt(o)})}async*streamQuery(){throw Error(`Streaming query is not supported by SQLite driver.`)}},QV=class{#e;#t;async lock(){for(;this.#e!==void 0;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},$V=class extends r{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},eH=class{#e;constructor(e){this.#e={...e}}createDriver(){return new XV(this.#e)}createQueryCompiler(){return new $V}createAdapter(){return new YV}createIntrospector(e){return n(e)}};const tH=e=>{let t=Dx(e);return e=>mp(t(e),YB.of)};function nH(e){return(n,...r)=>Kf({try:async()=>(await t(n,...r).execute(e)).rows,catch:YB.of})}const rH=sm(`Database.transaction`)(function*(e,t){let n=yield*Kf({try:()=>e.startTransaction().execute(),catch:YB.of}),r=yield*op(t(nH(n))),i=vp(Kf({try:()=>n.rollback().execute(),catch:YB.of})),a=Kf({try:()=>n.commit().execute(),catch:YB.of}).pipe(gp(()=>i));return yield*kd(r)?a:i,yield*r},qp);async function iH(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 eH({database:n})});return await t`SELECT 1`.execute(e),{kysely:e,sql:nH(e),close:()=>e.destroy()}}catch(e){throw n.close(),e}}var aH=class e extends P()(`clankerauth/Database`){static layer=t=>lf(e,R(function*(){yield*ep(()=>fee(lt(t),{recursive:!0,mode:448}));let e=yield*Ip(Kf(()=>iH(t)),e=>Gf(()=>e.close()));return{kysely:e.kysely,sql:e.sql,transaction:t=>rH(e.kysely,t)}}))};let oH,sH=!1;function cH(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function lH(){if(oH)return oH;let e=cH();if(e)return oH??=e,oH;try{let{AsyncLocalStorage:e}=await import(
|
|
26
|
-
/* @vite-ignore */
|
|
27
|
-
/* webpackIgnore: true */
|
|
28
|
-
`node:async_hooks`);return oH??=e,oH}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return oH??=t,oH;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(sH||(sH=!0,console.warn(`[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.`),console.warn(`[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler`),console.warn(`[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag`)),e)}}const uH=()=>v().context.endpointContextAsyncStorage,dH=async()=>{let e=uH();if(e)return e;let t=await lH(),n=v().context;return n.endpointContextAsyncStorage??=new t};function fH(){return x()}function pH(){let e=fH();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function mH(e,t){return(await dH()).run(e,t)}const hH=async()=>{let e=v(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await lH();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function gH(){return(await hH()).getStore()!==void 0}async function _H(){let e=(await hH()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function vH(e,t){return(await hH()).run(e,t)}function yH(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await _H();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await _H()).set(t,e)}}}function bH(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const Y=bH({USER_NOT_FOUND:`User not found`,FAILED_TO_CREATE_USER:`Failed to create user`,FAILED_TO_CREATE_SESSION:`Failed to create session`,FAILED_TO_UPDATE_USER:`Failed to update user`,FAILED_TO_GET_SESSION:`Failed to get session`,INVALID_PASSWORD:`Invalid password`,INVALID_EMAIL:`Invalid email`,INVALID_EMAIL_OR_PASSWORD:`Invalid email or password`,INVALID_USER:`Invalid user`,SOCIAL_ACCOUNT_ALREADY_LINKED:`Social account already linked`,PROVIDER_NOT_FOUND:`Provider not found`,INVALID_TOKEN:`Invalid token`,TOKEN_EXPIRED:`Token expired`,ID_TOKEN_NOT_SUPPORTED:`id_token not supported`,FAILED_TO_GET_USER_INFO:`Failed to get user info`,USER_EMAIL_NOT_FOUND:`User email not found`,EMAIL_NOT_VERIFIED:`Email not verified`,PASSWORD_TOO_SHORT:`Password too short`,PASSWORD_TOO_LONG:`Password too long`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,EMAIL_CAN_NOT_BE_UPDATED:`Email can not be updated`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,CREDENTIAL_ACCOUNT_NOT_FOUND:`Credential account not found`,SESSION_EXPIRED:`Session expired. Re-authenticate to perform this action.`,FAILED_TO_UNLINK_LAST_ACCOUNT:`You can't unlink your last account`,ACCOUNT_NOT_FOUND:`Account not found`,USER_ALREADY_HAS_PASSWORD:`User already has a password. Provide that to delete the account.`,CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:`Cross-site navigation login blocked. This request appears to be a CSRF attack.`,VERIFICATION_EMAIL_NOT_ENABLED:`Verification email isn't enabled`,EMAIL_ALREADY_VERIFIED:`Email is already verified`,EMAIL_MISMATCH:`Email mismatch`,SESSION_NOT_FRESH:`Session is not fresh`,LINKED_ACCOUNT_ALREADY_EXISTS:`Linked account already exists`,INVALID_ORIGIN:`Invalid origin`,INVALID_CALLBACK_URL:`Invalid callbackURL`,INVALID_REDIRECT_URL:`Invalid redirectURL`,INVALID_ERROR_CALLBACK_URL:`Invalid errorCallbackURL`,INVALID_NEW_USER_CALLBACK_URL:`Invalid newUserCallbackURL`,MISSING_OR_NULL_ORIGIN:`Missing or null Origin`,CALLBACK_URL_REQUIRED:`callbackURL is required`,FAILED_TO_CREATE_VERIFICATION:`Unable to create verification`,FIELD_NOT_ALLOWED:`Field not allowed to be set`,ASYNC_VALIDATION_NOT_SUPPORTED:`Async validation is not supported`,VALIDATION_ERROR:`Validation Error`,MISSING_FIELD:`Field is required`,METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:`POST method requires deferSessionRefresh to be enabled in session config`,BODY_MUST_BE_AN_OBJECT:`Body must be an object`,PASSWORD_ALREADY_SET:`User already has a password set`}),xH=async()=>{let e=v(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await lH();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},SH=async e=>xH().then(t=>t.getStore()?.adapter||e).catch(()=>e),CH=async(e,t)=>{let n=!1;return xH().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},wH=async(e,t,n)=>{let r=!1;return xH().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=rt(e)?.();a&&await a;let o=[],s,c,l=!1;try{s=await e.transaction(async e=>(o=[],i.run({adapter:e,pendingHooks:o,isTransactionActive:!0},t)))}catch(e){l=!0,c=e}let u=async e=>{for(let t of o)try{await t()}catch(t){if(!n?.onAfterCommitHookError){if(e===`throw`)throw t;try{f.error(`Failed to run an after-commit hook for work that could not roll back`,t)}catch{}continue}try{await n.onAfterCommitHookError(t)}catch{}}};if(l)throw e.options?.adapterConfig.transaction===!1&&await u(`log`),c;return await u(`throw`),s}).catch(e=>{if(!r)return t();throw e})},TH=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await xH()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function EH(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function DH(e){let t=``;for(let n=0;n<e.length;n++)t+=EH(e[n]);return t}function OH(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${OH(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=DH(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`)l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);else{for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=EH(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:EH(t)}c+=l}}}return c}function kH(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function AH(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=OH(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=kH.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}function jH(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function MH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}function NH(e){try{return(MH(new URL(e).pathname)||`/`)!==`/`}catch{throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function PH(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new D(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof D?t:new D(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function FH(e,t=`/api/auth`){if(PH(e),NH(e))return e;let n=MH(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function IH(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function LH(e,t,n,r,i){if(e)return FH(e,t);if(r!==!1){let e=C.BETTER_AUTH_URL||C.NEXT_PUBLIC_BETTER_AUTH_URL||C.PUBLIC_BETTER_AUTH_URL||C.NUXT_PUBLIC_BETTER_AUTH_URL||C.NUXT_PUBLIC_AUTH_URL||(C.BASE_URL===`/`?void 0:C.BASE_URL);if(e)return FH(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&IH(o,`proto`)&&IH(a,`host`))try{return FH(`${o}://${a}`,t)}catch{}if(n){let e=RH(n.url);if(!e)throw new D(`Could not get origin from request. Please provide a valid base URL.`);return FH(e,t)}if(typeof window<`u`&&window.location)return FH(window.location.origin,t)}function RH(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function zH(e){try{return new URL(e).protocol}catch{return null}}function BH(e){try{return new URL(e).host}catch{return null}}function VH(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function HH(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function UH(e,t){let n=HH(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&IH(e,`host`))return e}let r=n.get(`host`);if(r&&IH(r,`host`))return r;if(HH(e))try{return new URL(e.url).host}catch{return null}return null}function WH(e,t,n){if(t===`http`||t===`https`)return t;let r=HH(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&IH(e,`proto`))return e}if(HH(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=UH(e,n);return i&&jH(i)?`http`:`https`}const GH=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?AH(r)(n):n.toLowerCase()===r.toLowerCase()};function KH(e,t,n,r){let i=UH(t,r);if(!i){if(e.fallback)return FH(e.fallback,n);throw new D(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>GH(i,e)))return FH(`${WH(t,e.protocol,r)}://${i}`,n);if(e.fallback)return FH(e.fallback,n);throw new D(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function qH(e,t,n,r,i){if(VH(e))return n?KH(e,n,t,i):e.fallback?FH(e.fallback,t):LH(void 0,t,void 0,r,i);let a=HH(n)?n:void 0;return LH(typeof e==`string`?e:void 0,t,a,r,i)}const JH=h(`a-z`,`0-9`,`A-Z`,`-_`);var YH=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ae(e),fe(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),we(r)}update(e){return de(this),this.iHash.update(e),this}digestInto(e){de(this),Te(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const XH=/* @__PURE__ */ (()=>{let e=((e,t,n)=>new YH(e,t).update(n).digest());return e.create=(e,t)=>new YH(e,t),e})(),ZH=/* @__PURE__ */ Uint8Array.of(0),QH=/* @__PURE__ */ Uint8Array.of();function $H(e,t,n,r=32,i){ae(e),Ce(r,`length`),fe(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=QH:fe(n,void 0,`info`),!o)return i&&we(t),/* @__PURE__ */ new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=XH.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){ZH[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(ZH).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(ZH[0]=o,o>1&&c.update(u),c.update(n).update(ZH).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&we(u),we(ZH),r===s.length)return s;let f=s.slice(0,r);return we(s),f}const eU=(e,t,n,r,i)=>{ae(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=XH.create(e,n).update(t);return $H(e,a.digest(),r,i,a)},tU=e=>e/2**32|0,nU=e=>e>>>0;function rU(e,t,n,r){let i=tU(n),a=nU(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function iU(e,t,n){return e&t^~e&n}function aU(e,t,n){return e&t^e&n^t&n}var oU=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=m(this.buffer)}update(e){de(this),fe(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=m(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){de(this),Te(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),rU(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:m(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const sU=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cU=/* @__PURE__ */ Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lU=/* @__PURE__ */ new Uint32Array(64);var uU=class extends oU{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)lU[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=lU[e-15],n=lU[e-2],r=w(t,7)^w(t,18)^t>>>3,i=w(n,17)^w(n,19)^n>>>10;lU[e]=i+lU[e-7]+r+lU[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=w(o,6)^w(o,11)^w(o,25),u=l+t+iU(o,s,c)+cU[e]+lU[e]|0,d=(w(n,2)^w(n,13)^w(n,22))+aU(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){we(lU)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),we(this.buffer)}},dU=class extends uU{constructor(){super(32,sU)}};const fU=/* @__PURE__ */ ne(()=>new dU,/* @__PURE__ */ eee(1));async function pU(e,t,n=3600){return await new cI(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function mU(e,t){try{return(await oI(e,new TextEncoder().encode(t))).payload}catch{return null}}const hU=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),gU=()=>Date.now()/1e3|0,_U=`A256CBC-HS512`;function vU(e,t){return eU(fU,new TextEncoder().encode(e),new TextEncoder().encode(t),hU,64)}function yU(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function bU(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function xU(e,t,n,r=3600){let i=vU(yU(t),n),a=await pI({kty:`oct`,k:xP(i)},`sha256`);return await new Tde(e).setProtectedHeader({alg:`dir`,enc:_U,kid:a}).setIssuedAt().setExpirationTime(gU()+r).setJti(crypto.randomUUID()).encrypt(i)}const SU={clockTolerance:15,keyManagementAlgorithms:[`dir`],contentEncryptionAlgorithms:[_U,`A256GCM`]};async function CU(e,t,n){if(!e)return null;let r=!1;try{r=bI(e).kid!==void 0}catch{return null}try{let r=bU(t),{payload:i}=await sI(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=vU(e.value,n);if(t===await pI({kty:`oct`,k:xP(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,vU(r[0].value,n)},SU);return i}catch{if(r)return null;let i=bU(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await sI(e,vU(r.value,n),SU);return a}catch{continue}return null}}function wU(e,t){typeof e==`string`&&(e=new TextEncoder().encode(e)),typeof t==`string`&&(t=new TextEncoder().encode(t));let n=new Uint8Array(e),r=new Uint8Array(t),i=n.length^r.length,a=Math.max(n.length,r.length);for(let e=0;e<a;e++)i|=(e<n.length?n[e]:0)^(e<r.length?r[e]:0);return i===0}const TU={N:16384,r:16,p:1,dkLen:64};function EU(e,t){return new Promise((n,r)=>{ot(e.normalize(`NFKC`),t,TU.dkLen,{N:TU.N,r:TU.r,p:TU.p,maxmem:128*TU.N*TU.r*2},(e,t)=>{e?r(e):n(t)})})}async function DU(e){let t=at(16).toString(`hex`);return`${t}:${(await EU(e,t)).toString(`hex`)}`}async function OU(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await EU(t,n)).toString(`hex`)===r}const kU=DU,AU=async({hash:e,password:t})=>OU(e,t);function jU(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function MU(e,t){return{digest:async n=>{let r=_e(n),i=await jU().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?ye.encode(i,{padding:t!==`base64urlnopad`}):ue.encode(i):i}}}
|
|
29
|
-
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
30
|
-
function NU(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const PU=e=>e?`"${e}" `:``;function FU(e,t=``){if(typeof e!=`boolean`)throw TypeError(PU(t)+`expected boolean, got type=`+typeof e);return e}function IU(e,t=``){if(typeof e!=`number`)throw TypeError(PU(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(PU(t)+`expected integer >= 0, got `+e);return e}function LU(e,t,n=``){if(NU(e)&&(t===void 0||e.length===t))return e;t!==void 0&&IU(t,`length`);let r=NU(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=PU(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const RU=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function zU(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function BU(e,t){LU(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function VU(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function HU(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function UU(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const WU=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function GU(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function KU(e){for(let t=0;t<e.length;t++)e[t]=GU(e[t]);return e}const qU=WU?e=>e:KU,JU=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,YU=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function XU(e){if(LU(e),JU)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=YU[e[n]];return t}function ZU(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function QU(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(JU)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=ZU(e.charCodeAt(i)),a=ZU(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function $U(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function eW(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function tW(e,t){if(eW(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function nW(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];LU(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function rW(e,t){return RU(e,`defaults`),RU(t,`opts`),Object.assign(e,t)}function iW(e,t){if(e=LU(e),t=LU(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function aW(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(/* @__PURE__ */ new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}const oW=(e,t)=>{function n(n,...r){if(LU(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];LU(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(NU(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&LU(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);LU(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,LU(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(LU(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function sW(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(LU(t,e,`output`),n&&!lW(t))throw Error(`invalid output, must be aligned`);return t}function cW(e,t,n){IU(e),IU(t),FU(n);let r=/* @__PURE__ */ new Uint8Array(16),i=UU(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function lW(e){return e.byteOffset%4==0}function uW(e){return Uint8Array.from(LU(e))}function dW(e=32){IU(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function fW(e,t=dW){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;IU(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=nW(e,t);return eW(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){LU(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){LU(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}const pW=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),mW=/* @__PURE__ */ qU(VU(pW(`expand 16-byte k`))),hW=/* @__PURE__ */ qU(VU(pW(`expand 32-byte k`)));function gW(e,t){return e<<t|e>>>32-t}const _W=2**32-1,vW=/* @__PURE__ */ Uint32Array.of();function yW(e,t,n,r,i,a,o,s){let c=i.length,l=/* @__PURE__ */ new Uint8Array(64),u=VU(l),d=WU&&lW(i)&&lW(a),f=d?VU(i):vW,p=d?VU(a):vW;if(WU)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=_W)throw Error(`arx: counter overflow`);let h=Math.min(64,c-m);if(d&&h===64){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<16;t++)n=e+t,p[n]=f[n]^u[t];m+=64}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),qU(u),o>=_W)throw Error(`arx: counter overflow`);let f=Math.min(64,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function bW(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=rW({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return IU(i),IU(o),FU(a),FU(n),(t,s,c,l,u=0)=>{LU(t,void 0,`key`),LU(s,void 0,`nonce`),LU(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=sW(d,l,!1),f&&tW(c,l),IU(u),u<0||u>=_W)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=uW(t)),g=hW;else if(m===16&&n)h=/* @__PURE__ */ new Uint8Array(32),h.set(t),h.set(t,16),g=mW,p.push(h);else throw LU(t,32,`arx key`),Error(`invalid key size`);(!WU||!lW(s))&&p.push(s=uW(s));let _=VU(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(WU)r(g,_,VU(e),_);else{let t=qU(Uint32Array.from(g));r(t,_,VU(e),_),HU(t),qU(_)}s=s.subarray(16)}else WU||qU(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=/* @__PURE__ */ new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=qU(VU(s));try{return yW(e,g,_,y,c,l,u,o),l}finally{HU(...p)}}}function xW(e,t){return e[t++]&255|(e[t++]&255)<<8}var SW=class{blockLen=16;outputLen=16;buffer=/* @__PURE__ */ new Uint8Array(16);r=/* @__PURE__ */ new Uint16Array(10);h=/* @__PURE__ */ new Uint16Array(10);pad=/* @__PURE__ */ new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=uW(LU(e,32,`key`));let t=xW(e,0),n=xW(e,2),r=xW(e,4),i=xW(e,6),a=xW(e,8),o=xW(e,10),s=xW(e,12),c=xW(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=xW(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=xW(e,t+0),_=xW(e,t+2),v=xW(e,t+4),y=xW(e,t+6),b=xW(e,t+8),x=xW(e,t+10),S=xW(e,t+12),ee=xW(e,t+14),C=i[0]+(g&8191),te=i[1]+((g>>>13|_<<3)&8191),ne=i[2]+((_>>>10|v<<6)&8191),w=i[3]+((v>>>7|y<<9)&8191),T=i[4]+((y>>>4|b<<12)&8191),re=i[5]+(b>>>1&8191),ie=i[6]+((b>>>14|x<<2)&8191),ae=i[7]+((x>>>11|S<<5)&8191),oe=i[8]+((S>>>8|ee<<8)&8191),se=i[9]+(ee>>>5|r),ce=0,le=ce+C*o+5*h*te+5*m*ne+5*p*w+5*f*T;ce=le>>>13,le&=8191,le+=5*d*re+5*u*ie+5*l*ae+5*c*oe+5*s*se,ce+=le>>>13,le&=8191;let ue=ce+C*s+te*o+5*h*ne+5*m*w+5*p*T;ce=ue>>>13,ue&=8191,ue+=5*f*re+5*d*ie+5*u*ae+5*l*oe+5*c*se,ce+=ue>>>13,ue&=8191;let de=ce+C*c+te*s+ne*o+5*h*w+5*m*T;ce=de>>>13,de&=8191,de+=5*p*re+5*f*ie+5*d*ae+5*u*oe+5*l*se,ce+=de>>>13,de&=8191;let fe=ce+C*l+te*c+ne*s+w*o+5*h*T;ce=fe>>>13,fe&=8191,fe+=5*m*re+5*p*ie+5*f*ae+5*d*oe+5*u*se,ce+=fe>>>13,fe&=8191;let pe=ce+C*u+te*l+ne*c+w*s+T*o;ce=pe>>>13,pe&=8191,pe+=5*h*re+5*m*ie+5*p*ae+5*f*oe+5*d*se,ce+=pe>>>13,pe&=8191;let me=ce+C*d+te*u+ne*l+w*c+T*s;ce=me>>>13,me&=8191,me+=re*o+5*h*ie+5*m*ae+5*p*oe+5*f*se,ce+=me>>>13,me&=8191;let he=ce+C*f+te*d+ne*u+w*l+T*c;ce=he>>>13,he&=8191,he+=re*s+ie*o+5*h*ae+5*m*oe+5*p*se,ce+=he>>>13,he&=8191;let ge=ce+C*p+te*f+ne*d+w*u+T*l;ce=ge>>>13,ge&=8191,ge+=re*c+ie*s+ae*o+5*h*oe+5*m*se,ce+=ge>>>13,ge&=8191;let _e=ce+C*m+te*p+ne*f+w*d+T*u;ce=_e>>>13,_e&=8191,_e+=re*l+ie*c+ae*s+oe*o+5*h*se,ce+=_e>>>13,_e&=8191;let ve=ce+C*h+te*m+ne*p+w*f+T*d;ce=ve>>>13,ve&=8191,ve+=re*u+ie*l+ae*c+oe*s+se*o,ce+=ve>>>13,ve&=8191,ce=(ce<<2)+ce|0,ce=ce+le|0,le=ce&8191,ce>>>=13,ue+=ce,i[0]=le,i[1]=ue,i[2]=de,i[3]=fe,i[4]=pe,i[5]=me,i[6]=he,i[7]=ge,i[8]=_e,i[9]=ve}finalize(){let{h:e,pad:t}=this,n=/* @__PURE__ */ new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;HU(n)}update(e){zU(this),LU(e),e=uW(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,HU(this.h,this.r,this.buffer,this.pad)}digestInto(e){zU(this),BU(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};const CW=/* @__PURE__ */ aW(32,e=>new SW(e));function wW(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,ee=s,C=c,te=l,ne=u,w=d,T=f,re=p,ie=m,ae=h,oe=g,se=_,ce=v,le=y,ue=b,de=x;for(let e=0;e<a;e+=2)S=S+ne|0,ce=gW(ce^S,16),ie=ie+ce|0,ne=gW(ne^ie,12),S=S+ne|0,ce=gW(ce^S,8),ie=ie+ce|0,ne=gW(ne^ie,7),ee=ee+w|0,le=gW(le^ee,16),ae=ae+le|0,w=gW(w^ae,12),ee=ee+w|0,le=gW(le^ee,8),ae=ae+le|0,w=gW(w^ae,7),C=C+T|0,ue=gW(ue^C,16),oe=oe+ue|0,T=gW(T^oe,12),C=C+T|0,ue=gW(ue^C,8),oe=oe+ue|0,T=gW(T^oe,7),te=te+re|0,de=gW(de^te,16),se=se+de|0,re=gW(re^se,12),te=te+re|0,de=gW(de^te,8),se=se+de|0,re=gW(re^se,7),S=S+w|0,de=gW(de^S,16),oe=oe+de|0,w=gW(w^oe,12),S=S+w|0,de=gW(de^S,8),oe=oe+de|0,w=gW(w^oe,7),ee=ee+T|0,ce=gW(ce^ee,16),se=se+ce|0,T=gW(T^se,12),ee=ee+T|0,ce=gW(ce^ee,8),se=se+ce|0,T=gW(T^se,7),C=C+re|0,le=gW(le^C,16),ie=ie+le|0,re=gW(re^ie,12),C=C+re|0,le=gW(le^C,8),ie=ie+le|0,re=gW(re^ie,7),te=te+ne|0,ue=gW(ue^te,16),ae=ae+ue|0,ne=gW(ne^ae,12),te=te+ne|0,ue=gW(ue^te,8),ae=ae+ue|0,ne=gW(ne^ae,7);let fe=0;r[fe++]=o+S|0,r[fe++]=s+ee|0,r[fe++]=c+C|0,r[fe++]=l+te|0,r[fe++]=u+ne|0,r[fe++]=d+w|0,r[fe++]=f+T|0,r[fe++]=p+re|0,r[fe++]=m+ie|0,r[fe++]=h+ae|0,r[fe++]=g+oe|0,r[fe++]=_+se|0,r[fe++]=v+ce|0,r[fe++]=y+le|0,r[fe++]=b+ue|0,r[fe++]=x+de|0}function TW(e,t,n,r){let i=WU?e:qU(e.slice(0,4)),a=WU?t:qU(t.slice(0,8)),o=WU?n:qU(n.slice(0,4)),s=/* @__PURE__ */ new Uint32Array(16);wW(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,qU(r),WU||HU(i,a,o),HU(s)}const EW=/* @__PURE__ */ bW(wW,{counterRight:!1,counterLength:8,extendNonceFn:TW,allowShortKeys:!1}),DW=/* @__PURE__ */ new Uint8Array(16),OW=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(DW.subarray(n))},kW=/* @__PURE__ */ new Uint8Array(32);function AW(e,t,n,r,i){i!==void 0&&LU(i,void 0,`AAD`);let a=e(t,n,kW),o=cW(r.length,i?i.length:0,!0),s=CW.create(a);i&&OW(s,i),OW(s,r),s.update(o);let c=s.digest();return HU(a,o),c}const jW=/* @__PURE__ */ oW({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},/* @__PURE__ */ (e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=sW(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=AW(e,t,n,s,r);return a.set(c,o),HU(c),a},decrypt(i,a){a=sW(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=AW(e,t,n,o,r);if(!iW(s,c))throw HU(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),HU(c),a}}))(EW)),MW={name:`HMAC`,hash:`SHA-256`},NW=`$ba$`;function PW(e){if(!e.startsWith(NW))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function FW(e,t){return`${NW}${e}$${t}`}async function IW(e,t){let n=await MU(`SHA-256`).digest(e),r=$U(t);return XU(fW(jW)(new Uint8Array(n)).encrypt(r))}async function LW(e,t){let n=await MU(`SHA-256`).digest(e),r=QU(t),i=fW(jW)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}const RW=async({key:e,data:t})=>{if(typeof e==`string`)return IW(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await IW(n,t);return FW(e.currentVersion,r)},zW=async({key:e,data:t})=>{if(typeof e==`string`)return LW(e,t);let n=PW(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return LW(t,n.ciphertext)}if(e.legacySecret)return LW(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},BW=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await jU().importKey(`raw`,t,MW,!1,[`sign`,`verify`])},VW=async(e,t)=>{let n=await BW(t),r=await jU().sign(MW.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))};function HW(e){return!!e.database||!!e.secondaryStorage}function UW(e){return!!e.database}function WW(e){return UW(e)}function GW(e){return Pe(nee,e)}function KW(e){return ke(qe,e)}function qW(e){return Ae(Qe,e)}const JW=A({id:k(),createdAt:$e().default(()=>/* @__PURE__ */ new Date),updatedAt:$e().default(()=>/* @__PURE__ */ new Date)}),YW=JW.extend({userId:GW(),expiresAt:$e(),token:k(),ipAddress:k().nullish(),userAgent:k().nullish()}),XW=JW.extend({email:k().transform(e=>e.toLowerCase()),emailVerified:Ge().default(!1),name:k(),image:k().nullish()});function ZW(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}const QW=/* @__PURE__ */ new WeakMap;function $W(e,t,n){let r=`${t}:${n}`;QW.has(e)||QW.set(e,/* @__PURE__ */ new Map);let i=QW.get(e);if(i.has(r))return i.get(r);let a=n===`output`?p(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function eG(e,t){return ZW(t,$W(e,`user`,`output`))}function tG(e,t){let n=$W(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function nG(e,t){return ZW(t,$W(e,`session`,`output`))}function rG(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=ZW(t,$W(e,`account`,`output`));return c}function iG(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r)if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw E.from(`BAD_REQUEST`,{...Y.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw E.from(`INTERNAL_SERVER_ERROR`,Y.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw E.from(`BAD_REQUEST`,{...Y.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t]}else if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue}else if(r[t].required&&n===`create`)throw E.from(`BAD_REQUEST`,{...Y.MISSING_FIELD,message:`${t} is required`});return i}function aG(e,t={},n){return iG(t,{fields:$W(e,`user`,`input`),action:n})}function oG(e,t={},n){let r=$W(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return iG(i,{fields:r,action:n})}function sG(e,t,n){return iG(t,{fields:$W(e,`session`,`input`),action:n})}function cG(e){let t=$W(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}function lG(e,t){if(!t)return e;for(let n in t){let r=t[n]?.modelName;r&&(e[n].modelName=r);for(let r in e[n].fields){let i=t[n]?.fields?.[r];i&&(e[n].fields[r].fieldName=i)}}return e}const uG=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function dG(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}const fG=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function pG(e){let t=fG.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*315576e5;break;case`months`:case`month`:case`mo`:i=n*2592e6;break;case`weeks`:case`week`:case`w`:i=n*6048e5;break;case`days`:case`day`:case`d`:i=n*864e5;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*36e5;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*6e4;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*1e3;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function mG(e){return Math.round(pG(e)/1e3)}const hG=Ve({session:YW.loose(),user:XW.loose(),updatedAt:Fe(),version:k().optional()}),gG=A({session:Ie(k(),et()),expiresAt:Fe(),signature:k()});function _G(e){let t=le(e);if(t===null)return null;let n=hG.safeParse(t);return n.success?n.data:(f.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function vG(e){let t=gG.safeParse(e);return t.success?t.data:null}function yG(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function bG(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}function xG(e){let t=/* @__PURE__ */ new Map;return bG(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=wG(a.join(`=`));if(!i)return;let s={value:yG(o)};r.forEach(e=>{let[t,...n]=e.split(`=`),r=n.join(`=`),i=t.trim().toLowerCase();switch(i){case`max-age`:s[`max-age`]=r?parseInt(r.trim(),10):void 0;break;case`expires`:s.expires=r?new Date(r.trim()):void 0;break;case`domain`:s.domain=r?r.trim():void 0;break;case`path`:s.path=r?r.trim():void 0;break;case`secure`:s.secure=!0;break;case`httponly`:s.httponly=!0;break;case`samesite`:s.samesite=r?r.trim().toLowerCase():void 0;break;case`partitioned`:s.partitioned=!0;break;default:s[i]=!r||r.trim()}}),t.set(i,s)}),t}const SG=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,CG=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function wG(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function TG(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function EG(e){let t=/* @__PURE__ */ new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=TG(n.slice(0,e)),i=wG(TG(n.slice(e+1)));SG.test(r)&&CG.test(i)&&t.set(r,yG(i))}return t}function DG(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function OG(e){let t=_G(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}const kG={name:`HMAC`,hash:`SHA-256`},AG=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await jU().importKey(`raw`,t,kG,!1,[`sign`,`verify`])},jG=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await jU().verify(kG,n,i,new TextEncoder().encode(t))}catch{return!1}},MG=async(e,t)=>{let n=await AG(t),r=await jU().sign(kG.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},NG=async(e,t)=>{let n=await MG(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},PG=/^application\/([a-z0-9.+-]*\+)?json/i;async function FG(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new O(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new O(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(PG.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new O(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function IG(e){return e instanceof O||e?.name===`APIError`}function LG(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function RG(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function zG(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const BG={secure:`__Secure-`,host:`__Host-`},VG=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return BG[t]+e};function HG(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=/* @__PURE__ */ new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,LG(n))}n=i+1}return t}function UG(e,t,n={}){let r=VG(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function WG({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}const GG=(e,t,n)=>(t=encodeURIComponent(t),WG(UG(e,t,n))),KG=async(e,t,n,r)=>(t=await NG(t,n),WG(UG(e,t,r)));async function qG(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:JG(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:JG(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function JG(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}const YG=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await qG(t,e);if(o)throw new Me(o.message,o.issues);let s=e.headers===void 0?`request`in e&&zG(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?HG(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=VG(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=VG(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await jG(s,o,await AG(t))?o:!1},setCookie:(e,t,n)=>{let i=GG(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await KG(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new O(`FOUND`,void 0,r)),error:(e,t,n)=>new O(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function XG(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function ZG(e){let t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function QG(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const $G=/* @__PURE__ */ new Set(/* @__PURE__ */ `host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function eK(e){for(let t of $G)e.delete(t)}function tK(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function nK(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);eK(n),tK(e.headers,n)}return e}if(QG(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(tK(i,r?.headers),tK(i,e.headers),t?.headers){let e=new Headers(t.headers);eK(e),tK(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(IG(e))return nK(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return eK(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):XG(e)&&(n=ZG(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function rK(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new je(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new je(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await RG(YG(t,{options:i,path:r}));if(o)throw o instanceof Me?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new O(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(IG(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?nK(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function iK(e,t){return[...e??[],...t??[]]}rK.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return rK(n,{...r,use:iK(r.use,e?.use)},i)}let[n,r]=t;return rK({...n,use:iK(n.use,e?.use)},r)}return t};function aK(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await YG(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw IG(e)&&Object.defineProperty(e,Ne,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}aK.create=e=>{function t(t,n){if(typeof t==`function`)return aK({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return aK({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};const oK={};function sK(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function cK(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof Xe&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof Xe&&t.push({name:e,in:`query`,schema:{type:sK(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function lK(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof Xe||e.body instanceof He)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof Xe&&(n[e]={type:sK(t),description:t.description},t instanceof He||r.push(e))}),{required:e.body instanceof He?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function uK(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function dK(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(oK[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cK(n),responses:uK(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=lK(n);oK[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cK(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:uK(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:oK}}const fK=(e,t)=>`<!doctype html>
|
|
31
|
-
<html>
|
|
32
|
-
<head>
|
|
33
|
-
<title>Scalar API Reference</title>
|
|
34
|
-
<meta charset="utf-8" />
|
|
35
|
-
<meta
|
|
36
|
-
name="viewport"
|
|
37
|
-
content="width=device-width, initial-scale=1" />
|
|
38
|
-
</head>
|
|
39
|
-
<body>
|
|
40
|
-
<script
|
|
41
|
-
id="api-reference"
|
|
42
|
-
type="application/json">
|
|
43
|
-
${JSON.stringify(e)}
|
|
44
|
-
<\/script>
|
|
45
|
-
<script>
|
|
46
|
-
var configuration = {
|
|
47
|
-
favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
|
|
48
|
-
theme: ${t?.theme||`saturn`},
|
|
49
|
-
metaData: {
|
|
50
|
-
title: ${t?.title||`Open API Reference`},
|
|
51
|
-
description: ${t?.description||`Better Call Open API`},
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
document.getElementById('api-reference').dataset.configuration =
|
|
55
|
-
JSON.stringify(configuration)
|
|
56
|
-
<\/script>
|
|
57
|
-
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
|
|
58
|
-
</body>
|
|
59
|
-
</html>`,pK=/* @__PURE__ */ (()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function mK(){return{root:{key:``},static:new pK}}function hK(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function gK(e){if(!e.includes(`{`))return;let t=hK(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}function _K(e){return`__rou3_unnamed_${e}`}function vK(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:`__rou3_esc_`+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function yK(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function bK(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92)n++;else if(r===40)t++;else if(r===41&&t>0)t--;else if(r===42&&t===0)return!0}return!1}function xK(e,t,n=_K){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);o===92?(a+=e[t],t+1<e.length&&(a+=e[++t])):o===40?(r++,a+=e[t]):o===41&&r>0?(r--,a+=e[t]):a+=o===42&&r===0?`(?<${n(i++)}>[^/]*)`:e[t]}return[a,i]}function SK(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function CK(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||bK(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function wK(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function TK(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function EK(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function DK(e){let t=EK(e);for(;t[t.length-1]===``;)t.pop();return t}function OK(e,t){let n=new pK;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[yK(t)]=e.groups[t]}}return n}function kK(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=gK(n);if(i){for(let n of i)kK(e,t,n,r);return}n=SK(n);let a=DK(n),o=wK(a);if(o){for(let n of o)kK(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=CK(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=AK(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new pK),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new pK;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function AK(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=``+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=xK(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${vK(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${_K(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function jK(e,t=``,n,r){r?.normalize&&(n=TK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=EK(n),o=MK(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?OK(a,o.paramsMap):void 0}}function MK(e,t,n,r){if(r===n.length){if(e.methods){let r=NK(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&NK(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&NK(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=MK(a,t,n,r+1);if(e)return e}}if(e.param){let i=MK(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return NK(e.wildcard.methods,t,n,!0,!1)}function NK(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function PK(e,t=``,n,r){r?.normalize&&(n=TK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=EK(n),a=FK(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?OK(i,e.paramsMap):void 0}))}function FK(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)IK(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}IK(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(FK(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}IK(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&FK(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&IK(i,n,e.key===`*`)}return i}function IK(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}const LK=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=rK(n.path,{method:`GET`},async t=>{let r=await dK(e);return new Response(fK(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=mK(),r=mK();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)kK(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)kK(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=jK(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await FG(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=PK(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return nK(r)}catch(e){if(IG(e))return nK(e);throw e}if(t?.throwError)throw n;return IG(n)?nK(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=zG(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}},RK=4050;function zK(e,t){return RK-GG(e,``,{...t}).length}function BK(e,t){let n=`${e}.`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=Number(r);return!Number.isSafeInteger(i)||i<0||String(i)!==r?null:i}function VK(e,t){let n={},r=EG(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||BK(e,t)!==null)&&(n[t]=i);return n}function HK(e,t,n,r){let i=zK(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>100)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${RK} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function UK(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}const WK=e=>(t,n,r)=>{let i=VK(t,r),a=r.context.logger,o=()=>{let e=UK(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=HK(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},GK=WK(`Session`),KK=WK(`Account`);function qK(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of EG(i)){let i=BK(t,e);i!==null&&r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function JK(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await xU(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=KK(n.name,r,e);a.setCookies(a.chunk(i,r))}async function YK(e){let t=qK(e,e.context.authCookies.accountData.name);if(t){let n=le(await CU(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}const XK=nt(A({disableCookieCache:qW().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:qW().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()})),ZK=/* @__PURE__ */ new Map,QK=new TextEncoder,$K={decode:(e,t=`utf-8`)=>(ZK.has(t)||ZK.set(t,new TextDecoder(t)),ZK.get(t).decode(e)),encode:e=>QK.encode(e)},eq=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>jU().importKey(`raw`,_e(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await jU().sign(`HMAC`,e,_e(r));return t===`hex`?Se.encode(i):t===`base64`?ue.encode(i):t===`base64url`||t===`base64urlnopad`?ye.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=typeof i==`string`?Se.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await ue.decode(i)),jU().verify(`HMAC`,e,_e(i),_e(r)))};return n};function tq(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):te):e.advanced?.useSecureCookies)?`__Secure-`:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!VH(e.baseURL))throw new D(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function nq(e){let t=tq(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||mG(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function rq(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=ZW(t.session,e.context.options.session?.additionalFields),i=eG(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=dG(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=uG(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await xU(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;d=t?await t.sign(e,s,c.maxAge||300):await pU(s,e.context.secret,c.maxAge||300)}else d=ye.encode(JSON.stringify({session:s,expiresAt:l,signature:await eq(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=GK(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!sq(e,e.context.authCookies.accountData.name)){let n=await YK(e);if(n){if(!WW(e.context.options)||n.userId===t.user.id)await JK(e,n);else{cq(e,e.context.authCookies.accountData);let t=KK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function iq(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await CU(t,e.context.secretConfig,`better-auth-session`),r=_G(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await mU(t,e.context.secret),i=_G(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=vG(le($K.decode(ye.decode(t))));if(!r||!await eq(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=_G(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function aq(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await rq(e,t,n),e.context.setNewSession(t)}function oq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():bG(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function sq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():bG(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function cq(e,t){oq(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function lq(e,t){if(cq(e,e.context.authCookies.sessionToken),cq(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){cq(e,e.context.authCookies.accountData);let t=KK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&cq(e,e.context.createAuthCookie(`oauth_state`));let n=GK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||cq(e,e.context.authCookies.dontRememberToken)}const uq=g(`better-auth:oauth-encryption:v1`);function dq(e,t){return se(eU(fU,g(e),uq,g(`better-auth:${t}:v1`),32))}function fq(e,t){return typeof e==`string`?dq(e,t):{keys:new Map(Array.from(e.keys,([e,n])=>[e,dq(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:dq(e.legacySecret,t)}}}const pq=Ve({callbackURL:k(),codeVerifier:k(),errorURL:k().optional(),newUserURL:k().optional(),expiresAt:Fe(),oauthState:k().optional(),link:A({email:k(),userId:GW()}).optional(),requestSignUp:Ge().optional(),idTokenNonce:k().optional(),serverContext:Ie(k(),et()).optional()}),mq=e=>`auth-state:${e}`;new Set(Object.keys(pq.shape));var hq=class extends D{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function gq(e,t,n){let r=JH(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await RW({key:fq(e.context.secretConfig,`oauth-state-cookie`),data:JSON.stringify(i)}),o=e.context.createAuthCookie(n?.cookieName??`oauth_state`,{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:r,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(n?.cookieName??`state`,{maxAge:300});await e.setSignedCookie(i.name,r,e.context.secret,i.attributes);let a=/* @__PURE__ */ new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:r}),identifier:mq(r),expiresAt:a}))throw new hq(`Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database`,{code:`state_generation_error`});return{state:r,codeVerifier:t.codeVerifier}}async function _q(e,t,n){if(!t)throw new hq(`State not found in OAuth callback`,{code:`state_not_found`});let r=e.context.oauthConfig.storeStateStrategy,i;if(r===`cookie`){let r=e.context.createAuthCookie(n?.cookieName??`oauth_state`),a=e.getCookie(r.name);if(!a)throw new hq(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await zW({key:fq(e.context.secretConfig,`oauth-state-cookie`),data:a});i=pq.parse(JSON.parse(t))}catch(e){throw new hq(`State invalid: Failed to decrypt or parse auth state`,{code:`state_invalid`,details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new hq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});cq(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(mq(t));if(!r)throw new hq(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=pq.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new hq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});let a=e.context.createAuthCookie(n?.cookieName??`state`),o=await e.getSignedCookie(a.name,e.context.secret);if(!(n?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new hq(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});cq(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(mq(t))}if(i.expiresAt<Date.now())throw new hq(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function vq(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}const yq=`https://better-auth.invalid`;function bq(e,t){let n=e.startsWith(`/`);if(e.startsWith(`//`)||e.startsWith(`/\\`))throw TypeError(`Expected an absolute or root-relative URL`);let r=n?new URL(e,yq):new URL(e);if(n&&r.origin!==yq)throw TypeError(`Expected an absolute or root-relative URL`);let i=t.toString();if(!i)return e;let a=r.search.endsWith(`&`)?``:`&`;return r.search=r.search?`${r.search}${a}${i}`:i,n?r.href.slice(r.origin.length):r.href}const xq=[`javascript:`,`data:`,`vbscript:`],Sq={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`};function Cq(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=bq(t,i);throw e.redirect(a)}function wq(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}const{get:Tq,set:Eq}=yH(()=>null),Dq=async()=>await Tq(),{get:Oq,set:kq}=yH(()=>null),Aq=async e=>{await kq({...await Oq()??{},...e})};function jq(e){return e.requiresIdTokenNonce?JH(32):void 0}async function Mq(e,t){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw E.from(`BAD_REQUEST`,Y.CALLBACK_URL_REQUIRED);let r=t?.codeVerifier??JH(128),i=await Oq(),a=i&&Object.keys(i).length?i:void 0,o={...t?.additionalData?t.additionalData:{},callbackURL:n,codeVerifier:r,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:a,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await Eq(o);try{return gq(e,o)}catch(t){throw e.context.logger.error(`Failed to create verification`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`Unable to create verification`,cause:t})}}async function Nq(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await _q(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof hq&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL||n),Cq(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await Eq(r),r}const Pq={scope:`server`};function Fq(e){return e instanceof O||e instanceof E||e?.name===`APIError`}const Iq={"Cache-Control":`no-store`,Pragma:`no-cache`};function Lq(e,t){Fq(t)&&e&&Object.defineProperty(t,Ne,{enumerable:!1,configurable:!0,value:e,writable:!1})}const Rq=aK(async()=>({})),zq=aK.create({use:[Rq,aK(async()=>({}))]}),Bq=rK.create({use:[Rq]});function Vq(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(Iq))t.setHeader(e,n);try{return await mH(t,()=>e(t))}catch(e){throw Lq(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Bq(t,n,Vq(r,n))}let[t,n]=e;return Bq(t,Vq(n,t))}function Hq(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Hq(e),t);const Uq=/[\u0000-\u001f\u007f-\u009f]/,Wq=`https://better-auth.invalid`,Gq=/%2[fF]|%5[cC]/,Kq=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},qq=e=>{if(Uq.test(e))return null;let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=r.search(/[?#]/),o=Kq(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},Jq=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||Uq.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(Gq.test(n))return!1;try{return new URL(e,Wq).origin===Wq}catch{return!1}},Yq=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&Jq(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return AH(t)(RH(e)||e);let n=BH(e);return n?AH(t)(n):!1}let r=zH(e);if(r===`http:`||r===`https:`||!r)return t===RH(e);let i=qq(e),a=qq(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function Xq(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function Zq(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function Qq(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=vq(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}const $q=Xq(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),eJ=zq(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await nJ(e),Qq(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw E.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),tJ=e=>zq(async t=>{if(!t.request||Qq(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function nJ(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`),i=r||n.get(`referer`)||``,a=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(Zq(e)){e.context.options.advanced?.disableOriginCheck===!0&&$q();return}if(Qq(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?LH(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?RH(o):void 0)??i;if(!s||s===`null`)throw E.from(`FORBIDDEN`,Y.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!c.some(e=>Yq(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${c}`),E.from(`FORBIDDEN`,Y.INVALID_ORIGIN)}const rJ=zq(async e=>{e.request&&await iJ(e)});async function iJ(e){let t=e.request;if(!t||e.context.skipCSRFCheck||Zq(e))return;let n=t.headers;if(n.has(`cookie`))return await nJ(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),E.from(`FORBIDDEN`,Y.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await nJ(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await nJ(e,!0)}const aJ=ze(),oJ=Ye();function sJ(e){return cJ(e)||lJ(e)}function cJ(e){return We(aJ,e)}function lJ(e){return We(oJ,e)}function uJ(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(cJ(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&cJ(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=dJ(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function dJ(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function fJ(e,t){let n=dJ(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function pJ(e,t={}){if(cJ(e)||!lJ(e))return e.toLowerCase();let n=uJ(e);return n?n.toLowerCase():fJ(e,t.ipv6Subnet??64)}function mJ(e){if(cJ(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!lJ(e))return null;let t=uJ(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=dJ(e),r=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}const hJ=/^\d+$/;function gJ(e){let t=e.lastIndexOf(`/`),n=mJ(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!hJ.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function _J(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function vJ(e){return e.filter(e=>gJ(e)===null)}function yJ(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(gJ).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?mJ(i):null;if(!i||!a)return null;if(!r.some(e=>_J(a,e)))return pJ(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!sJ(i)?null:pJ(i,{ipv6Subnet:t.ipv6Subnet})}const bJ=[`x-forwarded-for`];function xJ(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||bJ;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=yJ(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return Ee()||S()?`127.0.0.1`:null}function SJ(e,t){return`${e}|${t}`}const CJ=/* @__PURE__ */ new Map,wJ=1e5;function TJ(){let e=Date.now();for(let[t,n]of CJ)e>=n.expiresAt&&CJ.delete(t);if(CJ.size<=wJ)return;let t=CJ.size-wJ,n=0;for(let e of CJ.keys())if(CJ.delete(e),++n>=t)break}function EJ(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:OJ(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function DJ(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"Content-Type":`application/json`,"X-Retry-After":e.toString()}})}function OJ(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function kJ(e){let t=`rateLimit`,n=e.adapter,r=Math.max(...AJ(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return typeof r?.lastRequest==`bigint`&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:OJ(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function AJ(e){let t=[e.rateLimit.window,...FJ().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function jJ(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new D(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){TJ();let r=Date.now(),i=CJ.get(e),a=EJ(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&CJ.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return kJ(e)}let MJ=!1;async function NJ(e,t){let n=new URL(t.baseURL).pathname,r=vq(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=xJ(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!MJ&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),MJ=!0);let s=SJ(o??`no-trusted-ip`,r),c=FJ().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?AH(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function PJ(e,t){if(!t.rateLimit.enabled)return;let n=await NJ(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=jJ(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return DJ(l??i)}function FJ(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}const{get:IJ,set:pfe}=yH(()=>!1),LJ=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:XK,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw E.from(`METHOD_NOT_ALLOWED`,Y.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&r)return null;let a=qK(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=GK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!i)return null;let o=r&&!e.query?.disableCookieCache,s=o&&a?await iq(e,a):null;o&&a&&!s&&cq(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,n=t.session.token!==i;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=s.expiresAt<e||!Number.isFinite(r)||r<e}if(n)cq(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=nG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=eG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=s.expiresAt-Date.now(),i=n.updateAge*1e3,a=await IJ();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await rq(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=nG(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=eG(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:o},e.json({session:a,user:o})}let o=nG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=eG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:o,user:l},e.json({session:o,user:l})}}let l=await e.context.internalAdapter.findSession(i);if(e.context.session=l,!l||l.session.expiresAt</* @__PURE__ */ new Date)return lq(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=nG(e.context.options,l.session),n=eG(e.context.options,l.user);return e.json({session:t,user:n})}let u=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge,f=l.session.expiresAt.valueOf()-u*1e3+d*1e3<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,m=await IJ(),h=f&&!p&&!m;if(t&&!n){await rq(e,l,!!c);let t=nG(e.context.options,l.session),n=eG(e.context.options,l.user);return e.json({session:t,user:n,needsRefresh:h})}if(h){let t=await e.context.internalAdapter.updateSession(l.session.token,{expiresAt:uG(e.context.sessionConfig.expiresIn,`sec`),updatedAt:/* @__PURE__ */ new Date});if(!t)throw lq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await aq(e,{session:t,user:l.user},!1,{maxAge:n});let r=nG(e.context.options,t),i=eG(e.context.options,l.user);return e.json({session:r,user:i})}await rq(e,l,!!c);let g=nG(e.context.options,l.session),_=eG(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Fq(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION))}}),RJ=e=>HW(e.context.options),zJ=async(e,t)=>{if(e.context.session)return e.context.session;let n=await LJ()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},BJ=async e=>RJ(e)?(e.context.session=null,zJ(e,{disableCookieCache:!0})):zJ(e),VJ=zq(async e=>{let t=await zJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),HJ=zq(async e=>{let t=await BJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});zq(async e=>{let t=await zJ(e);if(!t?.session&&(e.request||e.headers))throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});const UJ=zq(async e=>{let t=await zJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`FORBIDDEN`,Y.SESSION_NOT_FRESH)}return{session:t}}),WJ=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[UJ],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>/* @__PURE__ */ new Date);return e.json(t.map(t=>nG(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),GJ=X(`/revoke-session`,{method:`POST`,body:A({token:k().meta({description:`The token to revoke`})}),use:[HJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),KJ=X(`/revoke-sessions`,{method:`POST`,use:[HJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),qJ=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[HJ],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>/* @__PURE__ */ new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function JJ(e){if(!e?.method)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function YJ(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;JJ(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new E(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new E(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}const XJ=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})};async function ZJ(e,t){return!t||t===`plain`?e:t===`hashed`?XJ(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function QJ(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}const $J=`better_auth.operation_id`,eY=`better_auth.hook.type`,tY=`better_auth.context`;function nY(e,t){let n=oe(t.options),r=t.hooks;async function i(t,i,a){let o=fH(),s=t;for(let{source:e,hooks:t}of r){let r=t[i]?.create?.before;if(r){let t=await n(`db create.before ${i}`,{[eY]:`create.before`,[ve]:i,[tY]:e},()=>r(s,o));if(t===!1)return null;typeof t==`object`&&`data`in t&&(s={...s,...t.data})}}let c=null;(!a||a.executeMainFn)&&(c=await(await SH(e)).create({model:i,data:s,forceAllowId:!0})),a?.fn&&(c=await a.fn(c??s));for(let{source:e,hooks:t}of r){let r=t[i]?.create?.after;r&&await TH(async()=>{await n(`db create.after ${i}`,{[eY]:`create.after`,[ve]:i,[tY]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=fH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db update.before ${a}`,{[eY]:`update.before`,[ve]:a,[tY]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await SH(e)).update({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await TH(async()=>{await n(`db update.after ${a}`,{[eY]:`update.after`,[ve]:a,[tY]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=fH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db updateMany.before ${a}`,{[eY]:`updateMany.before`,[ve]:a,[tY]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await SH(e)).updateMany({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await TH(async()=>{await n(`db updateMany.after ${a}`,{[eY]:`updateMany.after`,[ve]:a,[tY]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=fH(),s=null;try{s=(await(await SH(e)).findMany({model:i,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":e},()=>r(s,o))===!1)return null}let c=a?await a.fn(t):null,l=(!a||a.executeMainFn)&&s?await(await SH(e)).delete({model:i,where:t}):c;if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${i}`,{[eY]:`delete.after`,[ve]:i,[tY]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=fH(),s=[];try{s=await(await SH(e)).findMany({model:i,where:t})}catch{}for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":t},()=>r(e,o))===!1)return null}let c=a?await a.fn(t):null,l=!a||a.executeMainFn?await(await SH(e)).deleteMany({model:i,where:t}):c;for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${i}`,{[eY]:`delete.after`,[ve]:i,[tY]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=fH(),c=r.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),l=o??null;if(c.length){if(!l)try{l=(await(await SH(e)).findMany({model:t,where:i,limit:1}))[0]||null}catch{}if(l){for(let{source:e,fn:r}of c)if(await n(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>r(l,s))===!1)return null}}let u=await a();if(!u)return null;for(let{source:e,hooks:i}of r){let r=i[t]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${t}`,{[eY]:`delete.after`,[ve]:t,[tY]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function rY(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}const iY=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=/* @__PURE__ */ new Map,o=r.session?.expiresIn||604800,s=!!i&&r.session?.storeSessionInDatabase===!0&&r.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:u,deleteWithHooks:d,deleteManyWithHooks:f,consumeOneWithHooks:p}=nY(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await SH(e)).updateMany({model:`session`,where:n,update:{expiresAt:/* @__PURE__ */ new Date}})},executeMainFn:!1})};async function h(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=(le(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=le(r);if(!a)return;let o=rY(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function g(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&le(t)||[]}async function _(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await g(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;c?await i.set(r,JSON.stringify(s),rY(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await TH(()=>_(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function y(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>wH(e,async()=>{let e=await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new E(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await c({...n,userId:e.id,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};JJ(e);let r;try{r=pH()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new E(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await YJ(r,{user:i,source:e})}return await c(i,`user`,void 0)},createAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(s)return(await(await SH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]})).map(e=>nG(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=le(e)||[],a=Date.now(),o=/* @__PURE__ */ new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(nG(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await SH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await SH(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await SH(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await g(e);(!i||r.session?.storeSessionInDatabase)&&await f([{field:`userId`,value:e}],`session`,void 0),await f([{field:`userId`,value:e}],`account`,void 0),await d([{field:`id`,value:e}],`user`,void 0)!==null&&await v(e,t)},createSession:async(a,l,u,d,f)=>{let p=await(async()=>{let e=fH();return e?.headers||e?.request?.headers})(),m=r.session?.storeSessionInDatabase,h=f?.deferSecondaryStorageWrites===!0&&s,{id:g,..._}=u||{},v;if(i&&!m){let e=t.generateId({model:`session`});v=e===!1?pe():e}let y=cG(r),b={...v?{id:v}:{},ipAddress:p&&xJ(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:uG(l?86400:o,`sec`),userId:a,token:pe(32),createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...y,...d?_:{}},x=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=le(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==b.token));let s=[...r,{token:b.token,expiresAt:b.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=rY(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await SH(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=rY(b.expiresAt,o);return u>0&&await i.set(b.token,JSON.stringify({session:t,user:l}),u),t};return await c(b,`session`,i?{fn:async e=>h?(await TH(async()=>{await x(e)},{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}),e):x(e),executeMainFn:m}:void 0)},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=le(e);return n?{session:nG(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:eG(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await SH(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:nG(t.options,s),user:eG(t.options,o)}:null},findSessions:async(t,n)=>{let r=[...new Set(t)],a=/* @__PURE__ */ new Map,o=[];if(i)for(let e of r){let t=await i.get(e);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=/* @__PURE__ */ new Date)continue;let o={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};a.set(e,o)}catch{continue}else o.push(e)}let c=i?o:r;if(c.length>0&&(!i||s)){let t=await(await SH(e)).findMany({model:`session`,limit:c.length,where:[{field:`token`,value:c,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]],join:{user:!0}});for(let{user:e,...n}of t)e&&a.set(n.token,{session:n,user:e})}return r.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,n)=>await l(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=le(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=nG(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=rY(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&le(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),rY(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=le(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=le(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),rY(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e}]);return}}await d([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await f([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await d([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await g(e);if(i){if(!r.session?.storeSessionInDatabase){await v(e,n);return}if(t.options.session?.preserveSessionInDatabase){await m([{field:`userId`,value:e}])!==null&&await v(e,n);return}}await f([{field:`userId`,value:e}],`session`,void 0)!==null&&await v(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e,operator:`in`}]);return}}await f([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({providerId:t,accountId:n})=>{let r=await(await SH(e)).findMany({model:`account`,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}],limit:2,join:{user:!0}});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let i=r[0];if(!i)return null;let{user:a,...o}=i;return a?{kind:`owned`,user:a,account:o}:{kind:`orphaned`,account:o}},findUserByEmail:async(t,n)=>{let r=await(await SH(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await SH(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await TH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await TH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await u({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await SH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await SH(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`accountId`,value:t}]}),findAccountByKey:async({providerId:t,accountId:n})=>{let r=await(await SH(e)).findMany({model:`account`,limit:2,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}]});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return r[0]??null},findAccountByUserId:async t=>await(await SH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=QJ(e.identifier,r.verification?.storeIdentifier),n=await ZJ(e.identifier,t);return await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=rY(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=QJ(t,r.verification?.storeIdentifier),a=await ZJ(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=le(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=le(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await SH(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await f([{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await ZJ(e,QJ(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await d([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=QJ(t,r.verification?.storeIdentifier),a=await ZJ(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?le(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>y(`verification:${t}`,()=>wH(e,async()=>{let n=await SH(e),r=[{field:`identifier`,value:t}],i=(await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:1}))[0]??null;return i?p(`verification`,[{field:`id`,value:i.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:i.id}]});return e?(await n.deleteMany({model:`verification`,where:r}),e):null},i):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt</* @__PURE__ */ new Date?null:c},reserveVerificationValue:async t=>{let n=xe(new Uint8Array(await MU(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=QJ(t.identifier,r.verification?.storeIdentifier),o=await ZJ(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new D(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=rY(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await ZJ(e,QJ(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=le(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=rY(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await l(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:h}};function aY(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function oY(e,t,n=`.`,r){if(!aY(t))return oY(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:aY(a)&&aY(i[t])?oY(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function sY(e){return(...t)=>t.reduce((t,n)=>oY(t,n,``,e),{})}const cY=sY(),lY=/* @__PURE__ */ new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function uY(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function dY(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function fY(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function pY(e){return e.replace(/\.+$/,``)}function mY(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function hY(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function gY(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function _Y(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=hY(e);return gY(t,hY(`127.0.0.0`),8)?`loopback`:gY(t,hY(`10.0.0.0`),8)||gY(t,hY(`172.16.0.0`),12)||gY(t,hY(`192.168.0.0`),16)?`private`:gY(t,hY(`169.254.0.0`),16)?`linkLocal`:gY(t,hY(`100.64.0.0`),10)?`sharedAddressSpace`:gY(t,hY(`192.0.2.0`),24)||gY(t,hY(`198.51.100.0`),24)||gY(t,hY(`203.0.113.0`),24)?`documentation`:gY(t,hY(`198.18.0.0`),15)?`benchmarking`:gY(t,hY(`224.0.0.0`),4)?`multicast`:gY(t,hY(`0.0.0.0`),8)||gY(t,hY(`192.0.0.0`),24)||gY(t,hY(`192.88.99.0`),24)||gY(t,hY(`240.0.0.0`),4)?`reserved`:`public`}function vY(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function yY(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=vY(e,1);return t&&_Y(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=vY(e,6);return t&&_Y(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=vY(e,6,{xor:!0});return t&&_Y(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function bY(e){let t=pY(fY(uY(dY(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!sJ(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:lY.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(mY(t))return{kind:_Y(t),literal:`ipv4`,canonical:t};let n=pJ(t,{ipv6Subnet:128});return mY(n)?{kind:_Y(n),literal:`ipv4`,canonical:n}:{kind:yY(n),literal:`ipv6`,canonical:n}}function xY(e){return bY(e).kind===`loopback`}function SY(e){let t=bY(e).kind;return t===`loopback`||t===`localhost`}function CY(e){return bY(e).kind===`public`}async function wY(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=dG(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=cY(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=iY(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function TY(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function EY(e,t){let n=[];if(VH(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||SY(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=LH(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=C.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function DY(e){if(HH(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has(`host`)||t.has(`x-forwarded-host`))return t}function OY(e){return e.advanced?.trustedProxyHeaders??!1}async function kY(e,t,n){let r=e.options.baseURL,i=qH(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new D(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:RH(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?HH(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await EY(o,c),a.trustedProviders=await jY(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=nq(a.options),a.createAuthCookie=tq(a.options)),a}async function AY(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function jY(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function MY(e){return e}async function NY(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new D(`OAUTH_ACCOUNT_SUBJECT_INVALID`);return{providerId:e.id,accountId:o}}async function PY(e,t,n){try{return await NY(e,t,n)}catch{throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO)}}function FY(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function IY(e,t){return e&&(t.options.account?.encryptOAuthTokens&&FY(e)?zW({key:t.secretConfig,data:e}):e)}function LY(e,t){return t.options.account?.encryptOAuthTokens&&e?RW({key:t.secretConfig,data:e}):e}function RY(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function zY(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function BY(e,t,n,r=3600,i){return await pU({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function VY(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let n=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}const HY=X(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:A({email:Re().meta({description:`The email to send the verification email to`}),callbackURL:k().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await zJ(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await VY(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw E.from(`BAD_REQUEST`,Y.EMAIL_MISMATCH);if(n?.user.emailVerified)throw E.from(`BAD_REQUEST`,Y.EMAIL_ALREADY_VERIFIED);return await VY(e,n.user),e.json({status:!0})}),UY=X(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:A({token:k().meta({description:`The token to verify the email`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){if(e.query.callbackURL){let n=new URLSearchParams({error:t.code}),r=bq(e.query.callbackURL,n);throw e.redirect(r)}throw E.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await oI(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof cP?t(Y.TOKEN_EXPIRED):t(Y.INVALID_TOKEN)}let i=A({email:Re(),updateTo:k().optional(),requestType:k().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(Y.USER_NOT_FOUND);if(i.updateTo){let n=await zJ(e);if(n&&n.user.email!==i.email)return t(Y.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await BY(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},zY(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await aq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:eG(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await BY(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},zY(e.request))),await aq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:eG(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await zJ(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);await aq(e,{session:t,user:{...a.user,emailVerified:!0}})}else await aq(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function WY(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function GY(e){let t=e=>new Date((/* @__PURE__ */ new Date()).getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:WY(e.scope),idToken:e.id_token,raw:e}}function KY(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[.../* @__PURE__ */ new Set([...n,...r])].join(`,`)}function qY(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function JY(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return ye.encode(new Uint8Array(n),{padding:!1})}const YY=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],XY=new Set(YY);async function ZY({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let b=qY(t.clientId);if(!b)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,b),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await JY(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))XY.has(e)||y.searchParams.set(e,t);return y}const QY=Ie(k(),k()).refine(e=>!Object.keys(e).some(e=>XY.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${YY.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional(),$Y=/^Basic +(.*)$/i;function eX(e){return new URLSearchParams({v:e}).toString().slice(2)}function tX(e){let t=new URLSearchParams(`v=${e}`).get(`v`);if(t===null)throw Error(`form-url-encoded value could not be decoded`);return t}function nX(e,t){let n=`${eX(e)}:${eX(t)}`;return`Basic ${ue.encode(n)}`}function rX(e){let t=e.match($Y);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(ue.decode(n)),i=r.indexOf(`:`);if(i===-1)throw Error(`Basic credential is missing the client id/secret separator`);let a=r.slice(0,i),o=r.slice(i+1);if(!a||!o)throw Error(`Basic credential client id and secret must both be non-empty`);return{clientId:tX(a),clientSecret:tX(o)}}const iX=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`];async function aX({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`}}var oX=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}};const sX=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}};var cX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},lX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function uX(e){if(typeof e==`number`)return new cX({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new cX(e);case`exponential`:return new lX(e);default:throw Error(`Invalid retry strategy`)}}const dX=[`get`,`post`,`put`,`patch`,`delete`];function fX(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return dX.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}const pX=e=>e===`.`||e===`..`,mX=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function hX(e,t){let n=t.get(e);if(n===void 0)return mX(e);if(pX(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function gX(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=fX(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=/* @__PURE__ */ new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>hX(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}const _X=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},vX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function yX(e){let t=e.headers.get(`content-type`),n=/* @__PURE__ */ new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return vX.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function bX(e){try{return JSON.parse(e),!0}catch{return!1}}function xX(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function SX(e){try{return JSON.parse(e)}catch{return e}}function CX(e){return typeof e==`function`}function wX(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&CX(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&CX(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function TX(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function EX(e){let t=new Headers(TX(e?.headers,await _X(e)));if(!t.has(`content-type`)){let n=DX(e?.body);n&&t.set(`content-type`,n)}return t}function DX(e){return xX(e)?`application/json`:null}function OX(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function kX(e,t){let{body:n}=e;return n?!xX(n)||typeof n==`string`?n:OX(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function AX(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=fX(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function jX(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var MX=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function NX(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new MX(n.issues);return n.value}function PX(e){"@babel/helpers - typeof";return PX=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},PX(e)}function FX(e,t){if(PX(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(PX(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function IX(e){var t=FX(e,`string`);return PX(t)==`symbol`?t:t+``}function LX(e,t,n){return(t=IX(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RX(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function zX(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?RX(Object(n),!0).forEach(function(t){LX(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RX(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const BX=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await sX(e,t),o=wX(a),s=new AbortController,c=a.signal??s.signal,l=gX(i,a),u=await EX(a),d=kX(a,u),f=AX(i,a),p=zX(zX({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=jX(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(zX(zX({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=yX(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??SX)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await NX(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(zX(zX({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??SX,b=await h.text(),x=bX(b),S=x?await y(b):null,ee={response:h,responseText:b,request:p,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var C;await e(zX(zX({},ee),{},{response:t!=null&&(C=t.hookOptions)!=null&&C.cloneResponse?h.clone():h}))}if(t?.retry){let n=uX(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await BX(e,zX(zX({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new oX(h.status,h.statusText,x?S:b);return{data:null,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})}},VX=/* @__PURE__ */ new Set([301,302,303,307,308]);function HX(e){return e.type===`opaqueredirect`||VX.has(e.status)}function UX(e){return new D(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}const WX={redirect:`manual`};async function GX(e,t){let n=!1,r=t?.onError,i=await BX(e,{...t,...WX,async onError(e){HX(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?UX(e):t});if(n)throw UX(e);return i}function KX(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function qX(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function JX(e,t){t&&e.set(`client_id`,t)}function YX(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function XX(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function ZX({body:e,options:t,clientId:n,requireClientSecret:r}){r&&YX(`client_secret_post`,t),t.clientSecret&&(XX(`client_secret_post`,n),JX(e,n),e.set(`client_secret`,t.clientSecret))}function QX({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);YX(`client_secret_basic`,t),XX(`client_secret_basic`,n),e.authorization=nX(n,t.clientSecret)}function $X(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function eZ({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){$X(e);let s=qY(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);qX(`private_key_jwt`,n,e),JX(e,s);return}let c=a??KX(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),$X(e);else if(c.method===`private_key_jwt`){if(qX(c.method,n,e),XX(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await aX({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});JX(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(qX(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);XX(c.method,s),JX(e,s)}else c.method===`client_secret_basic`?QX({headers:t,options:n,clientId:s,body:e}):ZX({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}const tZ=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],nZ=/* @__PURE__ */ new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function rZ(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function iZ(e,t){return Object.assign(Error(t),{code:e})}function aZ(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function oZ(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function sZ(e){return oZ(e)?.token??e}function cZ(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function lZ(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return xP(new Uint8Array(t))}async function uZ(e){return pI(e,`sha256`)}function dZ(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function fZ(e){return dZ(e.cnf)}function pZ(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function mZ(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function hZ(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw iZ(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw iZ(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function gZ(e){if(!e||typeof e!=`object`||Array.isArray(e))throw iZ(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw iZ(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of nZ)if(t in e)throw iZ(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function _Z(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return xP(new Uint8Array(n))}async function vZ(e,t){if(e&&!await e.reserve(t))throw iZ(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function yZ({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=300,signingAlgorithms:c=tZ,replayStore:l}){if(!e||e.split(`.`).length!==3)throw iZ(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=bI(e)}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw iZ(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);hZ(u.alg,c),gZ(u.jwk);let d;try{d=(await oI(e,await yI(u.jwk,u.alg),{typ:`dpop+jwt`})).payload}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=pZ(d,`htm`),p=pZ(d,`htu`),m=pZ(d,`jti`),h=mZ(d,`iat`);if(!f||!p||!m||h===void 0)throw iZ(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>512)throw iZ(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw iZ(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=cZ(n),_=cZ(p)}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw iZ(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw iZ(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=pZ(d,`ath`);if(a&&!v)throw iZ(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await lZ(r))throw iZ(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await uZ(u.jwk);if(i!==void 0&&y!==i)throw iZ(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await _Z({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=/* @__PURE__ */ new Date((h+s)*1e3);return await vZ(l,{key:b,expiresAt:x,now:/* @__PURE__ */ new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function bZ(e,t){return Object.assign(Error(t),{code:e})}function xZ(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function SZ({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=fZ(e);if(c){if(t.scheme!==`DPoP`)throw bZ(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw bZ(`invalid_dpop_proof`,`DPoP proof header is required`);try{await yZ({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw aZ(e)?bZ(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw bZ(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}const CZ=/* @__PURE__ */ new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function wZ({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=EZ({refreshToken:e,options:t,extraParams:a,resource:o});return await eZ({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function TZ(e,t){if(t)for(let[n,r]of Object.entries(t))CZ.has(n)||e.set(n,r)}function EZ({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&TZ(i,n),{body:i,headers:a}}async function DZ({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await wZ({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await GX(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:WY(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.refresh_token_expires_in*1e3)),d}async function OZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=kZ({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await eZ({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function kZ({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function AZ({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await OZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await GX(i,{method:`POST`,body:d,headers:f});if(m)throw m;return GY(p)}yP.code,gP.code,vP.code;const jZ=/* @__PURE__ */ new Map,MZ=/* @__PURE__ */ new WeakMap,NZ=5e3;function PZ(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function FZ(e,t){return e.pending!==void 0&&t-e.pending.startedAt<NZ}async function IZ(e,t){let n=Date.now();if(!e.pending||!FZ(e,n)){let r={startedAt:n,promise:RZ(t).then(t=>(n>=e.fetchedAt&&(e.jwks=t,e.fetchedAt=n),t)).finally(()=>{e.pending===r&&(e.pending=void 0)})};e.pending=r}let{promise:r,startedAt:i}=e.pending,a;try{return await Promise.race([r,new Promise((e,t)=>{a=setTimeout(()=>t(new yP),i+NZ-n)})])}finally{clearTimeout(a)}}async function LZ(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!FZ(e,r)){if(r-e.refetchedAt<3e4)return;e.refetchedAt=r}return IZ(e,n)}async function RZ(e){try{let t=typeof e==`string`?await GX(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();if(!t)throw Error(`No jwks found`);return t}catch(e){if(e instanceof TypeError){try{f.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function zZ(e,t){return(await BZ(e,t)).jwks}async function BZ(e,t){let n;try{n=bI(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?PZ(jZ,t.jwksFetch):t.jwksCacheKey?PZ(MZ,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<3e5?i.jwks:void 0;if(!a)return{jwks:await IZ(i,t.jwksFetch),kid:r};let o=e=>LZ(i,e,t.jwksFetch);return!r||a.keys.some(e=>e.kid===r)?{jwks:a,kid:r,refresh:o}:{jwks:await o(a)??a,kid:r}}async function VZ(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function HZ(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await VZ(t):!1}function UZ(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function WZ(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;if(!a)return!1;if(`verify`in a)return await a.verify(t,n,r);if(t.split(`.`).length!==3)return a.allowOpaqueToken===!0;let{alg:o}=bI(t),{payload:s}=await oI(t,a.jwks,{issuer:a.issuer,audience:a.audience,algorithms:a.algorithms??(o?[o]:void 0),maxTokenAge:a.maxTokenAge,clockTolerance:30});return!(n&&!await HZ(s.nonce,n,a.nonceComparison)||a.verifyClaims&&!a.verifyClaims(s))}catch{return!1}}function GZ(e,t){return{linked:!1,error:{code:e,message:t}}}async function mfe(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await YJ(e,{user:{...n,id:t.userId,email:n.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:r.providerId,profile:i}}})}catch(e){if(!Fq(e)||!e.body?.code)throw e;return GZ(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(r.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),GZ(Sq.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return GZ(Sq.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return GZ(Sq.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=KY(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(o.id,i)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...r,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return GZ(Sq.UNABLE_TO_LINK_ACCOUNT);return await JZ(e,t.userId,n),{linked:!0}}async function KZ(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
|
|
60
|
-
Error: `,t),Cq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)});if(u?.kind===`orphaned`)return e.context.logger.error(`OAuth account references a missing user. Repair the account before retrying authentication.`),{error:`unable to link account`,data:null,isRegister:!1};let d=await(async()=>{if(u?.kind===`owned`){if(t.selectedUser&&u.user.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`account_ownership_conflict`,message:`Account is already linked to another user`});return{user:u.user,linkedAccount:u.account,accounts:[u.account]}}if(t.selectedUser){let n=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!n)throw new E(`NOT_FOUND`,{code:`user_not_found`,message:`User not found`});return{user:n,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if(Fq(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
|
|
61
|
-
Error: `,t),Cq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,p=!f;if(d){let i=d.linkedAccount??d.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await YJ(e,{user:{...o,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`sign-in`}});let u=e.context.options.account?.updateAccountOnSignIn===!1?{}:Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>t!==void 0));if(e.context.options.account?.storeAccountCookie){let n={...i,...u};t.deferNonDatabaseWrites?l=n:await JK(e,n)}if(Object.keys(u).length>0){let n=await e.context.internalAdapter.updateAccount(i.id,u);if(!n)return{error:`unable to update account`,data:null};if(c&&(n.accountId!==r.accountId||n.providerId!==r.providerId||n.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});t.deferNonDatabaseWrites&&l&&(l=n)}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!d.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return S()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:`account not linked`,data:null};try{let{id:i,...a}=n;await YJ(e,{user:{...a,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`link-account`}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:d.user.id,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:`unable to link account`,data:null};if(c&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=o:await JK(e,o))}catch(t){if(Fq(t))throw t;return e.context.logger.error(`Unable to link account`,t),{error:`unable to link account`,data:null}}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0}),t.selectedUser||(f=await JZ(e,d.user.id,n)??f)}if(t.selectedUser?t.selectedUser.profile===`update`:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...c}=n,l=oG(e.context.options,c,`update`),u=await e.context.internalAdapter.updateUser(d.user.id,{name:o,image:s,...l,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===d.user.email&&d.user.emailVerified||n.emailVerified});if(u??e.context.logger.warn(`Could not update user info during OAuth sign in; preserving existing user for session.`),t.selectedUser&&u&&u.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`user_hook_selection_conflict`,message:`User hook changed the selected user`});f=u??f}}else{if(a)return{error:`signup disabled`,data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:u,image:d,...p}=n,m=oG(e.context.options,p,`create`),h={accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:g,createdAccount:_}=await wH(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:u,image:d,...m,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...h,userId:t.id})}});if(c&&(_.accountId!==r.accountId||_.providerId!==r.providerId||_.userId!==g.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});f=g,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=_:await JK(e,_))}catch(t){if(Fq(t))throw t;return e.context.logger.error(`Unable to create OAuth user`,t),{error:`unable to create user`,data:null,isRegister:!1}}}if(!f)return{error:`unable to create user`,data:null,isRegister:!1};let m=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(p&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??m)&&await qZ(e,f,i,t.deferNonDatabaseWrites),m&&!f.emailVerified)return!p&&e.context.options.emailVerification?.sendOnSignIn&&await qZ(e,f,i,t.deferNonDatabaseWrites),{error:Sq.EMAIL_NOT_VERIFIED,data:null,isRegister:p};let h=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!h)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&h.userId!==(t.selectedUser?.userId??f.id))throw new E(`CONFLICT`,{code:`session_hook_user_conflict`,message:`Session hook changed the selected user`});return{data:{session:h,user:f},error:null,isRegister:p,accountCookie:l}}async function qZ(e,t,n,r){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let a=async()=>{try{let r=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(n||`/`)}`;await e.context.runInBackgroundOrAwait(i({user:t,url:a,token:r},e.request))}catch(t){e.context.logger.error(`Failed to send OAuth verification email`,t)}};r?await TH(a):await a()}async function JZ(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=oG(e.context.options,s,`update`);return await e.context.internalAdapter.updateUser(t,{name:a,image:o,...c})}catch(t){e.context.logger.warn(`Could not update user info on account link`,t);return}}const hfe=e=>{let t=`https://appleid.apple.com/auth/token`;return{id:`apple`,name:`Apple`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i,codeVerifier:a}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client ID and client secret are required for Apple. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`name`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`apple`,options:e,authorizationEndpoint:`https://appleid.apple.com/auth/authorize`,scopes:o,state:t,redirectURI:r,codeVerifier:a,responseMode:`form_post`,responseType:`code id_token`,additionalParams:i})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>gfe(e.kid),issuer:`https://appleid.apple.com`,audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:`1h`,nonceComparison:`exact-or-sha256`},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=xI(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}},gfe=async e=>{let{data:t}=await BX(`https://appleid.apple.com/auth/keys`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await yI(n,n.alg)},_fe=e=>{let t=`https://auth.atlassian.com/oauth/token`;return{id:`atlassian`,name:`Atlassian`,accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Secret are required for Atlassian`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Atlassian`);let o=e.disableDefaultScope?[]:[`read:jira-user`,`offline_access`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`atlassian`,options:e,authorizationEndpoint:`https://auth.atlassian.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:{...a??{},audience:`api.atlassian.com`},prompt:e.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:n}=await BX(`https://api.atlassian.com/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Atlassian:`,e),null}},options:e}},YZ=`https://dash.cloudflare.com/oauth2/token`,XZ=e=>{let t=e.clientSecret?`client_secret_basic`:`none`;return{method:e.tokenEndpointAuthMethod??t}},vfe=e=>({id:`cloudflare`,name:`Cloudflare`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i}){let a=e.disableDefaultScope?[]:[`user-details.read`];return e.scope?.length&&a.push(...e.scope),n?.length&&a.push(...n),ZY({id:`cloudflare`,options:e,authorizationEndpoint:`https://dash.cloudflare.com/oauth2/auth`,scopes:a.length?[...new Set(a)]:void 0,state:t,codeVerifier:r,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:YZ,tokenEndpointAuth:XZ(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:YZ,tokenEndpointAuth:XZ(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.cloudflare.com/client/v4/user`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n?.success||!n.result)return f.error(`Failed to fetch user info from Cloudflare:`,r??n?.errors),null;let i=n.result,a=[i.first_name,i.last_name].filter(Boolean).join(` `)||i.email,o=await e.mapProfileToUser?.(i);return{user:{name:a,email:i.email,emailVerified:!1,...o},data:i}},options:e}),yfe=e=>{if(!e.domain||!e.region||!e.userPoolId)throw f.error(`Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options.`),new D(`DOMAIN_AND_REGION_REQUIRED`);let t=e.domain.replace(/^https?:\/\//,``),n=`https://${t}/oauth2/authorize`,r=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:`cognito`,name:`Cognito`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!qY(e.clientId))throw f.error(`ClientId is required for Amazon Cognito. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(e.requireClientSecret&&!e.clientSecret)throw f.error(`Client Secret is required when requireClientSecret is true. Make sure to provide it in the options.`),new D(`CLIENT_SECRET_REQUIRED`);let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];e.scope&&s.push(...e.scope),r&&s.push(...r);let c=await ZY({id:`cognito`,options:{...e},authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...o??{}}}),l=c.searchParams.get(`scope`);if(l){c.searchParams.delete(`scope`);let e=encodeURIComponent(l),t=c.toString(),n=t.includes(`?`)?`&`:`?`;return new URL(`${t}${n}scope=${e}`)}return c},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>bfe(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=xI(t.idToken);if(!n)return null;let r=n.name||n.given_name||n.username||``,i={...n,name:r},a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:i}}catch(e){f.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n){let t=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.given_name||n.username||``,email:n.email,image:n.picture,emailVerified:n.email_verified,...t},data:n}}}catch(e){f.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},bfe=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await BX(r);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await yI(n,n.alg)}catch(e){throw f.error(`Failed to fetch Cognito public key:`,e),e}},xfe=e=>{let t=`https://discord.com/api/oauth2/token`;return{id:`discord`,name:`Discord`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identify`,`email`];n&&a.push(...n),e.scope&&a.push(...e.scope);let o=a.includes(`bot`);return ZY({id:`discord`,options:e,authorizationEndpoint:`https://discord.com/api/oauth2/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`none`,additionalParams:{...o&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...i??{}}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://discord.com/api/users/@me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator===`0`?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let e=n.avatar.startsWith(`a_`)?`gif`:`png`;n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${e}`}let i=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||``,email:n.email,emailVerified:n.verified,image:n.image_url,...i},data:n}},options:e}},Sfe=e=>{let t=`https://api.dropboxapi.com/oauth2/token`;return{id:`dropbox`,name:`Dropbox`,accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`account_info.read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`dropbox`,options:e,authorizationEndpoint:`https://www.dropbox.com/oauth2/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>await AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.dropboxapi.com/2/users/get_current_account`,{method:`POST`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}};async function Cfe(e,t){let n=qY(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await BX(`https://graph.facebook.com/debug_token`,{query:{input_token:e,access_token:`${n}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return o!==!0||!s||!r.includes(s)||!c?null:c}const wfe=e=>({id:`facebook`,name:`Facebook`,accountSubject:({profile:e})=>`sub`in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client ID and client secret are required for Facebook. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`public_profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`facebook`,options:e,authorizationEndpoint:`https://www.facebook.com/v24.0/dialog/oauth`,scopes:o,state:t,redirectURI:r,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...a??{}}})},validateAuthorizationCode:async({code:t,redirectURI:n})=>AZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:jde(new URL(`https://limited.facebook.com/.well-known/oauth/openid/jwks/`)),issuer:`https://www.facebook.com`,audience:e.clientId,algorithms:[`RS256`],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&t.idToken.split(`.`).length===3){let n=xI(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 Cfe(n,e);if(!r)return null;let{data:i,error:a}=await BX(`https://graph.facebook.com/me?fields=`+[`id`,`name`,`email`,`picture`,...e?.fields||[]].join(`,`),{auth:{type:`Bearer`,token:n}});if(a||i.id!==r)return null;let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),Tfe=e=>{let t=`https://api.figma.com/v1/oauth/token`;return{id:`figma`,name:`Figma`,accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret are required for Figma. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Figma`);let o=e.disableDefaultScope?[]:[`current_user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`figma`,options:e,authorizationEndpoint:`https://www.figma.com/oauth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return f.error(`Failed to fetch user from Figma`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},Efe=e=>{let t=`https://github.com/login/oauth/access_token`;return{id:`github`,name:`GitHub`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`read:user`,`user:email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),ZY({id:`github`,options:e,authorizationEndpoint:`https://github.com/login/oauth/authorize`,scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:r,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>{let{body:a,headers:o}=await OZ({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await BX(t,{method:`POST`,body:a,headers:o});return c?(f.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(f.error(`GitHub OAuth token exchange failed:`,s),null):GY(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await BX(`https://api.github.com/user/emails`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});!n.email&&i&&(n.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===n.email)?.verified??!1,o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||``,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},ZZ=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),Dfe=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:ZZ(`${t}/oauth/authorize`),tokenEndpoint:ZZ(`${t}/oauth/token`),userinfoEndpoint:ZZ(`${t}/api/v4/user`)}},Ofe=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=Dfe(e.issuer),i=`gitlab`;return{id:i,name:`Gitlab`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:n,scopes:r,codeVerifier:a,loginHint:o,redirectURI:s,additionalParams:c})=>{let l=e.disableDefaultScope?[]:[`read_user`];return e.scope&&l.push(...e.scope),r&&l.push(...r),await ZY({id:i,options:e,authorizationEndpoint:t,scopes:l,state:n,redirectURI:s,codeVerifier:a,loginHint:o,additionalParams:c})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>AZ({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:i}=await BX(r,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||n.state!==`active`||n.locked)return null;let a=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.username??``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...a},data:n}},options:e}},QZ=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,kfe=e=>({id:`google`,name:`Google`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,display:o,additionalParams:s}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for Google. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Google`);let c=e.disableDefaultScope?[]:[`email`,`profile`,`openid`];return e.scope&&c.push(...e.scope),n&&c.push(...n),await ZY({id:`google`,options:e,authorizationEndpoint:`https://accounts.google.com/o/oauth2/v2/auth`,scopes:c,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:`true`},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>Afe(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,maxTokenAge:`1h`,verifyClaims:e.hd?t=>QZ(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=xI(t.idToken);if(!QZ(e.hd,n.hd))return f.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??`<missing>`}" does not satisfy the configured "hd" option "${e.hd}".`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...r},data:n}},options:e}),Afe=async e=>{let[t]=await jfe(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},jfe=async e=>{let{data:t}=await BX(`https://www.googleapis.com/oauth2/v3/certs`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=e?t.keys.filter(t=>t.kid===e):t.keys;if(!n.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(n.map(e=>yI(e,`RS256`)))},Mfe=e=>{let t=`https://huggingface.co/oauth/token`;return{id:`huggingface`,name:`Hugging Face`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`huggingface`,options:e,authorizationEndpoint:`https://huggingface.co/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://huggingface.co/oauth/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},Nfe=e=>{let t=`https://kauth.kakao.com/oauth/token`;return{id:`kakao`,name:`Kakao`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`account_email`,`profile_image`,`profile_nickname`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`kakao`,options:e,authorizationEndpoint:`https://kauth.kakao.com/oauth/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://kapi.kakao.com/v2/user/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n),a=n.kakao_account||{},o=a.profile||{};return{user:{name:o.nickname||a.name||``,email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:n}},options:e}},Pfe=e=>({id:`kick`,name:`Kick`,accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,codeVerifier:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`kick`,redirectURI:r,options:e,authorizationEndpoint:`https://id.kick.com/oauth/authorize`,scopes:o,codeVerifier:i,state:t,additionalParams:a})},async validateAuthorizationCode({code:t,redirectURI:n,codeVerifier:r}){return AZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:`https://id.kick.com/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.kick.com/public/v1/users`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=n.data[0],a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),Ffe=e=>{let t=`https://api.line.me/oauth2/v2.1/token`;return{id:`line`,name:`LINE`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),await ZY({id:`line`,options:e,authorizationEndpoint:`https://access.line.me/oauth2/v2.1/authorize`,scopes:s,state:t,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,n)=>{let r=new URLSearchParams;r.set(`id_token`,t),r.set(`client_id`,e.clientId),n&&r.set(`nonce`,n);let{data:i,error:a}=await BX(`https://api.line.me/oauth2/v2.1/verify`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:r});return!(a||!i||i.aud!==e.clientId||i.nonce&&i.nonce!==n)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=null;if(t.idToken)try{n=xI(t.idToken)}catch{}if(!n){let{data:e}=await BX(`https://api.line.me/oauth2/v2.1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});n=e||null}if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}},options:e}},Ife=e=>{let t=`https://api.linear.app/oauth/token`;return{id:`linear`,name:`Linear`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`linear`,options:e,authorizationEndpoint:`https://linear.app/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linear.app/graphql`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
62
|
-
query {
|
|
63
|
-
viewer {
|
|
64
|
-
id
|
|
65
|
-
name
|
|
66
|
-
email
|
|
67
|
-
avatarUrl
|
|
68
|
-
active
|
|
69
|
-
createdAt
|
|
70
|
-
updatedAt
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
`})});if(r||!n?.data?.viewer)return null;let i=n.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{name:n.data.viewer.name,email:n.data.viewer.email,image:n.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},Lfe=e=>{let t=`https://www.linkedin.com/oauth/v2/accessToken`;return{id:`linkedin`,name:`Linkedin`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`profile`,`email`,`openid`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`linkedin`,options:e,authorizationEndpoint:`https://www.linkedin.com/oauth/v2/authorization`,scopes:o,state:t,loginHint:i,redirectURI:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>await AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linkedin.com/v2/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,emailVerified:n.email_verified??!1,image:n.picture,...i},data:n}},options:e}},$Z=`9188040d-6c67-4c5b-b112-36a304b66dad`,Rfe=e=>{let t=e.tenantId||`common`,n=e.authority||`https://login.microsoftonline.com`;for(;n.endsWith(`/`);)n=n.slice(0,-1);let r=`${n}/${t}/oauth2/v2.0/authorize`,i=`${n}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new D(`Microsoft Entra ID clientAssertion cannot be combined with clientSecret`);let a=e.clientAssertion?{method:`private_key_jwt`,getClientAssertion:e.clientAssertion}:void 0;return{id:`microsoft`,name:`Microsoft EntraID`,accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!qY(e.clientId))throw f.error(`Client Id is required for Microsoft Entra ID. Make sure to provide it in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`microsoft`,options:e,authorizationEndpoint:r,state:t.state,codeVerifier:t.codeVerifier,scopes:n,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode({code:t,codeVerifier:n,redirectURI:r}){return AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:i,tokenEndpointAuth:a})},idToken:{jwks:e=>zfe(e.kid,t,n),algorithms:[`RS256`],audience:e.clientId,maxTokenAge:`1h`,issuer:t!==`common`&&t!==`organizations`&&t!==`consumers`?`${n}/${t}/v2.0`:void 0,verifyClaims:e=>{let r=e.tid;return!(typeof r!=`string`||e.iss!==`${n}/${r}/v2.0`||t===`organizations`&&r===$Z||t===`consumers`&&r!==$Z)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=xI(t.idToken);if(typeof n.oid!=`string`||n.oid.trim().length===0)return f.error(`Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier.`),null;let r=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await BX(`https://graph.microsoft.com/v1.0/me/photos/${r}x${r}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer();n.picture=`data:image/jpeg;base64, ${ue.encode(t)}`}catch(e){f.error(e&&typeof e==`object`&&`name`in e?e.name:``,e)}}});let i=await e.mapProfileToUser?.(n),a=n.email_verified===void 0?!!(n.email&&(n.verified_primary_email?.includes(n.email)||n.verified_secondary_email?.includes(n.email))):n.email_verified;return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:a,...i},data:n}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:n.join(` `)},tokenEndpoint:i,tokenEndpointAuth:a})},options:e}},zfe=async(e,t,n)=>{let{data:r}=await BX(`${n}/${t}/discovery/v2.0/keys`);if(!r?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let i=r.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await yI(i,i.alg??`RS256`)},Bfe=e=>{let t=`https://nid.naver.com/oauth2.0/token`;return{id:`naver`,name:`Naver`,accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`profile`,`email`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`naver`,options:e,authorizationEndpoint:`https://nid.naver.com/oauth2.0/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://openapi.naver.com/v1/nid/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n||n.resultcode!==`00`)return null;let i=await e.mapProfileToUser?.(n),a=n.response||{};return{user:{name:a.name||a.nickname||``,email:a.email,image:a.profile_image,emailVerified:!1,...i},data:n}},options:e}},Vfe=e=>{let t=`https://api.notion.com/v1/oauth/token`;return{id:`notion`,name:`Notion`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=(e.disableDefaultScope,[]);return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`notion`,options:e,authorizationEndpoint:`https://api.notion.com/v1/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:{...a??{},owner:`user`}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.notion.com/v1/users/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":`2022-06-28`}});if(r||!n)return null;let i=n.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{name:i.name||``,email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},Hfe=e=>{let t=e.issuer||`https://idp.paybin.io`,n=`${t}/oauth2/authorize`,r=`${t}/oauth2/token`;return{id:`paybin`,name:`Paybin`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for Paybin. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Paybin`);let c=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&c.push(...e.scope),r&&c.push(...r),await ZY({id:`paybin`,options:e,authorizationEndpoint:n,scopes:c,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=xI(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}},Ufe=e=>{let t=(e.environment||`sandbox`)===`sandbox`,n=t?`https://www.sandbox.paypal.com/signin/authorize`:`https://www.paypal.com/signin/authorize`,r=t?`https://api-m.sandbox.paypal.com/v1/oauth2/token`:`https://api-m.paypal.com/v1/oauth2/token`,i=t?`https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo`:`https://api-m.paypal.com/v1/identity/oauth2/userinfo`,a={clientId:e.clientId,clientSecret:e.clientSecret},o={method:`client_secret_basic`};return{id:`paypal`,name:`PayPal`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for PayPal. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);return await ZY({id:`paypal`,options:e,authorizationEndpoint:n,scopes:[],state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>{try{return await AZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw f.error(`PayPal token exchange failed:`,e),new D(`FAILED_TO_GET_ACCESS_TOKEN`)}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await DZ({refreshToken:e,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw f.error(`PayPal token refresh failed:`,e),new D(`FAILED_TO_REFRESH_ACCESS_TOKEN`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return f.error(`Access token is required to fetch PayPal user info`),null;try{let n=await BX(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:`application/json`}});if(!n.data)return f.error(`Failed to fetch user info from PayPal`),null;let r=n.data;if(t.idToken){let e;try{e=xI(t.idToken).sub}catch(e){return f.error(`Failed to decode PayPal ID token:`,e),null}let n=r.sub??r.user_id;if(!e||n!==e)return f.error(`PayPal user info subject does not match ID token subject`),null}let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:r}}catch(e){return f.error(`Failed to fetch user info from PayPal:`,e),null}},options:e}},Wfe=e=>{let t=`https://api.polar.sh/v1/oauth2/token`;return{id:`polar`,name:`Polar`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`polar`,options:e,authorizationEndpoint:`https://polar.sh/oauth2/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.polar.sh/v1/oauth2/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.public_name||n.username||``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},eQ=`https://backboard.railway.com/oauth/token`,Gfe=e=>({id:`railway`,name:`Railway`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`railway`,options:e,authorizationEndpoint:`https://backboard.railway.com/oauth/auth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:eQ,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:eQ,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://backboard.railway.com/oauth/me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:e});function tQ({identifier:e,namespace:t}){let n=Re().safeParse(`${e}@${t}.placeholder.invalid`);if(!n.success)throw TypeError(`Invalid placeholder email`);return n.data}const nQ={apple:hfe,atlassian:_fe,cloudflare:vfe,cognito:yfe,discord:xfe,facebook:wfe,figma:Tfe,github:Efe,microsoft:Rfe,google:kfe,huggingface:Mfe,slack:e=>{let t=`https://slack.com/api/openid.connect.token`;return{id:`slack`,name:`Slack`,accountSubject:({profile:e})=>e[`https://slack.com/user_id`],createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return n&&a.push(...n),e.scope&&a.push(...e.scope),ZY({id:`slack`,options:e,authorizationEndpoint:`https://slack.com/openid/connect/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://slack.com/api/openid.connect.userInfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,emailVerified:n.email_verified,image:n.picture||n[`https://slack.com/user_image_512`],...i},data:n}},options:e}},spotify:e=>{let t=`https://accounts.spotify.com/api/token`;return{id:`spotify`,name:`Spotify`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user-read-email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`spotify`,options:e,authorizationEndpoint:`https://accounts.spotify.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.spotify.com/v1/me`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.display_name,email:n.email,image:n.images[0]?.url,emailVerified:!1,...i},data:n}},options:e}},twitch:e=>{let t=`https://id.twitch.tv/oauth2/token`;return{id:`twitch`,name:`Twitch`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user:read:email`,`openid`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`twitch`,redirectURI:r,options:e,authorizationEndpoint:`https://id.twitch.tv/oauth2/authorize`,scopes:a,state:t,claims:e.claims||[`email`,`email_verified`,`preferred_username`,`picture`],additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.idToken;if(!n)return f.error(`No idToken found in token`),null;let r=xI(n),i=await e.mapProfileToUser?.(r);return{user:{name:r.preferred_username,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}},twitter:e=>{let t=`https://api.x.com/2/oauth2/token`;return{id:`twitter`,name:`Twitter`,accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let n=e.disableDefaultScope?[]:[`users.read`,`tweet.read`,`offline.access`,`users.email`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`twitter`,options:e,authorizationEndpoint:`https://x.com/i/oauth2/authorize`,scopes:n,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,authentication:`basic`,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:`basic`,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.x.com/2/users/me?user.fields=profile_image_url`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i,error:a}=await BX(`https://api.x.com/2/users/me?user.fields=confirmed_email`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(n.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(n);return{user:{name:n.data.name,email:n.data.email||tQ({identifier:n.data.id,namespace:`twitter`}),image:n.data.profile_image_url,emailVerified:o,...s},data:n}},options:e}},dropbox:Sfe,kick:Pfe,linear:Ife,linkedin:Lfe,gitlab:Ofe,tiktok:e=>{let t=`https://open.tiktokapis.com/v2/oauth/token/`,n={method:`custom`,customizeRequest({body:t}){t.set(`client_key`,e.clientKey),t.set(`client_secret`,e.clientSecret)}};return{id:`tiktok`,name:`TikTok`,accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user.info.profile`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://www.tiktok.com/v2/auth/authorize`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`client_key`,e.clientKey),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`client_key`&&o.searchParams.set(e,t);return o},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>AZ({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>DZ({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://open.tiktokapis.com/v2/user/info/?fields=${[`open_id`,`avatar_large_url`,`display_name`,`username`].join(`,`)}`,{headers:{authorization:`Bearer ${t.accessToken}`}});return r?null:{user:{email:n.data.user.email||tQ({identifier:n.data.user.open_id,namespace:`tiktok`}),name:n.data.user.display_name||n.data.user.username||``,image:n.data.user.avatar_large_url,emailVerified:!1},data:n}},options:e}},reddit:e=>{let t=`https://www.reddit.com/api/v1/access_token`,n={clientId:e.clientId,clientSecret:e.clientSecret},r={method:`client_secret_basic`};return{id:`reddit`,name:`Reddit`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identity`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`reddit`,options:e,authorizationEndpoint:`https://www.reddit.com/api/v1/authorize`,scopes:a,state:t,redirectURI:r,duration:e.duration,additionalParams:i})},validateAuthorizationCode:async({code:i,redirectURI:a})=>AZ({code:i,redirectURI:e.redirectURI||a,options:n,tokenEndpoint:t,tokenEndpointAuth:r,headers:{accept:`text/plain`,"user-agent":`better-auth`}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>DZ({refreshToken:e,options:n,tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://oauth.reddit.com/api/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});if(r)return null;let i=await e.mapProfileToUser?.(n),a=i?.email||tQ({identifier:n.id,namespace:`reddit`});return{user:{name:n.name,image:n.icon_img?.split(`?`)[0],...i,email:a,emailVerified:i?.emailVerified??!1},data:n}},options:e}},roblox:e=>{let t=`https://apis.roblox.com/oauth/v1/token`;return{id:`roblox`,name:`Roblox`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`roblox`,options:e,authorizationEndpoint:`https://apis.roblox.com/oauth/v1/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`select_account consent`,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t,authentication:`post`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://apis.roblox.com/oauth/v1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.nickname||n.preferred_username||``,image:n.picture,email:tQ({identifier:n.sub,namespace:`roblox`}),emailVerified:!1,...i},data:{...n}}},options:e}},salesforce:e=>{let t=(e.environment??`production`)===`sandbox`,n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?`https://test.salesforce.com/services/oauth2/authorize`:`https://login.salesforce.com/services/oauth2/authorize`,r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?`https://test.salesforce.com/services/oauth2/token`:`https://login.salesforce.com/services/oauth2/token`,i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?`https://test.salesforce.com/services/oauth2/userinfo`:`https://login.salesforce.com/services/oauth2/userinfo`;return{id:`salesforce`,name:`Salesforce`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Salesforce`);let s=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&s.push(...e.scope),r&&s.push(...r),ZY({id:`salesforce`,options:e,authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:e.redirectURI||a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return f.error(`Failed to fetch user info from Salesforce`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.photos?.picture||n.photos?.thumbnail,emailVerified:n.email_verified??!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Salesforce:`,e),null}},options:e}},vk:e=>{let t=`https://id.vk.com/oauth2/auth`;return{id:`vk`,name:`VK`,accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`email`,`phone`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`vk`,options:e,authorizationEndpoint:`https://id.vk.com/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i,deviceId:a})=>AZ({code:n,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let{data:n,error:r}=await BX(`https://id.vk.com/oauth2/user_info`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString()});if(r)return null;let i=await e.mapProfileToUser?.(n);return!n.user.email&&!i?.email?null:{user:{first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...i},data:n}},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:`zoom`,name:`Zoom`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:n,codeVerifier:r,additionalParams:i})=>ZY({id:`zoom`,options:t,authorizationEndpoint:`https://zoom.us/oauth/authorize`,state:e,redirectURI:n,codeVerifier:t.pkce?r:void 0,additionalParams:i}),validateAuthorizationCode:async({code:e,redirectURI:n,codeVerifier:r})=>AZ({code:e,redirectURI:t.redirectURI||n,codeVerifier:r,options:t,tokenEndpoint:`https://zoom.us/oauth/token`,authentication:`post`}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>DZ({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:`https://zoom.us/oauth/token`}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:n,error:r}=await BX(`https://api.zoom.us/v2/users/me`,{headers:{authorization:`Bearer ${e.accessToken}`}});if(r)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.display_name,image:n.pic_url,email:n.email,emailVerified:!!n.verified,...i},data:{...n}}}}},notion:Vfe,kakao:Nfe,naver:Bfe,line:Ffe,paybin:Hfe,paypal:Ufe,polar:Wfe,railway:Gfe,vercel:e=>({id:`vercel`,name:`Vercel`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!r)throw new D(`codeVerifier is required for Vercel`);let o;return(e.scope!==void 0||n!==void 0)&&(o=[],e.scope&&o.push(...e.scope),n&&o.push(...n)),ZY({id:`vercel`,options:e,authorizationEndpoint:`https://vercel.com/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://api.vercel.com/login/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.vercel.com/login/oauth/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}),wechat:e=>({id:`wechat`,name:`WeChat`,accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`snsapi_login`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://open.weixin.qq.com/connect/qrconnect`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`appid`,e.clientId),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),o.searchParams.set(`lang`,e.lang||`cn`),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`appid`&&o.searchParams.set(e,t);return o.hash=`wechat_redirect`,o},validateAuthorizationCode:async({code:t})=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/access_token?`+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:`authorization_code`}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`),openid:n.openid,unionid:n.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/refresh_token?`+new URLSearchParams({appid:e.clientId,grant_type:`refresh_token`,refresh_token:t}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.openid;if(!n)return null;let{data:r,error:i}=await BX(`https://api.weixin.qq.com/sns/userinfo?`+new URLSearchParams({access_token:t.accessToken||``,openid:n,lang:`zh_CN`}).toString(),{method:`GET`});if(i||!r||r.errcode)return null;let a=await e.mapProfileToUser?.(r),o=r.unionid||r.openid||n;return{user:{name:r.nickname,email:r.email||tQ({identifier:o,namespace:`wechat`}),image:r.headimgurl,emailVerified:!1,...a},data:r}},options:e})},Kfe=Object.keys(nQ),rQ=Je(Kfe).or(k());function iQ(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const qfe=X(`/list-accounts`,{method:`GET`,use:[VJ],metadata:{openapi:{operationId:`listUserAccounts`,description:`List all accounts linked to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},createdAt:{type:`string`,format:`date-time`},updatedAt:{type:`string`,format:`date-time`},accountId:{type:`string`},userId:{type:`string`},scopes:{type:`array`,items:{type:`string`}}},required:[`id`,`providerId`,`createdAt`,`updatedAt`,`accountId`,`userId`,`scopes`]}}}}}}}}},async e=>{let t=e.context.session,n=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(n.map(t=>{let{scope:n,...r}=rG(e.context.options,t);return{...r,scopes:iQ(n)}}))}),Jfe=X(`/link-social`,{method:`POST`,requireHeaders:!0,body:A({callbackURL:k().meta({description:`The URL to redirect to after the user has signed in`}).optional(),provider:rQ,idToken:A({token:k(),nonce:k().optional(),accessToken:k().optional(),refreshToken:k().optional()}).optional(),requestSignUp:Ge().optional(),scopes:Le(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:Ge().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:Ie(k(),Ze()).optional()}),use:[VJ],metadata:{openapi:{description:`Link a social account to the user`,operationId:`linkSocialAccount`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{url:{type:`string`,description:`The authorization URL to redirect the user to`},redirect:{type:`boolean`,description:`Indicates if the user should be redirected to the authorization URL`},status:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=e.context.session,n=await AY(e.context.socialProviders,{value:e.body.provider});if(!n)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!UZ(n))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await WZ(n,r,i,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let a=await n.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(wq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(n,{idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},a.data),s=await e.context.internalAdapter.findAccountByKey(o);if(s?.userId===t.user.id){let i=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>t!==void 0));return await e.context.internalAdapter.updateAccount(s.id,i),await JZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}if(s)throw E.from(`CONFLICT`,Y.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(n.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - linking not allowed`,code:`LINKING_NOT_ALLOWED`});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - different emails not allowed`,code:`LINKING_DIFFERENT_EMAILS_NOT_ALLOWED`});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...o,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)})}catch{throw E.from(`EXPECTATION_FAILED`,{message:`Account not linked - unable to create account`,code:`LINKING_FAILED`})}return await JZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}let r=jq(n),i=await Mq(e,{link:{userId:t.user.id,email:t.user.email},additionalData:e.body.additionalData,idTokenNonce:r}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:r,redirectURI:`${e.context.baseURL}${RY(n)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),Yfe=X(`/unlink-account`,{method:`POST`,body:A({accountId:k().meta({description:`The Better Auth account ID to unlink`})}),use:[UJ],metadata:{openapi:{description:`Unlink an account`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let{accountId:t}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(n.length===1&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_UNLINK_LAST_ACCOUNT);let r=n.find(e=>e.id===t);if(!r)throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(r.id),e.json({status:!0})});async function aQ(e,t){let n=await zJ(e,{disableCookieCache:RJ(e)});if(!n&&(e.request||e.headers))throw e.error(`UNAUTHORIZED`);let r=n?.user?.id||t;if(!r)throw E.from(`BAD_REQUEST`,{message:`Either userId or session is required`,code:`USER_ID_OR_SESSION_REQUIRED`});return r}const oQ=Oe([tt({accountId:k().meta({description:`The Better Auth account ID`}),userId:k().meta({description:`The user ID associated with the account`}).optional()}),tt({useAccountCookie:Ke(!0).meta({description:`Select the current OAuth account from its signed cookie`}),userId:k().meta({description:`The user ID associated with the account`}).optional()})]);function sQ(e,t,{resolvedUserId:n,selection:r}){return(!WW(e.context.options)||t.userId===n)&&(`accountId`in r?t.id===r.accountId:!0)}async function cQ(e,{resolvedUserId:t,selection:n}){if(`accountId`in n){let r=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===n.accountId);if(r)return{account:r,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let r=await YK(e);if(r&&sQ(e,r,{resolvedUserId:t,selection:n}))return{account:r,accountCookie:r}}throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND)}async function lQ(e,{resolvedUserId:t,selection:n,account:r}){let i=r??(await cQ(e,{resolvedUserId:t,selection:n})).account;if(!sQ(e,i,{resolvedUserId:t,selection:n}))throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);let a=await AY(e.context.socialProviders,{value:i.providerId});if(!a)throw E.from(`BAD_REQUEST`,{message:`Provider ${i.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});try{let t=null,n=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(i.refreshToken&&n&&a.refreshAccessToken){let n=await IY(i.refreshToken,e.context);t=await a.refreshAccessToken(n,e);let r={accessToken:await LY(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await LY(t.refreshToken,e.context):i.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:t?.idToken||i.idToken},o=null;i.id&&(o=await e.context.internalAdapter.updateAccount(i.id,r)),e.context.options.account?.storeAccountCookie&&await JK(e,{...i,...o??r})}let r=(()=>{if(t?.accessTokenExpiresAt)return typeof t.accessTokenExpiresAt==`string`?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt;if(i.accessTokenExpiresAt)return typeof i.accessTokenExpiresAt==`string`?new Date(i.accessTokenExpiresAt):i.accessTokenExpiresAt})();return{accessToken:t?.accessToken??await IY(i.accessToken??``,e.context),accessTokenExpiresAt:r,scopes:iQ(i.scope),idToken:t?.idToken??i.idToken??void 0}}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to get a valid access token`,code:`FAILED_TO_GET_ACCESS_TOKEN`})}}const Xfe=X(`/get-access-token`,{method:`POST`,body:oQ,metadata:{openapi:{description:`Get a valid access token, doing a refresh if needed`,responses:{200:{description:`A Valid access token`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,n=await lQ(e,{resolvedUserId:await aQ(e,t),selection:e.body});return e.json(n)}),Zfe=X(`/refresh-token`,{method:`POST`,body:oQ,metadata:{openapi:{description:`Refresh the access token using a refresh token`,responses:{200:{description:`Access token refreshed successfully`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},refreshToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`},refreshTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,{account:n,accountCookie:r}=await cQ(e,{resolvedUserId:await aQ(e,t),selection:e.body}),i=await AY(e.context.socialProviders,{value:n.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});if(!i.refreshAccessToken)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} does not support token refreshing.`,code:`TOKEN_REFRESH_NOT_SUPPORTED`});let a=n.refreshToken??void 0;if(!a)throw E.from(`BAD_REQUEST`,{message:`Refresh token not found`,code:`REFRESH_TOKEN_NOT_FOUND`});try{let t=await IY(a,e.context),o=await i.refreshAccessToken(t,e),s=o.refreshToken?await LY(o.refreshToken,e.context):a,c=o.refreshTokenExpiresAt??n.refreshTokenExpiresAt,l={accessToken:await LY(o.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,idToken:o.idToken||n.idToken},u=null;n.id&&(u=await e.context.internalAdapter.updateAccount(n.id,l)),r?.id===n.id&&e.context.options.account?.storeAccountCookie&&await JK(e,{...r,...u??l});let d=u?.scope??n.scope;return e.json({accessToken:o.accessToken,refreshToken:o.refreshToken??t,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,scope:d,idToken:o.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to refresh access token`,code:`FAILED_TO_REFRESH_ACCESS_TOKEN`})}}),Qfe=X(`/account-info`,{method:`GET`,metadata:{openapi:{description:`Get the account info provided by the provider`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,properties:{name:{type:`string`},email:{type:`string`,nullable:!0},image:{type:`string`},emailVerified:{type:`boolean`}},required:[`emailVerified`]},account:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},accountId:{type:`string`}},required:[`id`,`providerId`,`accountId`],additionalProperties:!1},data:{type:`object`,properties:{},additionalProperties:!0}},required:[`user`,`data`,`account`],additionalProperties:!1}}}}}}},query:oQ},async e=>{let{userId:t}=e.query,n=await aQ(e,t),{account:r}=await cQ(e,{resolvedUserId:n,selection:e.query}),i=await AY(e.context.socialProviders,{value:r.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Account is not associated with a configured social provider.`,code:`PROVIDER_NOT_CONFIGURED`});let a=await lQ(e,{resolvedUserId:n,selection:e.query,account:r});if(!a.accessToken)throw E.from(`BAD_REQUEST`,{message:`Access token not found`,code:`ACCESS_TOKEN_NOT_FOUND`});let o=await i.getUserInfo({...a,accessToken:a.accessToken});if(!o)throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);return e.json({...o,account:{id:r.id,providerId:r.providerId,accountId:r.accountId}})}),uQ=A({code:k().optional(),error:k().optional(),device_id:k().optional(),error_description:k().optional(),state:k().optional(),user:k().optional(),iss:k().optional()}),$fe=X(`/callback/:id`,{method:[`GET`,`POST`],operationId:`handleOAuthCallback`,body:uQ.optional(),query:uQ.optional(),metadata:{...Pq,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`]}},async e=>{let t,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if(e.method===`POST`){let t=e.body?uQ.parse(e.body):{},n=e.query?uQ.parse(e.query):{},r=uQ.parse({...t,...n}),i=new URLSearchParams;for(let[e,t]of Object.entries(r))t!=null&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if(e.method===`GET`)t=uQ.parse(e.query);else if(e.method===`POST`)t=uQ.parse(e.body);else throw Error(`Unsupported method`)}catch(t){e.context.logger.error(`INVALID_CALLBACK_REQUEST`,t);let r=bq(n,new URLSearchParams({error:`invalid_callback_request`}));throw e.redirect(r)}let{code:r,error:i,state:a,error_description:o,device_id:s,user:c,iss:l}=t;if(a===void 0&&r){let t=await AY(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let n=jq(t),{state:r,codeVerifier:i}=await Mq(e,{idTokenNonce:n}),a=await t.createAuthorizationURL({state:r,codeVerifier:i,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`});throw e.redirect(a.toString())}}if(!a){e.context.logger.error(`State not found`,i);let t=bq(n,new URLSearchParams({error:`state_not_found`}));throw e.redirect(t)}let{codeVerifier:u,callbackURL:d,link:f,errorURL:p,newUserURL:m,requestSignUp:h,idTokenNonce:g}=await Nq(e);function _(t,r){let i=p??n,a=new URLSearchParams({error:t});r&&a.set(`error_description`,r);let o=bq(i,a);throw e.redirect(o)}if(i&&_(i,o),!r)throw e.context.logger.warn(`Code not found`),_(Sq.NO_CODE);let v=await AY(e.context.socialProviders,{value:e.params.id});if(!v)throw e.context.logger.warn(`OAuth provider not found`,{providerId:e.params.id}),_(Sq.PROVIDER_NOT_FOUND);if(l&&v.issuer&&l!==v.issuer)throw e.context.logger.error(`OAuth issuer mismatch`,{expected:v.issuer,received:l}),_(Sq.ISSUER_MISMATCH);if(v.requiresIdTokenNonce&&!g)throw e.context.logger.error(`OAuth id_token nonce binding required but no expected nonce was found in state`,{providerId:v.id}),_(Sq.NONCE_BINDING_MISSING);let y;try{y=await v.validateAuthorizationCode({code:r,codeVerifier:u,deviceId:s,redirectURI:`${e.context.baseURL}${RY(v)}`})}catch(t){throw e.context.logger.error(``,t),_(Sq.INVALID_CODE)}if(!y)throw _(Sq.INVALID_CODE);let b=c?le(c):null,x=await v.getUserInfo({...y,...g?{expectedIdTokenNonce:g}:{},user:b??void 0});if(!x?.user)return e.context.logger.error(`Unable to get user info`),_(Sq.UNABLE_TO_GET_USER_INFO);let S=x.user,ee=MY(x.data),C;try{C=await NY(v,y,x.data)}catch(t){return e.context.logger.error(`Unable to derive provider account identity`,{providerId:v.id,error:t}),_(Sq.UNABLE_TO_GET_USER_INFO)}let{accountId:te}=C;if(!d)throw e.context.logger.error(`No callback URL found`),_(Sq.NO_CALLBACK_URL);let ne={...C,...y,scope:y.scopes?.join(`,`)};if(f){let t=await mfe(e,{link:f,userInfo:S,account:ne,profile:ee,scopes:y.scopes});if(!t.linked)return _(t.error.code,t.error.message);throw e.redirect(d)}if(!S.email)return e.context.logger.error(wq(v.id)),_(Sq.EMAIL_NOT_FOUND);let w;try{w=await KZ(e,{userInfo:{...S,id:te,email:S.email,name:S.name||``},account:ne,callbackURL:d,disableSignUp:v.disableImplicitSignUp&&!h||v.options?.disableSignUp,overrideUserInfo:v.options?.overrideUserInfoOnSignIn,source:{method:`oauth`,oauth:{providerId:v.id,profile:ee}}})}catch(e){throw Fq(e)&&e.body?.code&&_(e.body.code,e.body.message),e}if(w.error)return e.context.logger.error(w.error.split(` `).join(`_`)),_(w.error.split(` `).join(`_`));let{session:T,user:re}=w.data;await aq(e,{session:T,user:re});let ie;try{ie=(w.isRegister&&m||d).toString()}catch{ie=w.isRegister&&m||d}throw e.redirect(ie)});function dQ(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,`&`)}const epe=(e,t=`Unknown`,n=null)=>{let r=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
74
|
-
<html lang="en">
|
|
75
|
-
<head>
|
|
76
|
-
<meta charset="UTF-8" />
|
|
77
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
78
|
-
<title>Error</title>
|
|
79
|
-
<style>
|
|
80
|
-
* {
|
|
81
|
-
box-sizing: border-box;
|
|
82
|
-
}
|
|
83
|
-
body {
|
|
84
|
-
font-family: ${r?.font?.defaultFamily||`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`};
|
|
85
|
-
background: ${r?.colors?.background||`var(--background)`};
|
|
86
|
-
color: var(--foreground);
|
|
87
|
-
margin: 0;
|
|
88
|
-
}
|
|
89
|
-
:root,
|
|
90
|
-
:host {
|
|
91
|
-
--spacing: 0.25rem;
|
|
92
|
-
--container-md: 28rem;
|
|
93
|
-
--text-sm: ${r?.size?.textSm||`0.875rem`};
|
|
94
|
-
--text-sm--line-height: calc(1.25 / 0.875);
|
|
95
|
-
--text-2xl: ${r?.size?.text2xl||`1.5rem`};
|
|
96
|
-
--text-2xl--line-height: calc(2 / 1.5);
|
|
97
|
-
--text-4xl: ${r?.size?.text4xl||`2.25rem`};
|
|
98
|
-
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
99
|
-
--text-6xl: ${r?.size?.text6xl||`3rem`};
|
|
100
|
-
--text-6xl--line-height: 1;
|
|
101
|
-
--font-weight-medium: 500;
|
|
102
|
-
--font-weight-semibold: 600;
|
|
103
|
-
--font-weight-bold: 700;
|
|
104
|
-
--default-transition-duration: 150ms;
|
|
105
|
-
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
106
|
-
--radius: ${r?.size?.radiusSm||`0.625rem`};
|
|
107
|
-
--default-mono-font-family: ${r?.font?.monoFamily||`var(--font-geist-mono)`};
|
|
108
|
-
--primary: ${r?.colors?.primary||`black`};
|
|
109
|
-
--primary-foreground: ${r?.colors?.primaryForeground||`white`};
|
|
110
|
-
--background: ${r?.colors?.background||`white`};
|
|
111
|
-
--foreground: ${r?.colors?.foreground||`oklch(0.271 0 0)`};
|
|
112
|
-
--border: ${r?.colors?.border||`oklch(0.89 0 0)`};
|
|
113
|
-
--destructive: ${r?.colors?.destructive||`oklch(0.55 0.15 25.723)`};
|
|
114
|
-
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.545 0 0)`};
|
|
115
|
-
--corner-border: ${r?.colors?.cornerBorder||`#404040`};
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
button, .btn {
|
|
119
|
-
cursor: pointer;
|
|
120
|
-
background: none;
|
|
121
|
-
border: none;
|
|
122
|
-
color: inherit;
|
|
123
|
-
font: inherit;
|
|
124
|
-
transition: all var(--default-transition-duration)
|
|
125
|
-
var(--default-transition-timing-function);
|
|
126
|
-
}
|
|
127
|
-
button:hover, .btn:hover {
|
|
128
|
-
opacity: 0.8;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
@media (prefers-color-scheme: dark) {
|
|
132
|
-
:root,
|
|
133
|
-
:host {
|
|
134
|
-
--primary: ${r?.colors?.primary||`white`};
|
|
135
|
-
--primary-foreground: ${r?.colors?.primaryForeground||`black`};
|
|
136
|
-
--background: ${r?.colors?.background||`oklch(0.15 0 0)`};
|
|
137
|
-
--foreground: ${r?.colors?.foreground||`oklch(0.98 0 0)`};
|
|
138
|
-
--border: ${r?.colors?.border||`oklch(0.27 0 0)`};
|
|
139
|
-
--destructive: ${r?.colors?.destructive||`oklch(0.65 0.15 25.723)`};
|
|
140
|
-
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.65 0 0)`};
|
|
141
|
-
--corner-border: ${r?.colors?.cornerBorder||`#a0a0a0`};
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
@media (max-width: 640px) {
|
|
145
|
-
:root, :host {
|
|
146
|
-
--text-6xl: 2.5rem;
|
|
147
|
-
--text-2xl: 1.25rem;
|
|
148
|
-
--text-sm: 0.8125rem;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
@media (max-width: 480px) {
|
|
152
|
-
:root, :host {
|
|
153
|
-
--text-6xl: 2rem;
|
|
154
|
-
--text-2xl: 1.125rem;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
</style>
|
|
158
|
-
</head>
|
|
159
|
-
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
160
|
-
<div
|
|
161
|
-
style="
|
|
162
|
-
display: flex;
|
|
163
|
-
flex-direction: column;
|
|
164
|
-
align-items: center;
|
|
165
|
-
justify-content: center;
|
|
166
|
-
gap: 1.5rem;
|
|
167
|
-
position: relative;
|
|
168
|
-
width: 100%;
|
|
169
|
-
min-height: 100vh;
|
|
170
|
-
padding: 1rem;
|
|
171
|
-
"
|
|
172
|
-
>
|
|
173
|
-
${r?.disableBackgroundGrid?``:`
|
|
174
|
-
<div
|
|
175
|
-
style="
|
|
176
|
-
position: absolute;
|
|
177
|
-
inset: 0;
|
|
178
|
-
background-image: linear-gradient(to right, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px),
|
|
179
|
-
linear-gradient(to bottom, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px);
|
|
180
|
-
background-size: 40px 40px;
|
|
181
|
-
opacity: 0.6;
|
|
182
|
-
pointer-events: none;
|
|
183
|
-
width: 100vw;
|
|
184
|
-
height: 100vh;
|
|
185
|
-
"
|
|
186
|
-
></div>
|
|
187
|
-
<div
|
|
188
|
-
style="
|
|
189
|
-
position: absolute;
|
|
190
|
-
inset: 0;
|
|
191
|
-
display: flex;
|
|
192
|
-
align-items: center;
|
|
193
|
-
justify-content: center;
|
|
194
|
-
background: ${r?.colors?.background||`var(--background)`};
|
|
195
|
-
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
196
|
-
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
197
|
-
pointer-events: none;
|
|
198
|
-
"
|
|
199
|
-
></div>
|
|
200
|
-
`}
|
|
201
|
-
|
|
202
|
-
<div
|
|
203
|
-
style="
|
|
204
|
-
position: relative;
|
|
205
|
-
z-index: 10;
|
|
206
|
-
border: 2px solid var(--border);
|
|
207
|
-
background: ${r?.colors?.cardBackground||`var(--background)`};
|
|
208
|
-
padding: 1.5rem;
|
|
209
|
-
max-width: 42rem;
|
|
210
|
-
width: 100%;
|
|
211
|
-
"
|
|
212
|
-
>
|
|
213
|
-
${r?.disableCornerDecorations?``:`
|
|
214
|
-
<!-- Corner decorations -->
|
|
215
|
-
<div
|
|
216
|
-
style="
|
|
217
|
-
position: absolute;
|
|
218
|
-
top: -2px;
|
|
219
|
-
left: -2px;
|
|
220
|
-
width: 2rem;
|
|
221
|
-
height: 2rem;
|
|
222
|
-
border-top: 4px solid var(--corner-border);
|
|
223
|
-
border-left: 4px solid var(--corner-border);
|
|
224
|
-
"
|
|
225
|
-
></div>
|
|
226
|
-
<div
|
|
227
|
-
style="
|
|
228
|
-
position: absolute;
|
|
229
|
-
top: -2px;
|
|
230
|
-
right: -2px;
|
|
231
|
-
width: 2rem;
|
|
232
|
-
height: 2rem;
|
|
233
|
-
border-top: 4px solid var(--corner-border);
|
|
234
|
-
border-right: 4px solid var(--corner-border);
|
|
235
|
-
"
|
|
236
|
-
></div>
|
|
237
|
-
|
|
238
|
-
<div
|
|
239
|
-
style="
|
|
240
|
-
position: absolute;
|
|
241
|
-
bottom: -2px;
|
|
242
|
-
left: -2px;
|
|
243
|
-
width: 2rem;
|
|
244
|
-
height: 2rem;
|
|
245
|
-
border-bottom: 4px solid var(--corner-border);
|
|
246
|
-
border-left: 4px solid var(--corner-border);
|
|
247
|
-
"
|
|
248
|
-
></div>
|
|
249
|
-
<div
|
|
250
|
-
style="
|
|
251
|
-
position: absolute;
|
|
252
|
-
bottom: -2px;
|
|
253
|
-
right: -2px;
|
|
254
|
-
width: 2rem;
|
|
255
|
-
height: 2rem;
|
|
256
|
-
border-bottom: 4px solid var(--corner-border);
|
|
257
|
-
border-right: 4px solid var(--corner-border);
|
|
258
|
-
"
|
|
259
|
-
></div>`}
|
|
260
|
-
|
|
261
|
-
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
262
|
-
<div style="margin-bottom: 1.5rem;">
|
|
263
|
-
<div
|
|
264
|
-
style="
|
|
265
|
-
display: inline-block;
|
|
266
|
-
border: 2px solid ${r?.disableTitleBorder?`transparent`:r?.colors?.titleBorder||`var(--destructive)`};
|
|
267
|
-
padding: 0.375rem 1rem;
|
|
268
|
-
"
|
|
269
|
-
>
|
|
270
|
-
<h1
|
|
271
|
-
style="
|
|
272
|
-
font-size: var(--text-6xl);
|
|
273
|
-
font-weight: var(--font-weight-semibold);
|
|
274
|
-
color: ${r?.colors?.titleColor||`var(--foreground)`};
|
|
275
|
-
letter-spacing: -0.02em;
|
|
276
|
-
margin: 0;
|
|
277
|
-
"
|
|
278
|
-
>
|
|
279
|
-
ERROR
|
|
280
|
-
</h1>
|
|
281
|
-
</div>
|
|
282
|
-
<div
|
|
283
|
-
style="
|
|
284
|
-
height: 2px;
|
|
285
|
-
background-color: var(--border);
|
|
286
|
-
width: calc(100% + 3rem);
|
|
287
|
-
margin-left: -1.5rem;
|
|
288
|
-
margin-top: 1.5rem;
|
|
289
|
-
"
|
|
290
|
-
></div>
|
|
291
|
-
</div>
|
|
292
|
-
|
|
293
|
-
<h2
|
|
294
|
-
style="
|
|
295
|
-
font-size: var(--text-2xl);
|
|
296
|
-
font-weight: var(--font-weight-semibold);
|
|
297
|
-
color: var(--foreground);
|
|
298
|
-
margin: 0 0 1rem;
|
|
299
|
-
"
|
|
300
|
-
>
|
|
301
|
-
Something went wrong
|
|
302
|
-
</h2>
|
|
303
|
-
|
|
304
|
-
<div
|
|
305
|
-
style="
|
|
306
|
-
display: inline-flex;
|
|
307
|
-
align-items: center;
|
|
308
|
-
gap: 0.5rem;
|
|
309
|
-
border: 2px solid var(--border);
|
|
310
|
-
background-color: var(--muted);
|
|
311
|
-
padding: 0.375rem 0.75rem;
|
|
312
|
-
margin: 0 0 1rem;
|
|
313
|
-
flex-wrap: wrap;
|
|
314
|
-
justify-content: center;
|
|
315
|
-
"
|
|
316
|
-
>
|
|
317
|
-
<span
|
|
318
|
-
style="
|
|
319
|
-
font-size: 0.75rem;
|
|
320
|
-
color: var(--muted-foreground);
|
|
321
|
-
font-weight: var(--font-weight-semibold);
|
|
322
|
-
"
|
|
323
|
-
>
|
|
324
|
-
CODE:
|
|
325
|
-
</span>
|
|
326
|
-
<span
|
|
327
|
-
style="
|
|
328
|
-
font-size: var(--text-sm);
|
|
329
|
-
font-family: var(--default-mono-font-family, monospace);
|
|
330
|
-
color: var(--foreground);
|
|
331
|
-
word-break: break-all;
|
|
332
|
-
"
|
|
333
|
-
>
|
|
334
|
-
${dQ(t)}
|
|
335
|
-
</span>
|
|
336
|
-
</div>
|
|
337
|
-
|
|
338
|
-
<p
|
|
339
|
-
style="
|
|
340
|
-
color: var(--muted-foreground);
|
|
341
|
-
max-width: 28rem;
|
|
342
|
-
margin: 0 auto;
|
|
343
|
-
font-size: var(--text-sm);
|
|
344
|
-
line-height: 1.5;
|
|
345
|
-
text-wrap: pretty;
|
|
346
|
-
"
|
|
347
|
-
>
|
|
348
|
-
${n||`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`}
|
|
349
|
-
</p>
|
|
350
|
-
</div>
|
|
351
|
-
|
|
352
|
-
<div
|
|
353
|
-
style="
|
|
354
|
-
display: flex;
|
|
355
|
-
gap: 0.75rem;
|
|
356
|
-
margin-top: 1.5rem;
|
|
357
|
-
justify-content: center;
|
|
358
|
-
flex-wrap: wrap;
|
|
359
|
-
"
|
|
360
|
-
>
|
|
361
|
-
<a
|
|
362
|
-
href="/"
|
|
363
|
-
style="
|
|
364
|
-
text-decoration: none;
|
|
365
|
-
"
|
|
366
|
-
>
|
|
367
|
-
<div
|
|
368
|
-
style="
|
|
369
|
-
border: 2px solid var(--border);
|
|
370
|
-
background: var(--primary);
|
|
371
|
-
color: var(--primary-foreground);
|
|
372
|
-
padding: 0.5rem 1rem;
|
|
373
|
-
border-radius: 0;
|
|
374
|
-
white-space: nowrap;
|
|
375
|
-
"
|
|
376
|
-
class="btn"
|
|
377
|
-
>
|
|
378
|
-
Go Home
|
|
379
|
-
</div>
|
|
380
|
-
</a>
|
|
381
|
-
<a
|
|
382
|
-
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
|
|
383
|
-
target="_blank"
|
|
384
|
-
rel="noopener noreferrer"
|
|
385
|
-
style="
|
|
386
|
-
text-decoration: none;
|
|
387
|
-
"
|
|
388
|
-
>
|
|
389
|
-
<div
|
|
390
|
-
style="
|
|
391
|
-
border: 2px solid var(--border);
|
|
392
|
-
background: transparent;
|
|
393
|
-
color: var(--foreground);
|
|
394
|
-
padding: 0.5rem 1rem;
|
|
395
|
-
border-radius: 0;
|
|
396
|
-
white-space: nowrap;
|
|
397
|
-
"
|
|
398
|
-
class="btn"
|
|
399
|
-
>
|
|
400
|
-
Ask AI
|
|
401
|
-
</div>
|
|
402
|
-
</a>
|
|
403
|
-
</div>
|
|
404
|
-
</div>
|
|
405
|
-
</div>
|
|
406
|
-
</body>
|
|
407
|
-
</html>`},tpe=X(`/error`,{method:`GET`,metadata:{...Pq,openapi:{description:`Displays an error page`,responses:{200:{description:`Success`,content:{"text/html":{schema:{type:`string`,description:`The HTML content of the error page`}}}}}}}},async e=>{let t=new URL(e.request?.url||``),n=t.searchParams.get(`error`)||`UNKNOWN`,r=t.searchParams.get(`error_description`)||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||``)?n:`UNKNOWN`,a=r?dQ(r):null,o=new URLSearchParams;o.set(`error`,i),r&&o.set(`error_description`,r);let s=e.context.options,c=s.onAPIError?.errorURL;if(c){let e=bq(c,o);return new Response(null,{status:302,headers:{Location:e}})}return te&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(epe(e.context.options,i,a),{headers:{"Content-Type":`text/html`}})}),npe=X(`/ok`,{method:`GET`,metadata:{...Pq,openapi:{description:`Check if the API is working`,responses:{200:{description:`API is working`,content:{"application/json":{schema:{type:`object`,properties:{ok:{type:`boolean`,description:`Indicates if the API is working`}},required:[`ok`]}}}}}}}},async e=>e.json({ok:!0}));function fQ(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_SHORT)}function pQ(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_LONG)}async function rpe(e,t,n,r){await wH(e.context.adapter,async()=>{await r?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t)?await e.context.internalAdapter.updatePassword(t,n):await e.context.internalAdapter.createAccount({userId:t,providerId:`credential`,accountId:t,password:n})})}async function ipe(e,t){pQ(e,t.password);let n=await e.context.internalAdapter.findCredentialAccount(t.userId),r=n?.password;return!n||!r?!1:await e.context.password.verify({hash:r,password:t.password})}async function ape(e,t){let n=t.body.password;typeof n==`string`&&pQ(t,n);let r=await t.context.internalAdapter.findCredentialAccount(e),i=r?.password;if(!r||!i||!n)throw n&&await t.context.password.hash(n),E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);if(!await t.context.password.verify({hash:i,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return!0}function mQ(e,t,n){let r=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}function ope(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 spe=X(`/request-password-reset`,{method:`POST`,body:A({email:Re().meta({description:`The email address of the user to send a password reset email to`}),redirectTo:k().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:`requestPasswordReset`,description:`Send a password reset email to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`},message:{type:`string`}}}}}}}}},use:[tJ(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error(`Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!`),E.from(`BAD_REQUEST`,{message:`Reset password isn't enabled`,code:`RESET_PASSWORD_DISABLED`});let{email:t,redirectTo:n}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return pe(24),await e.context.internalAdapter.findVerificationValue(`dummy-verification-token`),e.context.logger.warn(`Reset Password: User not found`),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`});let i=uG(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,`sec`),a=pe(24);await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=n?encodeURIComponent(n):``,s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:r.user,url:s,token:a},e.request)),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`})}),cpe=X(`/reset-password/:token`,{method:`GET`,operationId:`resetPasswordCallback`,query:A({callbackURL:k().meta({description:`The URL to redirect the user to reset their password`})}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{operationId:`resetPasswordCallback`,description:`Redirects the user to the callback URL with the token`,parameters:[{name:`token`,in:`path`,required:!0,description:`The token to reset the password`,schema:{type:`string`}},{name:`callbackURL`,in:`query`,required:!0,description:`The URL to redirect the user to reset their password`,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:n}=e.query;if(!t||!n)throw e.redirect(mQ(e.context,n,{error:`INVALID_TOKEN`}));let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt</* @__PURE__ */ new Date?e.redirect(mQ(e.context,n,{error:`INVALID_TOKEN`})):e.redirect(ope(e.context,n,{token:t}))}),lpe=X(`/reset-password`,{method:`POST`,operationId:`resetPassword`,query:A({token:k().optional()}).optional(),body:A({newPassword:k().meta({description:`The new password to set`}),token:k().meta({description:`The token to reset the password`}).optional()}),metadata:{openapi:{operationId:`resetPassword`,description:`Reset the password for a user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let{newPassword:n}=e.body;fQ(e,n),pQ(e,n);let r=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(r);if(!i||i.expiresAt</* @__PURE__ */ new Date)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let a=i.value,o=await e.context.internalAdapter.findUserById(a);if(!o)throw E.from(`BAD_REQUEST`,Y.USER_NOT_FOUND);return await rpe(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})}),upe=X(`/verify-password`,{method:`POST`,body:A({password:k().meta({description:`The password to verify`})}),metadata:{scope:`server`,openapi:{operationId:`verifyPassword`,description:`Verify the current user's password`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}},use:[HJ]},async e=>{let{password:t}=e.body,n=e.context.session;if(!await ipe(e,{password:t,userId:n.user.id}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return e.json({status:!0})}),dpe=A({callbackURL:k().meta({description:`Callback URL to redirect to after the user has signed in`}).optional(),newUserCallbackURL:k().optional(),errorCallbackURL:k().meta({description:`Callback URL to redirect to if an error happens`}).optional(),provider:rQ,disableRedirect:Ge().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),idToken:nt(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:Fe().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:Le(k()).meta({description:`Array of scopes to request from the provider. This will override the default scopes passed.`}).optional(),requestSignUp:Ge().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:Ie(k(),Ze()).optional().meta({description:`Additional data to be passed through the OAuth flow`})}),fpe=()=>X(`/sign-in/social`,{method:`POST`,operationId:`socialSignIn`,body:dpe,metadata:{$Infer:{body:{},returned:{}},openapi:{description:`Sign in with a social provider`,operationId:`socialSignIn`,responses:{200:{description:`Success - Returns session details (idToken branch) or an authorize URL (redirect branch)`,content:{"application/json":{schema:{type:`object`,description:`Returns session details when idToken is provided, or an authorize URL otherwise`,properties:{token:{type:`string`},user:{type:`object`,$ref:`#/components/schemas/User`},url:{type:`string`},redirect:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=await AY(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!UZ(t))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:r}=e.body.idToken;if(!await WZ(t,n,r,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let i={idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},a=await t.getUserInfo(i);if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(wq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(t,i,a.data),s=MY(a.data),c=await KZ(e,{userInfo:{...a.user,email:a.user.email,id:o.accountId,name:a.user.name||``,image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{...o,accessToken:e.body.idToken.accessToken,idToken:n},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:`oauth`,oauth:{providerId:t.id,profile:s}}});if(c.error)throw c.error===Sq.EMAIL_NOT_VERIFIED?E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED):E.from(`UNAUTHORIZED`,{message:c.error,code:`OAUTH_LINK_ERROR`});return await aq(e,c.data),e.json({redirect:!1,token:c.data.session.token,url:void 0,user:eG(e.context.options,c.data.user)})}let n=jq(t),{codeVerifier:r,state:i}=await Mq(e,{additionalData:e.body.additionalData,idTokenNonce:n}),a=await t.createAuthorizationURL({state:i,codeVerifier:r,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),ppe=()=>X(`/sign-in/email`,{method:`POST`,operationId:`signInEmail`,use:[rJ],cloneRequest:!0,body:A({email:k().meta({description:`Email of the user`}),password:k().meta({description:`Password of the user`}),callbackURL:k().meta({description:`Callback URL to use as a redirect for email verification`}).optional(),rememberMe:Ge().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(!Re().safeParse(t).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);pQ(e,n);let r=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),i=r?.accounts.find(e=>e.providerId===`credential`&&e.accountId===r.user.id);if(!r||!i)throw await e.context.password.hash(n),e.context.logger.warn(`User not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);let a=r.user,o=i.password;if(!o)throw await e.context.password.hash(n),e.context.logger.warn(`Password not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:o,password:n}))throw e.context.logger.warn(`Invalid password`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!a.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await BY(e.context.secret,a.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:a,url:r,token:t},zY(e.request)))}throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(a.id,e.body.rememberMe===!1);if(!s)throw e.context.logger.error(`Failed to create session`),E.from(`UNAUTHORIZED`,Y.FAILED_TO_CREATE_SESSION);return await aq(e,{session:s,user:a},e.body.rememberMe===!1),e.body.callbackURL&&e.setHeader(`Location`,e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:eG(e.context.options,a)})}),mpe=A({callbackURL:k().meta({description:`The URL to redirect to after provider logout`}).optional(),disableRedirect:Ge().meta({description:`Return the provider logout URL without redirecting`}).optional(),state:k().meta({description:`State to pass to the provider logout endpoint`}).optional()}).optional(),hQ=e=>({success:!0,url:e?.url,redirect:e?.redirect}),hpe=X(`/sign-out`,{method:`POST`,body:mpe,operationId:`signOut`,requireHeaders:!0,metadata:{openapi:{operationId:`signOut`,description:`Sign out the current user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`},url:{type:`string`,description:`Provider logout URL when RP-initiated logout is available`},redirect:{type:`boolean`,description:`Whether the client should redirect to the provider logout URL`}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),n=null;if(t)try{n=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error(`Failed to read session from database`,t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error(`Failed to delete session from database`,t)}lq(e);let r=await(async()=>{try{if(!n)return null;let t=await e.context.internalAdapter.findAccounts(n.user.id),r=new Map(e.context.socialProviders.map(e=>[e.id,e])),i=t.filter(e=>!!r.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(i.length===0)return null;let a=/* @__PURE__ */ new Set,o=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of i){if(a.has(t.providerId))continue;a.add(t.providerId);let n=r.get(t.providerId);try{let r=await n?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:o,state:e.body?.state});if(r)return r.toString()}catch(n){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,n)}}return null}catch(t){return e.context.logger.error(`Failed to create provider logout URL`,t),null}})();if(r){let t=!e.body?.disableRedirect;return t&&e.setHeader(`Location`,r),e.json(hQ({url:r,redirect:t}))}return e.json(hQ())}),gpe=A({name:k(),email:Re(),password:k().nonempty(),image:k().optional(),callbackURL:k().optional(),rememberMe:Ge().optional()}).and(Ie(k(),Ze())),_pe=()=>X(`/sign-up/email`,{method:`POST`,operationId:`signUpWithEmailAndPassword`,use:[rJ],body:gpe,cloneRequest:!0,metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signUpWithEmailAndPassword`,description:`Sign up a user using email and password`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},email:{type:`string`,description:`The email of the user`},password:{type:`string`,description:`The password of the user`},image:{type:`string`,description:`The profile image URL of the user`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`},rememberMe:{type:`boolean`,description:"If this is false, the session will not be remembered. Default is `true`."}},required:[`name`,`email`,`password`]}}}},responses:{200:{description:`Successfully created user`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`Authentication token for the session`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}},422:{description:`Unprocessable Entity. User already exists or failed to create user.`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}}}}}}},async e=>wH(e.context.adapter,async()=>{if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw E.from(`BAD_REQUEST`,{message:`Email and password sign up is not enabled`,code:`EMAIL_PASSWORD_SIGN_UP_DISABLED`});let t=e.body,{name:n,email:r,password:i,image:a,callbackURL:o,rememberMe:s,...c}=t;if(!Re().safeParse(r).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);if(!i||typeof i!=`string`)throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);fQ(e,i),pQ(e,i);let l=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,u=e.context.options.emailAndPassword.autoSignIn===!1||l,d=aG(e.context.options,c,`create`),f=r.toLowerCase(),p=()=>{let t=/* @__PURE__ */ new Date,r=e.context.generateId({model:`user`})||pe(),i={name:n,email:f,emailVerified:!1,image:a??null,createdAt:t,updatedAt:t},o=e.context.options.emailAndPassword?.customSyntheticUser,s;if(o){let t=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of t)e in d&&(n[e]=d[e]);let a=o({coreFields:i,additionalFields:n,id:r});s=tG(e.context.options,a)}else s=tG(e.context.options,{...i,...d,id:r});return e.json({token:null,user:eG(e.context.options,s)})},m=await e.context.internalAdapter.findUserByEmail(f);if(m?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${r}`),l)return await e.context.password.hash(i),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:m.user},zY(e.request))),p();throw E.from(`UNPROCESSABLE_ENTITY`,Y.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let h=await e.context.password.hash(i),g;try{if(g=await e.context.internalAdapter.createUser({email:f,name:n,image:a,...d,emailVerified:!1},{method:`email-password`}),!g)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_USER)}catch(t){if(Fq(t)){if(t.statusCode===403&&l)return p();throw t}throw S()&&e.context.logger.error(`Failed to create user`,t),e.context.logger?.error(`Failed to create user`,t),E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER)}if(!g)throw E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:g.id,providerId:`credential`,accountId:g.id,password:h}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await BY(e.context.secret,g.email,void 0,e.context.options.emailVerification?.expiresIn),r=t.callbackURL?encodeURIComponent(t.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:g,url:i,token:n},zY(e.request)))}if(u)return e.json({token:null,user:eG(e.context.options,g)});let _=await e.context.internalAdapter.createSession(g.id,s===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!_)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_SESSION);return await aq(e,{session:_,user:g},s===!1),e.json({token:_.token,user:eG(e.context.options,g)})})),vpe=Ie(k().meta({description:`Field name must be a string`}),Ze()),ype=()=>X(`/update-session`,{method:`POST`,operationId:`updateSession`,body:vpe,use:[VJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateSession`,description:`Update the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{session:{type:`object`,$ref:`#/components/schemas/Session`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,r=sG(e.context.options,t,`update`);if(Object.keys(r).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let i=await e.context.internalAdapter.updateSession(n.session.token,{...r,updatedAt:/* @__PURE__ */ new Date});if(!i&&RJ(e))throw lq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let a=i??{...n.session,...r,updatedAt:/* @__PURE__ */ new Date};return await aq(e,{session:a,user:n.user}),e.json({session:nG(e.context.options,a)})}),bpe=Ie(k().meta({description:`Field name must be a string`}),Ze()),xpe=()=>X(`/update-user`,{method:`POST`,operationId:`updateUser`,body:bpe,use:[VJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateUser`,description:`Update the current user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},image:{type:`string`,description:`The image of the user`,nullable:!0}}}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);if(t.email)throw E.from(`BAD_REQUEST`,Y.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:r,...i}=t,a=e.context.session,o=aG(e.context.options,i,`update`);if(r===void 0&&n===void 0&&Object.keys(o).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:n,image:r,...o})??{...a.user,...n!==void 0&&{name:n},...r!==void 0&&{image:r},...o};return await aq(e,{session:a.session,user:s}),e.json({status:!0})}),Spe=X(`/change-password`,{method:`POST`,operationId:`changePassword`,body:A({newPassword:k().meta({description:`The new password to set`}),currentPassword:k().meta({description:`The current password is required`}),revokeOtherSessions:Ge().meta({description:`Must be a boolean value`}).optional()}),use:[HJ],metadata:{openapi:{operationId:`changePassword`,description:`Change the password of the user`,responses:{200:{description:`Password successfully changed`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`New session token if other sessions were revoked`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}}}}}},async e=>{let{newPassword:t,currentPassword:n,revokeOtherSessions:r}=e.body,i=e.context.session;fQ(e,t),pQ(e,t),pQ(e,n);let a=await e.context.internalAdapter.findCredentialAccount(i.user.id);if(!a||!a.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);let o=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);let s=await wH(e.context.adapter,async()=>{if(r&&await e.context.internalAdapter.deleteUserSessions(i.user.id),await e.context.internalAdapter.updateAccount(a.id,{password:o}),!r)return null;let t=await e.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION);return t}),c=null;return s&&(await aq(e,{session:s,user:i.user}),c=s.token),e.json({token:c,user:eG(e.context.options,i.user)})}),Cpe=X.serverOnly({method:`POST`,body:A({newPassword:k().meta({description:`The new password to set is required`})}),use:[HJ]},async e=>{let{newPassword:t}=e.body,n=e.context.session;fQ(e,t),pQ(e,t);let r=await e.context.internalAdapter.findCredentialAccount(n.user.id),i=await e.context.password.hash(t);if(!r)return await e.context.internalAdapter.linkAccount({userId:n.user.id,providerId:`credential`,accountId:n.user.id,password:i}),e.json({status:!0});if(!r.password)return await e.context.internalAdapter.updateAccount(r.id,{password:i}),e.json({status:!0});throw E.from(`BAD_REQUEST`,Y.PASSWORD_ALREADY_SET)}),wpe=X(`/delete-user`,{method:`POST`,use:[HJ],body:A({callbackURL:k().meta({description:`The callback URL to redirect to after the user is deleted`}).optional(),password:k().meta({description:`The password of the user is required to delete the user`}).optional(),token:k().meta({description:`The token to delete the user is required`}).optional()}),metadata:{openapi:{operationId:`deleteUser`,description:`Delete the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{callbackURL:{type:`string`,description:`The callback URL to redirect to after the user is deleted`},password:{type:`string`,description:`The user's password. Required if session is not fresh`},token:{type:`string`,description:`The deletion verification token`}}}}}},responses:{200:{description:`User deletion processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the operation was successful`},message:{type:`string`,enum:[`User deleted`,`Verification email sent`],description:`Status message of the deletion process`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.fromStatus(`NOT_FOUND`);let t=e.context.session;if(e.body.password){pQ(e,e.body.password);let n=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!n||!n.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD)}if(e.body.token)return await gQ({...e,query:{token:e.body.token}}),e.json({success:!0,message:`User deleted`});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=JH(32,`0-9`,`a-z`);await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1e3)});let r=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:r,token:n},e.request)),e.json({success:!0,message:`Verification email sent`})}if(!e.body.password&&e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`BAD_REQUEST`,Y.SESSION_EXPIRED)}let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),lq(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:`User deleted`})}),gQ=X(`/delete-user/callback`,{method:`GET`,query:A({token:k().meta({description:`The token to verify the deletion request`}),callbackURL:k().meta({description:`The URL to redirect to after deletion`}).optional()}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Callback to complete user deletion with verification token`,responses:{200:{description:`User successfully deleted`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the deletion was successful`},message:{type:`string`,enum:[`User deleted`],description:`Confirmation message`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.from(`NOT_FOUND`,{message:`Not found`,code:`NOT_FOUND`});let t=await zJ(e,{disableCookieCache:RJ(e)});if(!t)throw E.from(`NOT_FOUND`,Y.FAILED_TO_GET_USER_INFO);let n=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!n||n.value!==t.user.id)throw E.from(`NOT_FOUND`,Y.INVALID_TOKEN);let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),lq(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||`/`);return e.json({success:!0,message:`User deleted`})}),Tpe=X(`/change-email`,{method:`POST`,body:A({newEmail:Re().meta({description:`The new email address to set must be a valid email address`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[HJ],metadata:{openapi:{operationId:`changeEmail`,responses:{200:{description:`Email change request processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the request was successful`},message:{type:`string`,enum:[`Email updated`,`Verification email sent`],description:`Status message of the email change process`,nullable:!0}},required:[`status`]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error(`Change email is disabled.`),E.from(`BAD_REQUEST`,Y.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn(`Email is the same`),E.fromStatus(`BAD_REQUEST`,{message:`Email is the same`});let n=e.context.session.user.emailVerified!==!0&&e.context.options.user.changeEmail.updateEmailWithoutVerification,r=e.context.options.emailVerification?.sendVerificationEmail,i=r&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});if(await e.context.internalAdapter.findUserByEmail(t))return await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info(`Change email attempt for existing email`),e.json({status:!0});if(n){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await aq(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),r){let n=await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:i,token:n},e.request))}return e.json({status:!0})}if(i){let n=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-confirmation`}),r=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:r,token:n},e.request)),e.json({status:!0})}if(!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});let a=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),_Q=sY((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),vQ=/* @__PURE__ */ new WeakMap;function yQ(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function bQ(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 xQ(e){let t=e[Ne],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function Epe(e,t,n,r){let i=oe(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=vQ.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=vQ.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[eY]:`before`,[ge]:c,[tY]:s,[$J]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Fq(t)&&me(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});bQ(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=_Q(t,a);continue}return u}}return{context:a}}async function Dpe(e,t,n,r){let i=oe(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=vQ.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[eY]:`after`,[ge]:o,[tY]:t,[$J]:r},()=>a.handler(e)).catch(t=>{if(Fq(t))return me(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:xQ(t)};throw t});bQ(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function Ope(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(vQ.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(vQ.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(vQ.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(vQ.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function SQ(e,t){let n=oe(t.context.options),r=t.operationId??yQ(e),i=e.path??`/:virtual`,a=e.options?.method,o=Array.isArray(a)?a[0]:a,s=t.method??t.request?.method??o??`?`,c=t.asResponse??HH(t.request),l={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return n(`${s} ${i}`,{[ge]:i,[$J]:r},async()=>mH(l,async()=>{let{beforeHooks:a,afterHooks:o}=Ope(l.context),s=await Epe(l,a,e,r);if(`context`in s&&s.context&&typeof s.context==`object`){let{headers:e,...t}=s.context;if(e){l.headers||(l.headers=new Headers);let t=l.headers;e.forEach((e,n)=>{t.set(n,e)})}l=_Q(t,l)}else if(s){let e=l.context.responseHeaders;return c?nK(s,{headers:e}):t.returnHeaders?{headers:e,response:s}:s}l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let u=await mH(l,()=>n(`handler ${i}`,{[ge]:i,[$J]:r},()=>e(l))).catch(e=>{if(Fq(e))return{response:e,status:e.statusCode,headers:xQ(e)};throw e});if(u instanceof Response)return u;l.context.returned=u.response,l.context.responseHeaders=u.headers??void 0;let d=await Dpe(l,o,e,r);if(d.response!==void 0&&(u.response=d.response),u.headers=d.headers??u.headers,Fq(u.response)&&me(l.context.logger.level,`debug`)&&(u.response.stack=u.response.errorStack),Fq(u.response)&&!c)throw u.headers&&Object.defineProperty(u.response,Ne,{enumerable:!1,configurable:!0,writable:!1,value:u.headers}),u.response;return c?nK(u.response,{headers:u.headers??void 0,status:u.status}):t.returnHeaders?t.returnStatus?{headers:u.headers,response:u.response,status:u.status}:{headers:u.headers,response:u.response}:t.returnStatus?{response:u.response,status:u.status}:u.response}))}async function kpe(e,t){if(e.baseURL)return e;let n=DY(t),r=e.options.baseURL,i=VH(r)&&!!r.fallback;if(n===void 0&&!i)throw new E(`INTERNAL_SERVER_ERROR`,{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await kY(e,n,OY(e.options))}catch(e){throw e instanceof D?new E(`INTERNAL_SERVER_ERROR`,{message:e.message}):e}}function Ape(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=async e=>{let n=yQ(i,r),a=async()=>{let r=await t,a=r.checkSchema?.();a&&await a;let o=VH(r.options.baseURL)?await kpe(r,e):r;return SQ(i,{...e,context:o,operationId:n,asResponse:e?.asResponse??HH(e?.request)})};return await gH()?a():vH(/* @__PURE__ */ new WeakMap,a)},n[r].path=i.path,n[r].options=i.options;return n}function jpe(e,t){let n=/* @__PURE__ */ new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,r]of Object.entries(e.endpoints))if(r&&`path`in r&&typeof r.path==`string`){let i=r.path,a=[];r.options&&`method`in r.options&&(Array.isArray(r.options.method)?a=r.options.method:typeof r.options.method==`string`&&(a=[r.options.method])),a.length===0&&(a=[`*`]),n.has(i)||n.set(i,[]),n.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let r=[];for(let[e,t]of n.entries())if(t.length>1){let n=/* @__PURE__ */ new Map,i=!1;for(let e of t)for(let r of e.methods)n.has(r)||n.set(r,[]),n.get(r).push(e.pluginId),n.get(r).length>1&&(i=!0),(r===`*`&&t.length>1||r!==`*`&&n.has(`*`))&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,r]of n.entries())(r.length>1||e===`*`&&t.length>1||e!==`*`&&n.has(`*`))&&a.push(e);r.push({path:e,plugins:i,conflictingMethods:a})}}if(r.length>0){let e=r.map(e=>` - "${e.path}" [${e.conflictingMethods.join(`, `)}] used by plugins: ${e.plugins.join(`, `)}`).join(`
|
|
408
|
-
`);t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
409
|
-
${e}
|
|
410
|
-
|
|
411
|
-
To resolve this, you can:
|
|
412
|
-
1. Use only one of the conflicting plugins
|
|
413
|
-
2. Configure the plugins to use different paths (if supported)
|
|
414
|
-
3. Ensure plugins use different HTTP methods for the same path
|
|
415
|
-
`)}}function CQ(e,t){let n=oe(t),r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},i=t.plugins?.map(t=>t.middlewares?.map(r=>{let i=(async i=>{let a=await e;return n(`middleware ${r.path} ${t.id}`,{"better_auth.hook.type":`middleware`,"http.route":r.path,"better_auth.context":`plugin:${t.id}`},()=>r.middleware({...i,context:{...a,...i.context}}))});return i.options=r.middleware.options,{path:r.path,middleware:i}})).filter(e=>e!==void 0).flat()||[];return{api:Ape({signInSocial:fpe(),callbackOAuth:$fe,getSession:LJ(),signOut:hpe,signUpEmail:_pe(),signInEmail:ppe(),resetPassword:lpe,verifyPassword:upe,verifyEmail:UY,sendVerificationEmail:HY,changeEmail:Tpe,changePassword:Spe,setPassword:Cpe,updateSession:ype(),updateUser:xpe(),deleteUser:wpe,requestPasswordReset:spe,requestPasswordResetCallback:cpe,listSessions:WJ(),revokeSession:GJ,revokeSessions:KJ,revokeOtherSessions:qJ,linkSocialAccount:Jfe,listUserAccounts:qfe,deleteUserCallback:gQ,unlinkAccount:Yfe,refreshToken:Zfe,getAccessToken:Xfe,accountInfo:Qfe,...r,ok:npe,error:tpe},e),middlewares:i}}const Mpe=(e,t)=>{let n=oe(t),{api:r,middlewares:i}=CQ(e,t),a=new URL(e.baseURL).pathname;return LK(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:eJ},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=vq(t.url,a);if(r.includes(i))return new Response(`Not Found`,{status:404});let o=e.checkSchema?.();o&&await o;let s=t,c=await PJ(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[eY]:`onRequest`,[tY]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(r&&`response`in r)return r.response;r&&`request`in r&&(s=r.request)}return s},async onResponse(t,r){for(let r of e.options.plugins||[])if(r.onResponse){let i=await n(`onResponse ${r.id}`,{[eY]:`onResponse`,[tY]:`plugin:${r.id}`,[ce]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},async onError(n){if(Fq(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){try{await t.onAPIError.onError(n,e)}catch(t){e.logger.error(`onAPIError.onError threw`,t)}return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?f:void 0;if(t.logger?.disabled!==!0){if(n&&typeof n==`object`&&`message`in n&&typeof n.message==`string`&&(n.message.includes(`no column`)||n.message.includes(`column`)||n.message.includes(`relation`)||n.message.includes(`table`)||n.message.includes(`does not exist`))){e.logger?.error(n.message);return}Fq(n)?(n.status===`INTERNAL_SERVER_ERROR`&&e.logger.error(n.status,n),i?.error(n.message)):e.logger?.error(n&&typeof n==`object`&&`name`in n?n.name:``,n)}}})};async function Npe(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=p(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./dist-Dse7wyrJ.mjs`);n=i(r)(e)}return n.transaction||(f.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function Ppe(e){return Npe(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./kysely-adapter-9GDHEHvl.mjs`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new D(`Failed to initialize database adapter`);return n(r,{type:i||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:a})(e)})}function Fpe(e){let{indexesByTable:t,tables:n}=re(e),r=/* @__PURE__ */ new Map,i={};for(let e in n){let t=n[e],a=t.fields,o={};Object.entries(a).forEach(([e,t])=>{let i=t.references,a=i?n[i.model]:void 0,s=i&&a?{...t,references:{...i,model:a.modelName}}:t;o[t.fieldName||e]=s,i&&r.set(s,{modelKey:i.model,fieldKey:i.field})}),i[t.modelName]?(i[t.modelName].fields={...i[t.modelName].fields,...o},t.disableMigrations&&(i[t.modelName].disableMigrations=!0)):i[t.modelName]={fields:o,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,n]of t)i[e]&&(i[e].indexes=n);return{schema:i,tables:n,referenceKeys:r}}const Ipe={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function wQ(e,t){return`${ie(e)}\u0000${ie(t)}`}function TQ(e,t){return`${e}\u0000${t}`}function EQ(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 DQ(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function OQ(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[wQ(e.table,e.name),{columns:t.flatMap(e=>e.name===null?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>e.name!==null&&e.fullLength)}]}))}async function Lpe(e,n,r,i){if(i)return OQ(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=wQ(t,n),a=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=a===void 0?DQ(e.isUnique??e.is_unique):!DQ(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=DQ(e.isPartial),d=!DQ(e.isDisabled)&&!DQ(e.isHypothetical)&&(e.isValid===void 0||DQ(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 OQ([...o.values()])}async function Rpe(e,n){let r;switch(n.type){case`postgres`:case`sqlite`:return/* @__PURE__ */ new Map;case`mysql`:r=(await t`
|
|
488
|
-
SELECT
|
|
489
|
-
table_name AS tableName,
|
|
490
|
-
column_name AS columnName,
|
|
491
|
-
character_octet_length AS maxIndexBytes
|
|
492
|
-
FROM information_schema.columns
|
|
493
|
-
WHERE table_schema = DATABASE()
|
|
494
|
-
`.execute(e)).rows;break;case`mssql`:r=(await t`
|
|
495
|
-
SELECT
|
|
496
|
-
tables.name AS "tableName",
|
|
497
|
-
columns.name AS "columnName",
|
|
498
|
-
columns.max_length AS "maxIndexBytes"
|
|
499
|
-
FROM sys.columns AS columns
|
|
500
|
-
INNER JOIN sys.tables AS tables
|
|
501
|
-
ON tables.object_id = columns.object_id
|
|
502
|
-
INNER JOIN sys.schemas AS table_schemas
|
|
503
|
-
ON table_schemas.schema_id = tables.schema_id
|
|
504
|
-
WHERE table_schemas.name = ${n.schema}
|
|
505
|
-
`.execute(e)).rows}let i=/* @__PURE__ */ new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,n=e.columnName??e.COLUMN_NAME;if(!t||!n)continue;let r=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(TQ(t,n),{maxIndexBytes:r<0?null:r})}return i}function zpe({columnBounds:e,dbType:t,existingColumns:n,fields:r,indexes:i,index:a,table:o}){let s=t===`mysql`?3072:1700,c=0;for(let s of a.columns){let l=r[s];if(l){if(l.type===`string`||Array.isArray(l.type)){if(!n.has(s)){let e=T({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let l=e.get(TQ(o,s));if(!l?.maxIndexBytes)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because column "${s}" is not bounded for ${t===`mysql`?`MySQL`:`SQL Server`}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);c+=l.maxIndexBytes}else c+=16}}if(c>s)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because its columns can exceed ${t===`mysql`?`MySQL`:`SQL Server`}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}var Bpe=class extends D{};function Vpe(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function Hpe(e){return!(e.unique&&e.required===!1)&&(e.type===`string`||e.type===`number`||e.type===`boolean`)&&e.defaultValue!==void 0&&e.defaultValue!==null&&typeof e.defaultValue!=`function`}async function Upe(e,n,r){let i=e.selectFrom(r).select(t`1`.as(`present`));return(await(n===`mssql`?i.top(1):i.limit(1)).execute()).length>0}function Wpe(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=Ipe[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function kQ(e,{throwOnUnsafe:n=!0}={}){let{schema:r,tables:i,referenceKeys:o}=Fpe(e),d=he(e.logger),f=[],p=e=>{if(n)throw new Bpe(e);f.push(e)},{kysely:m,databaseType:h,introspectIndexes:g,schemaName:_}=await u(e);h||=(d.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),m||(d.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let v=await m.introspection.getTables(),b,x=v;switch(h){case`postgres`:{let e=_??await a(m);b={type:`postgres`,schema:e},d.debug(`PostgreSQL migration: Using schema '${e}' (${_?`from database.schemaName`:`from search_path`})`);try{(await m.introspection.getSchemas()).some(({name:t})=>t===e)||(_?d.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):d.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){d.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}x=v.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),d.debug(`Found ${x.length} table(s) in schema '${e}': ${x.map(e=>e.name).join(`, `)||`(none)`}`);break}case`mssql`:{let e=await c(m);b={type:`mssql`,schema:e},d.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),x=v.filter(t=>t.schema===e);break}case`mysql`:b={type:`mysql`};break;case`sqlite`:b={type:`sqlite`}}let S=await Lpe(m,b,v.map(e=>e.name),g),ee=await Rpe(m,b),C=ree(l(m,r),s(x)).filter(e=>e.kind===`unexpected-required-column`).map(e=>iee(e,`database`)),te=[],ne=[],w=[],re=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(r)){if(t.disableMigrations)continue;let n=x.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=wQ(e,i),o=S.get(a);if(o){if(!EQ(o,r))throw new D(`Database index "${i}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if(h===`sqlite`||h===`postgres`){let t=[...S.values()].find(t=>ie(t.name)===ie(i)&&ie(t.table)!==ie(e));if(t)throw new D(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=re.get(a);if(s){if(!EQ({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new D(`Database index name "${i}" identifies more than one index on table "${e}".`)}else n&&(h===`mysql`||h===`mssql`)&&zpe({columnBounds:ee,dbType:h,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),re.set(a,r),w.push({table:e,index:r,name:i})}if(!n){let n=te.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=te.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?te.push(r):te[n].fields={...te[n].fields,...t.fields}:te.splice(i,0,r);continue}let r={};for(let[i,a]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===i);t?(a.required!==!1&&t.isNullable&&d.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!Wpe(t.dataType,a.type,h)&&d.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${a.type} but got ${t.dataType}.`)):r[i]=a}Object.keys(r).length>0&&ne.push({table:e,fields:r,order:t.order||1/0})}let ae=[];_&&te.length>0&&ae.push(m.schema.createSchema(_).ifNotExists());let oe=e.advanced?.database?.generateId===`uuid`,se=e.advanced?.database?.generateId===`serial`;function ce(e,n,r){let i=e.type,a=h||`sqlite`,o={string:{sqlite:`text`,postgres:`text`,mysql:r?`varchar(${r})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:r?`varchar(${r})`:e.unique||e.sortable?`varchar(255)`:e.references?`varchar(36)`:`varchar(8000)`},boolean:{sqlite:`integer`,postgres:`boolean`,mysql:`boolean`,mssql:`smallint`},number:{sqlite:e.bigint?`bigint`:`integer`,postgres:e.bigint?`bigint`:`integer`,mysql:e.bigint?`bigint`:`integer`,mssql:e.bigint?`bigint`:`integer`},date:{sqlite:`date`,postgres:`timestamptz`,mysql:`timestamp(3)`,mssql:t`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:se?t`integer GENERATED BY DEFAULT AS IDENTITY`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},foreignKeyId:{postgres:se?`integer`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(n===`id`||e.references?.field===`id`)return n===`id`?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return`text`;if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${n}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let le=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 T({columnName:t,dialect:h,fields:n.fields,indexes:n.indexes??[]})};if(ne.length){let e=/* @__PURE__ */ new Map;for(let n of ne)for(let[r,i]of Object.entries(n.fields)){let a=Vpe(i,h),o=Hpe(i);if(i.required!==!1&&!a&&!o){let t=e.get(n.table);if(t===void 0&&(t=await Upe(m,h,n.table),e.set(n.table,t)),t){let e=i.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``;p(`Cannot add required column "${r}" to populated table "${n.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let s=ce(i,r,pe(n.table,r)),c=m.schema.alterTable(n.table);if(i.index||i.unique){let e=y(n.table,r,i.unique??!1),t=m.schema.createIndex(e).on(n.table).columns([r]);i.unique&&(t=t.unique(),i.required===!1&&h===`mssql`&&(t=t.where(r,`is not`,null)),i.required!==!1&&i.defaultValue!==void 0&&i.defaultValue!==null&&typeof i.defaultValue!=`function`&&d.warn(`Adding unique column "${r}" to existing table "${n.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),fe.push(t)}let l=c.addColumn(r,s,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),a?e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo(typeof i.defaultValue==`boolean`&&(h===`sqlite`||h===`mssql`)?+!!i.defaultValue:i.defaultValue)),e));ae.push(l)}}if(te.length)for(let e of te){let n=ce({type:se?`number`:`string`},`id`),r=m.schema.createTable(e.table).addColumn(`id`,n,e=>se?h===`postgres`||h===`sqlite`?e.primaryKey().notNull():h===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():oe&&h===`postgres`?e.primaryKey().defaultTo(t`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[n,i]of Object.entries(e.fields)){let a=ce(i,n,pe(e.table,n));if(r=r.addColumn(n,a,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),i.unique&&(e=e.unique()),i.type===`date`&&typeof i.defaultValue==`function`&&(h===`postgres`||h===`mysql`||h===`mssql`)&&(e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let t=m.schema.createIndex(y(e.table,n,!1)).on(e.table).columns([n]);fe.push(t)}}ae.push(r)}for(let{table:e,index:t,name:n}of w){let r=m.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),fe.push(r)}for(let e of fe)ae.push(e);async function me(){try{for(let e of ae)await e.execute()}finally{ae.length&&e.database&&oee(e.database)}}async function ge(){return ae.map(e=>e.compile().sql).join(`;
|
|
506
|
-
|
|
507
|
-
`)+`;`}return{toBeCreated:te,toBeAdded:ne,toBeAddedIndexes:w,unsafeChanges:f,schemaProblems:C,runMigrations:me,compileMigrations:ge}}function Gpe(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function Kpe(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new D(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let n=parseInt(e.slice(0,t),10);if(!Number.isInteger(n)||n<0)throw new D(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let r=e.slice(t+1).trim();if(!r)throw new D(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function qpe(e,t){if(e.length===0)throw new D("`secrets` array must contain at least one entry.");let n=/* @__PURE__ */ new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new D(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new D(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new D(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);n.add(e)}let r=e[0];r.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${r.version}) should be at least 32 characters long for adequate security.`),Gpe(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function Jpe(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(parseInt(String(t.version),10),t.value);return{keys:n,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&t!==`better-auth-secret-12345678901234567890`?t:void 0}}async function Ype(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let n=e.socialProviders?.[t];if(!n)return{};let r=typeof n==`function`?await n():n;return{id:t,mapProfileToUser:!!r.mapProfileToUser,disableDefaultScope:!!r.disableDefaultScope,disableIdTokenSignIn:!!r.disableIdTokenSignIn,disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,getUserInfo:!!r.getUserInfo,overrideUserInfoOnSignIn:!!r.overrideUserInfoOnSignIn,prompt:r.prompt,verifyIdToken:!!r.verifyIdToken,scope:r.scope,refreshAccessToken:!!r.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}function Xpe(){let e=C.npm_config_user_agent;if(!e)return;let t=e.split(` `)[0],n=t.lastIndexOf(`/`),r=t.substring(0,n);return{name:r===`npminstall`?`cnpm`:r,version:t.substring(n+1)}}function Zpe(){return C.CI!==`false`&&(`BUILD_ID`in C||`BUILD_NUMBER`in C||`CI`in C||`CI_APP_ID`in C||`CI_BUILD_ID`in C||`CI_BUILD_NUMBER`in C||`CI_NAME`in C||`CONTINUOUS_INTEGRATION`in C||`RUN_ID`in C)}function Qpe(){return typeof Deno<`u`?{name:`deno`,version:Deno?.version?.deno??null}:typeof Bun<`u`?{name:`bun`,version:Bun?.version??null}:typeof process<`u`&&process?.versions?.node?{name:`node`,version:process.versions.node??null}:{name:`edge`,version:null}}function $pe(){return b(`NODE_ENV`)===`production`?`production`:Zpe()?`ci`:Ee()?`test`:`development`}async function AQ(e){let t=await MU(`SHA-256`).digest(e);return ue.encode(t)}const eme=e=>h(`a-z`,`A-Z`,`0-9`)(e||32);let jQ;async function MQ(){if(jQ)return jQ;try{let e=process.cwd();if(!e)return;let t=await Dt.readFile(ct.join(e,`package.json`),`utf-8`);return jQ=JSON.parse(t),jQ}catch{}}async function NQ(e){if(jQ)return jQ.dependencies?.[e]||jQ.devDependencies?.[e]||jQ.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=ct.join(t,`node_modules`,e,`package.json`),r=await Dt.readFile(n,`utf-8`);return JSON.parse(r).version||await PQ(e)||void 0}catch{}return PQ(e)}async function PQ(e){let t=await MQ();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function tme(){return(await MQ())?.name}async function nme(){try{let e=mt.cpus();return{deploymentVendor:rme(),systemPlatform:mt.platform(),systemRelease:mt.release(),systemArchitecture:mt.arch(),cpuCount:e.length,cpuModel:e.length?e[0].model:null,cpuSpeed:e.length?e[0].speed:null,memory:mt.totalmem(),isWSL:await cme(),isDocker:await IQ(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}function rme(){let e=process.env,t=(...t)=>t.some(t=>!!e[t]);return t(`CF_PAGES`,`CF_PAGES_URL`,`CF_ACCOUNT_ID`)||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`?`cloudflare`:t(`VERCEL`,`VERCEL_URL`,`VERCEL_ENV`)?`vercel`:t(`NETLIFY`,`NETLIFY_URL`)?`netlify`:t(`RENDER`,`RENDER_URL`,`RENDER_INTERNAL_HOSTNAME`,`RENDER_SERVICE_ID`)?`render`:t(`AWS_LAMBDA_FUNCTION_NAME`,`AWS_EXECUTION_ENV`,`LAMBDA_TASK_ROOT`)?`aws`:t(`GOOGLE_CLOUD_FUNCTION_NAME`,`GOOGLE_CLOUD_PROJECT`,`GCP_PROJECT`,`K_SERVICE`)?`gcp`:t(`AZURE_FUNCTION_NAME`,`FUNCTIONS_WORKER_RUNTIME`,`WEBSITE_INSTANCE_ID`,`WEBSITE_SITE_NAME`)?`azure`:t(`DENO_DEPLOYMENT_ID`,`DENO_REGION`)?`deno-deploy`:t(`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`)?`fly-io`:t(`RAILWAY_STATIC_URL`,`RAILWAY_ENVIRONMENT_NAME`)?`railway`:t(`DYNO`,`HEROKU_APP_NAME`)?`heroku`:t(`DO_DEPLOYMENT_ID`,`DO_APP_NAME`,`DIGITALOCEAN`)?`digitalocean`:t(`KOYEB`,`KOYEB_DEPLOYMENT_ID`,`KOYEB_APP_NAME`)?`koyeb`:null}let FQ;async function ime(){try{return wt.statSync(`/.dockerenv`),!0}catch{return!1}}async function ame(){try{return wt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function IQ(){return FQ===void 0&&(FQ=await ime()||await ame()),FQ}let LQ;const ome=async()=>{try{return wt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function sme(){return LQ===void 0&&(LQ=await ome()||await IQ()),LQ}async function cme(){try{return process.platform===`linux`&&(mt.release().toLowerCase().includes(`microsoft`)||wt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await sme():!1}catch{return!1}}let RQ=null;async function zQ(e){if(RQ)return RQ;let t=await tme();return t?(RQ=await AQ(e?e+t:t),RQ):e?(RQ=await AQ(e),RQ):(RQ=eme(32),RQ)}async function lme(){for(let[e,t]of Object.entries({pg:`postgresql`,mysql:`mysql`,mariadb:`mariadb`,sqlite3:`sqlite`,"better-sqlite3":`sqlite`,"@prisma/client":`prisma`,mongoose:`mongodb`,mongodb:`mongodb`,"drizzle-orm":`drizzle`})){let n=await NQ(e);if(n)return{name:t,version:n}}}async function ume(){for(let[e,t]of Object.entries({next:`next`,nuxt:`nuxt`,"react-router":`react-router`,astro:`astro`,"@sveltejs/kit":`sveltekit`,"solid-start":`solid-start`,"tanstack-start":`tanstack-start`,hono:`hono`,express:`express`,elysia:`elysia`,expo:`expo`})){let n=await NQ(e);if(n)return{name:t,version:n}}}const dme=async function(){};async function fme(e,t){let n=e.telemetry?.debug||_(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=ee.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:dme};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(f.error):r&&(n?f.info(`telemetry event`,JSON.stringify(e,null,2)):await BX(r,{method:`POST`,body:e}).catch(f.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(_(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!Ee())})(),o;return a&&(o=await zQ(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await Ype(e,t),runtime:Qpe(),database:await lme(),framework:await ume(),environment:$pe(),systemInfo:await nme(),packageManager:Xpe()},anonymousId:o})),{publish:async t=>{a&&(o||=await zQ(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function pme(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function mme(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!Ee()){if(n&&te)throw new D("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!e)throw new D("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");e.length<32&&t.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),pme(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function hme(e,t,n){let r=HW(t);r||(t=cY(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=cY(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=TY(t),o=he(t.logger),s=VH(t.baseURL);if(VH(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new D(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:LH(typeof t.baseURL==`string`?t.baseURL:void 0,t.basePath);!c&&!s&&o.warn(`[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly.`),e.id===`memory`&&t.advanced?.database?.generateId===!1&&o.error(`[better-auth] Misconfiguration detected.
|
|
508
|
-
You are using the memory DB with generateId: false.
|
|
509
|
-
This will cause no id to be generated for any model.
|
|
510
|
-
Most of the features of Better Auth will not work correctly.`);let l=t.secrets??Kpe(C.BETTER_AUTH_SECRETS),u=t.secret||C.BETTER_AUTH_SECRET||C.AUTH_SECRET||``,d,f;l?(qpe(l,o),d=l[0].value,f=Jpe(l,u)):(d=u||`better-auth-secret-12345678901234567890`,mme(d,o),f=d),t={...t,secret:d,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},jpe(t,o);let m=t.advanced?.ipAddress?.trustedProxies;if(m&&m.length>0){let e=vJ(m);e.length>0&&o.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(`, `)}. Each entry must be an IP address or CIDR range.`)}let h=nq(t),g=p(t),_=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let n=typeof t==`function`?await t():t;if(n==null||n.enabled===!1)return null;n.clientId||o.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=nQ[e](n);return r.disableImplicitSignUp=n.disableImplicitSignUp,r}))).filter(e=>e!==null),v=({model:e,size:n})=>{if(typeof t.advanced?.generateId==`function`)return t.advanced.generateId({model:e,size:n});let r=t?.advanced?.database?.generateId;return typeof r==`function`?r({model:e,size:n}):r===`uuid`?crypto.randomUUID():r===`serial`||r===!1?!1:pe(n)},{publish:y}=await fme(t,{adapter:e.id,database:typeof t.database==`function`?`adapter`:n(t.database)}),b=new Set(t.plugins.map(e=>e.id)),x=e=>t.plugins.find(t=>t.id===e)??null,S=e=>b.has(e),ee=await EY(t),ne=await jY(t),w={appName:t.appName||`Better Auth`,baseURL:c||``,version:be(),socialProviders:_,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:g,trustedOrigins:ee,trustedProviders:ne,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>Yq(e,n,t))},sessionConfig:{updateAge:t.session?.updateAge===void 0?86400:t.session.updateAge,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(()=>{let e=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300;return r&&e?(o.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):e===!1||e===void 0?!1:e===!0?{enabled:!0,updateAge:Math.floor(n*.2)}:{enabled:!0,updateAge:e.updateAge===void 0?Math.floor(n*.2):e.updateAge}})()},secret:d,secretConfig:f,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??te,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?`secondary-storage`:`memory`)},authCookies:h,logger:o,generateId:v,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||kU,verify:t.emailAndPassword?.password?.verify||AU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:ape},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:iY(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:v}),createAuthCookie:tq(t),async runMigrations(){throw new D(`runMigrations will be set by the specific init implementation`)},publishTelemetry:y,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!Ee():t.advanced.disableOriginCheck,runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{o.error(`Failed to run background task:`,e)})):await e}catch(e){o.error(`Failed to run background task:`,e)}},getPlugin:x,hasPlugin:S},T=wY(w);return dG(T)&&await T,w.checkSchema=rt(w.adapter),w.explicitSchemaCheck=aee(w.adapter),w}const gme=async e=>{let t=await hme(await Ppe(e),e,e=>o(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new D(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await kQ(e);await t()},t},_me=(e,t)=>{let n=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;if(!e.checkSchema&&t!==!1){let n=t===!0?`warn`:`debug`;e.logger[n](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`)}let n=e.checkSchema?.();return n&&n.catch(t=>{e.logger.error(t instanceof see?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=CQ(n,e),i=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),a=async t=>{let r=await n,i=r.options.basePath||`/api/auth`,a;if(VH(e.baseURL))a=await kY(r,t,OY(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=LH(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new D(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:RH(n)||void 0},e=a.options}a.trustedOrigins=await EY(e,t),a.trustedProviders=await jY(e,t)}let{handler:o}=Mpe(a,e);return CH(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...Y}}},vme=e=>_me(e,gme),BQ=bH({INVALID_METADATA_TYPE:`metadata must be an object or undefined`,REFILL_AMOUNT_AND_INTERVAL_REQUIRED:`refillAmount is required when refillInterval is provided`,REFILL_INTERVAL_AND_AMOUNT_REQUIRED:`refillInterval is required when refillAmount is provided`,USER_BANNED:`User is banned`,UNAUTHORIZED_SESSION:`Unauthorized or invalid session`,KEY_NOT_FOUND:`API Key not found`,KEY_DISABLED:`API Key is disabled`,KEY_EXPIRED:`API Key has expired`,USAGE_EXCEEDED:`API Key has reached its usage limit`,KEY_NOT_RECOVERABLE:`API Key is not recoverable`,EXPIRES_IN_IS_TOO_SMALL:`The expiresIn is smaller than the predefined minimum value.`,EXPIRES_IN_IS_TOO_LARGE:`The expiresIn is larger than the predefined maximum value.`,INVALID_REMAINING:`The remaining count is either too large or too small.`,INVALID_PREFIX_LENGTH:`The prefix length is either too large or too small.`,INVALID_NAME_LENGTH:`The name length is either too large or too small.`,METADATA_DISABLED:`Metadata is disabled.`,RATE_LIMIT_EXCEEDED:`Rate limit exceeded.`,NO_VALUES_TO_UPDATE:`No values to update.`,KEY_DISABLED_EXPIRATION:`Custom key expiration values are disabled.`,INVALID_API_KEY:`Invalid API key.`,INVALID_USER_ID_FROM_API_KEY:`The user id from the API key is invalid.`,INVALID_REFERENCE_ID_FROM_API_KEY:`The reference id from the API key is invalid.`,INVALID_API_KEY_GETTER_RETURN_TYPE:`API Key getter returned an invalid key type. Expected string.`,SERVER_ONLY_PROPERTY:`The property you're trying to set can only be set from the server auth instance only.`,FAILED_TO_UPDATE_API_KEY:`Failed to update API key`,NAME_REQUIRED:`API Key name is required.`,ORGANIZATION_ID_REQUIRED:`Organization ID is required for organization-owned API keys.`,USER_NOT_MEMBER_OF_ORGANIZATION:`You are not a member of the organization that owns this API key.`,INSUFFICIENT_API_KEY_PERMISSIONS:`You do not have permission to perform this action on organization API keys.`,NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:`No default api-key configuration found.`,ORGANIZATION_PLUGIN_REQUIRED:`Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin.`});async function VQ(e,t,n){let r=e.length;if(r===0)return[];let{signal:i}=n;if(i?.aborted)throw i.reason;let a=Math.floor(n.concurrency),o=Math.min(r,a>=1?a:1),s=Array(r),c=0,l=!1;return await Promise.all(Array.from({length:o},async()=>{for(;!l&&c<r;){if(i?.aborted)throw i.reason;let n=c++;try{s[n]=await t(e[n],n)}catch(e){throw l=!0,e}}})),s}const yme={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},bme=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,HQ={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},xme=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Sme(e){return e instanceof Date&&!isNaN(e.getTime())}function Cme(e){let t=xme.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return Sme(f)?f:null}function wme(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in HQ)return HQ[s];if(!bme.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(yme).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t)r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);else{if(a&&typeof t==`string`){let e=Cme(t);if(e)return e}return i?i(e,t):t}})}catch(t){if(n)throw t;return e}}function Tme(e,t={strict:!0}){return wme(e,t)}function UQ(e){return e==null?null:typeof e==`object`?e:le(e)}function WQ(e){return e!=null&&typeof e==`string`}async function Eme(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>WQ(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=UQ(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 GQ(e,t,n){let r=UQ(t.metadata);if(WQ(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 KQ(e){return`api-key:${e}`}function qQ(e){return`api-key:by-id:${e}`}function JQ(e){return`api-key:by-ref:${e}`}function Dme(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),expiresAt:e.expiresAt?.toISOString()??null,lastRefillAt:e.lastRefillAt?.toISOString()??null,lastRequest:e.lastRequest?.toISOString()??null})}function YQ(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 XQ(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function ZQ(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 QQ(e,t,n){let r=KQ(t);return YQ(await n.get(r))}async function $Q(e,t,n){let r=qQ(t);return YQ(await n.get(r))}const e$=/* @__PURE__ */ new Map;function Ome(e,t){let n=(e$.get(e)??Promise.resolve()).then(t,t).finally(()=>{e$.get(e)===n&&e$.delete(e)});return e$.set(e,n),n}async function t$(e,t,n){await Ome(t,async()=>{let r=await e.get(t),i=[];if(r&&typeof r==`string`)try{i=JSON.parse(r)}catch{i=[]}else Array.isArray(r)&&(i=r);let a=n(i);a.length===0?await e.delete(t):await e.set(t,JSON.stringify(a))})}async function n$(e,t,n,r,i){let a=Dme(t),o=JQ(t.referenceId);i.fallbackToDatabase?await Promise.all([n.set(KQ(t.key),a,r),n.set(qQ(t.id),a,r),n.delete(o)]):(await Promise.all([n.set(KQ(t.key),a,r),n.set(qQ(t.id),a,r)]),await t$(n,o,e=>e.includes(t.id)?e:[...e,t.id]))}async function kme(e,t,n,r){let i=JQ(t.referenceId);r.fallbackToDatabase?await Promise.all([n.delete(KQ(t.key)),n.delete(qQ(t.id)),n.delete(i)]):await Promise.all([n.delete(KQ(t.key)),n.delete(qQ(t.id)),t$(n,i,e=>e.filter(e=>e!==t.id))])}async function r$(e,t,n){let r=XQ(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 QQ(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 n$(e,i,r,ZQ(i),n),i}return n.storage===`secondary-storage`?r?await QQ(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function i$(e,t,n){let r=XQ(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 $Q(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 n$(e,i,r,ZQ(i),n),i}return n.storage===`secondary-storage`?r?await $Q(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function a$(e,t,n){let r=XQ(e,n),i=ZQ(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await n$(e,t,r,i,n)}}async function o$(e,t,n){let r=XQ(e,n);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await kme(e,t,r,n)}}function s$(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 c$(e,t,n,r){let i=XQ(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=JQ(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 VQ(n,t=>$Q(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s$(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 VQ(l,t=>n$(e,t,i,ZQ(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=JQ(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 VQ(l,t=>$Q(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s$(u,s,c,a,o),total:u.length}}let[l,u]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);return{apiKeys:l,total:u}}function Ame(e){let t=e.context;if(`orgOptions`in t&&t.orgOptions)return t.orgOptions;let n=t.getPlugin?.(`organization`);return n&&`options`in n?n.options:null}async function l$(e,t,n,r){let i=Ame(e);if(!i){let e=BQ.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=BQ.USER_NOT_MEMBER_OF_ORGANIZATION;throw E.from(`FORBIDDEN`,e)}if(!await jme(e,a.role,n,r,i)){let e=BQ.INSUFFICIENT_API_KEY_PERMISSIONS;throw E.from(`FORBIDDEN`,e)}return a}async function jme(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-FxrB4RLj.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const u$=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Mme(e){return e instanceof E||e instanceof E||e?.name===`APIError`}const Nme=A({configId:k().meta({description:`The configuration ID to use for the API key. If not provided, the default configuration will be used.`}).optional(),name:k().meta({description:`Name of the Api Key`}).optional(),expiresIn:Fe().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:Fe().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:Ze().optional(),refillAmount:Fe().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:Fe().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:Fe().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:Fe().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:Ge().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:Ie(k(),Le(k())).meta({description:`Permissions of the Api Key.`}).optional(),userId:GW().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:GW().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function Pme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return X(`/api-key/create`,{method:`POST`,body:Nme,metadata:{openapi:{description:`Create a new API key for a user`,responses:{200:{description:`API key created successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`Unique identifier of the API key`},createdAt:{type:`string`,format:`date-time`,description:`Creation timestamp`},updatedAt:{type:`string`,format:`date-time`,description:`Last update timestamp`},name:{type:`string`,nullable:!0,description:`Name of the API key`},prefix:{type:`string`,nullable:!0,description:`Prefix of the API key`},start:{type:`string`,nullable:!0,description:`Starting characters of the key (if configured)`},key:{type:`string`,description:`The full API key (only returned on creation)`},enabled:{type:`boolean`,description:`Whether the key is enabled`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiration timestamp`},referenceId:{type:`string`,description:`ID of the reference owning the key`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`Last refill timestamp`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`Last request timestamp`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Metadata associated with the key`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum requests in time window`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`Rate limit time window in milliseconds`},remaining:{type:`number`,nullable:!0,description:`Remaining requests`},refillAmount:{type:`number`,nullable:!0,description:`Amount to refill`},refillInterval:{type:`number`,nullable:!0,description:`Refill interval in milliseconds`},rateLimitEnabled:{type:`boolean`,description:`Whether rate limiting is enabled`},requestCount:{type:`number`,description:`Current request count in window`},permissions:{type:`object`,nullable:!0,additionalProperties:{type:`array`,items:{type:`string`}},description:`Permissions associated with the key`}},required:[`id`,`createdAt`,`updatedAt`,`key`,`enabled`,`referenceId`,`rateLimitEnabled`,`requestCount`]}}}}}}}},async n=>{let{configId:i,name:a,expiresIn:o,prefix:s,remaining:c,metadata:l,refillAmount:u,refillInterval:d,permissions:f,rateLimitMax:p,rateLimitTimeWindow:m,rateLimitEnabled:h}=n.body,g=m$(n.context,t,i),_=g.customKeyGenerator||e,v=await zJ(n,{disableCookieCache:!0}),y=n.request||n.headers;if(y&&(u!==void 0||d!==void 0||p!==void 0||m!==void 0||h!==void 0||f!==void 0||c!==null))throw E.from(`BAD_REQUEST`,BQ.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw E.from(`UNAUTHORIZED`,BQ.UNAUTHORIZED_SESSION);let b=g.references??`user`,x;if(b===`organization`){let e=n.body.organizationId;if(!e){let e=BQ.ORGANIZATION_ID_REQUIRED;throw E.from(`BAD_REQUEST`,e)}let t=v?.user.id||n.body.userId;if(!t)throw E.from(`UNAUTHORIZED`,BQ.UNAUTHORIZED_SESSION);await l$(n,t,e,`create`),x=e}else if(y){if(!v?.user.id){let e=BQ.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=BQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=t||e}if(l){if(g.enableMetadata===!1)throw E.from(`BAD_REQUEST`,BQ.METADATA_DISABLED);if(typeof l!=`object`)throw E.from(`BAD_REQUEST`,BQ.INVALID_METADATA_TYPE)}if(u&&!d){let e=BQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(d&&!u){let e=BQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(o){if(g.keyExpiration.disableCustomExpiresTime===!0){let e=BQ.KEY_DISABLED_EXPIRATION;throw E.from(`BAD_REQUEST`,e)}let e=o/86400;if(g.keyExpiration.minExpiresIn>e){let e=BQ.EXPIRES_IN_IS_TOO_SMALL;throw E.from(`BAD_REQUEST`,e)}if(g.keyExpiration.maxExpiresIn<e){let e=BQ.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`,BQ.INVALID_PREFIX_LENGTH);if(a){if(a.length<g.minimumNameLength||a.length>g.maximumNameLength)throw E.from(`BAD_REQUEST`,BQ.INVALID_NAME_LENGTH)}else if(g.requireName)throw E.from(`BAD_REQUEST`,BQ.NAME_REQUIRED);r(n.context);let S=await _({length:g.defaultKeyLength,prefix:s||g.defaultPrefix}),ee=g.disableKeyHashing?S:await y$(S),C=null;g.startingCharactersConfig.shouldStore&&(C=S.substring(0,g.startingCharactersConfig.charactersLength));let te=g.permissions?.defaultPermissions?typeof g.permissions.defaultPermissions==`function`?await g.permissions.defaultPermissions(x,n):g.permissions.defaultPermissions:void 0,ne=f?JSON.stringify(f):te?JSON.stringify(te):void 0,w={configId:g.configId??`default`,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,name:a??null,prefix:s??g.defaultPrefix??null,start:C,key:ee,enabled:!0,expiresAt:o?u$(o,`sec`):g.keyExpiration.defaultExpiresIn?u$(g.keyExpiration.defaultExpiresIn,`sec`):null,referenceId:x,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:p??g.rateLimit.maxRequests??null,rateLimitTimeWindow:m??g.rateLimit.timeWindow??null,remaining:c===null?c:c??u??null,refillAmount:u??null,refillInterval:d??null,rateLimitEnabled:h===void 0?g.rateLimit.enabled??!0:h,requestCount:0,permissions:ne};l&&(w.metadata=l);let T;if(g.storage===`secondary-storage`&&g.fallbackToDatabase)T=await n.context.adapter.create({model:b$,data:w}),await a$(n,T,g);else if(g.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||pe();T={...w,id:e},await a$(n,T,g)}else T=await n.context.adapter.create({model:b$,data:w});return n.json({...T,key:S,metadata:l??null,permissions:T.permissions?le(T.permissions):null})})}function Fme({deleteAllExpiredApiKeys:e}){return X.serverOnly({method:`POST`},async t=>{try{await e(t.context,!0)}catch(e){return t.context.logger.error(`[API KEY PLUGIN] Failed to delete expired API keys:`,e),t.json({success:!1,error:e})}return t.json({success:!0,error:null})})}const Ime=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`})});function Lme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/delete`,{method:`POST`,body:Ime,use:[VJ],metadata:{openapi:{description:`Delete an existing API key`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{keyId:{type:`string`,description:`The id of the API key to delete`}},required:[`keyId`]}}}},responses:{200:{description:`API key deleted successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the API key was successfully deleted`}},required:[`success`]}}}}}}}},async t=>{let{configId:r,keyId:i}=t.body,a=t.context.session;if(a.user.banned===!0)throw E.from(`UNAUTHORIZED`,BQ.USER_BANNED);let o=m$(t.context,e,r),s=null;if(s=await i$(t,i,o),!s||!g$(s.configId,o.configId))throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);let c=m$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await l$(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);try{c.storage===`secondary-storage`&&c.fallbackToDatabase?(await o$(t,s,c),await t.context.adapter.delete({model:b$,where:[{field:`id`,value:s.id}]})):c.storage===`database`?await t.context.adapter.delete({model:b$,where:[{field:`id`,value:s.id}]}):await o$(t,s,c)}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const Rme=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),id:k().meta({description:`The id of the Api Key`})});function zme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/get`,{method:`GET`,query:Rme,use:[VJ],metadata:{openapi:{description:`Retrieve an existing API key by ID`,responses:{200:{description:`API key retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,id:i}=t.query,a=t.context.session,o=m$(t.context,e,r),s=null;if(s=await i$(t,i,o),!s||!g$(s.configId,o.configId))throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);let c=m$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await l$(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);n(t.context);let l=await GQ(t,s,c),{key:u,...d}=s;return t.json({...d,metadata:l,permissions:d.permissions?le(d.permissions):null})})}function Bme(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const Vme=A({configId:k().meta({description:`Filter by configuration ID. If not provided, returns keys from all configurations.`}).optional(),organizationId:k().meta({description:`Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys.`}).optional(),limit:KW().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:KW().int().nonnegative().meta({description:`The offset to start from`}).optional(),sortBy:k().meta({description:`The field to sort by (e.g., createdAt, name, expiresAt)`}).optional(),sortDirection:Je([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function Hme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/list`,{method:`GET`,use:[VJ],query:Vme,metadata:{openapi:{description:`List all API keys for the authenticated user or for a specific organization`,responses:{200:{description:`API keys retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{apiKeys:{type:`array`,items:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}},total:{type:`number`,description:`Total number of API keys`},limit:{type:`number`,nullable:!0,description:`The limit used for pagination`},offset:{type:`number`,nullable:!0,description:`The offset used for pagination`}},required:[`apiKeys`,`total`]}}}}}}}},async t=>{let r=t.context.session,i=t.query?.configId,a=t.query?.organizationId,o=t.query?.limit==null?void 0:Number(t.query.limit),s=t.query?.offset==null?void 0:Number(t.query.offset);a&&await l$(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await c$(t,c,m$(t.context,e,i),{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection});u=n}else{let n=/* @__PURE__ */ new Map;for(let t of e){let e=Bme(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>c$(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=>h$(t.configId)?h$(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>g$(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:UQ(e.metadata),permissions:n.permissions?le(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(Eme(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const Ume=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`}),userId:GW().meta({description:`The id of the user which the api key belongs to. server-only. Eg: "some-user-id"`}).optional(),name:k().meta({description:`The name of the key`}).optional(),enabled:Ge().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:Fe().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:Fe().meta({description:`The refill amount`}).optional(),refillInterval:Fe().meta({description:`The refill interval`}).optional(),metadata:Ze().optional(),expiresIn:Fe().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:Ge().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:Fe().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:Fe().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:Ie(k(),Le(k())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function Wme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/update`,{method:`POST`,body:Ume,metadata:{openapi:{description:`Update an existing API key by ID`,responses:{200:{description:`API key updated successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,keyId:i,expiresIn:a,enabled:o,metadata:s,refillAmount:c,refillInterval:l,remaining:u,name:d,permissions:f,rateLimitEnabled:p,rateLimitTimeWindow:m,rateLimitMax:h}=t.body,g=await zJ(t,{disableCookieCache:!0}),_=t.request||t.headers,v=_&&!g?null:g?.user||{id:t.body.userId};if(!v?.id||g&&t.body.userId&&g?.user.id!==t.body.userId)throw E.from(`UNAUTHORIZED`,BQ.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`,BQ.SERVER_ONLY_PROPERTY);let y=m$(t.context,e,r),b=null;if(b=await i$(t,i,y),!b||!g$(b.configId,y.configId))throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);let x=m$(t.context,e,b.configId);if((x.references??`user`)===`organization`)await l$(t,v.id,b.referenceId,`update`);else if(b.referenceId!==v.id)throw E.from(`NOT_FOUND`,BQ.KEY_NOT_FOUND);let S={};if(d!==void 0){if(d.length<x.minimumNameLength||d.length>x.maximumNameLength)throw E.from(`BAD_REQUEST`,BQ.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`,BQ.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<x.keyExpiration.minExpiresIn)throw E.from(`BAD_REQUEST`,BQ.EXPIRES_IN_IS_TOO_SMALL);if(e>x.keyExpiration.maxExpiresIn)throw E.from(`BAD_REQUEST`,BQ.EXPIRES_IN_IS_TOO_LARGE)}S.expiresAt=a?u$(a,`sec`):null}if(s!==void 0&&x.enableMetadata===!0){if(typeof s!=`object`)throw E.from(`BAD_REQUEST`,BQ.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`,BQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(l!==void 0&&c===void 0)throw E.from(`BAD_REQUEST`,BQ.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`,BQ.NO_VALUES_TO_UPDATE);let ee=b;try{if(x.storage===`secondary-storage`&&x.fallbackToDatabase){let e=await t.context.adapter.update({model:b$,where:[{field:`id`,value:b.id}],update:S});e&&(await a$(t,e,x),ee=e)}else if(x.storage===`database`){let e=await t.context.adapter.update({model:b$,where:[{field:`id`,value:b.id}],update:S});e&&(ee=e)}else{let e={...b,...S,updatedAt:/* @__PURE__ */ new Date};await a$(t,e,x),ee=e}}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let C=await GQ(t,ee,x),{key:te,...ne}=ee;return t.json({...ne,metadata:C,permissions:ne.permissions?le(ne.permissions):null})})}function d$(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:BQ.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function f$({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let c=n.disableKeyHashing?e:await y$(e),l=await r$(t,c,n);if(!l||o!==void 0&&!g$(l.configId,o))throw E.from(`UNAUTHORIZED`,BQ.INVALID_API_KEY);let u=m$(t.context,r,l.configId);if(s&&u.customAPIKeyValidator&&!await u.customAPIKeyValidator({ctx:t,key:e}))throw E.from(`UNAUTHORIZED`,BQ.KEY_NOT_FOUND);if(l.enabled===!1)throw E.from(`UNAUTHORIZED`,BQ.KEY_DISABLED);if(l.expiresAt&&Date.now()>new Date(l.expiresAt).getTime()){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await o$(t,l,u),await t.context.adapter.delete({model:b$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await o$(t,l,u):await t.context.adapter.delete({model:b$,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`,BQ.KEY_EXPIRED)}if(a){let e=l.permissions?le(l.permissions):null;if(!e||!uee(e).authorize(a).success)throw E.from(`UNAUTHORIZED`,BQ.KEY_NOT_FOUND)}if(l.remaining===0&&l.refillAmount===null){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await o$(t,l,u),await t.context.adapter.delete({model:b$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await o$(t,l,u):await t.context.adapter.delete({model:b$,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`,BQ.USAGE_EXCEEDED)}return{apiKey:u.storage===`database`||u.storage===`secondary-storage`&&u.fallbackToDatabase?await Gme({ctx:t,apiKey:l,opts:u,hashedKey:c}):await qme({ctx:t,apiKey:l,opts:u,hashedKey:c}),opts:u}}async function Gme({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await Kme(e,t)),i=await p$(e,i,n);let a=await e.context.adapter.update({model:b$,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw E.from(`UNAUTHORIZED`,BQ.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await a$(e,a,n),a}async function Kme(e,t){let n=/* @__PURE__ */ new Date,{refillInterval:r,refillAmount:i}=t;if(r&&i){let a=new Date(t.lastRefillAt??t.createdAt).getTime();if(n.getTime()-a>r){let r=await e.context.adapter.incrementOne({model:b$,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:b$,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw E.from(`TOO_MANY_REQUESTS`,BQ.USAGE_EXCEEDED);return a}async function p$(e,t,n){let r=d$(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:b$,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:b$,where:[{field:`id`,value:t.id}]});if(!a)throw E.from(`UNAUTHORIZED`,BQ.INVALID_API_KEY);return p$(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:b$,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:b$,where:[{field:`id`,value:t.id}]});if(!o)throw E.from(`UNAUTHORIZED`,BQ.INVALID_API_KEY);return p$(e,o,n)}async function qme({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t.remaining,a=t.lastRefillAt;if(i!==null){let e=Date.now(),{refillInterval:n,refillAmount:r}=t,o=new Date(a??t.createdAt).getTime();if(n&&r&&e-o>n&&(i=r,a=/* @__PURE__ */ new Date),i===0)throw E.from(`TOO_MANY_REQUESTS`,BQ.USAGE_EXCEEDED);i--}let o={...Jme(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await r$(e,r,n);if(!t)return null;let i={...t,...o};return await a$(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`,BQ.FAILED_TO_UPDATE_API_KEY);return c}function Jme(e,t){let n=d$(e,t);switch(n.type){case`deny`:throw new E(`TOO_MANY_REQUESTS`,{message:n.message,code:`RATE_LIMITED`,details:{tryAgainIn:n.tryAgainIn}});case`skip`:return n.lastRequest===null?{}:{lastRequest:n.lastRequest};case`start`:case`reset`:return{lastRequest:n.now,requestCount:1};case`increment`:return{lastRequest:n.now,requestCount:e.requestCount+1}}}const Yme=A({configId:k().meta({description:`Configuration ID to scope verification to. When omitted, the key is validated against its own configuration.`}).optional(),key:k().meta({description:`The key to verify`}),permissions:Ie(k(),Le(k())).meta({description:`The permissions to verify.`}).optional()});function Xme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X.serverOnly({method:`POST`,body:Yme},async r=>{let{configId:i,key:a}=r.body,o=m$(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:BQ.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await f$({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:o,configurations:e,schema:t,expectedConfigId:i,runCustomValidator:i===void 0});s=l.apiKey,c=l.opts,c.deferUpdates&&r.context.runInBackground(n(r.context).catch(e=>{r.context.logger.error(`Failed to delete expired API keys:`,e)}))}catch(e){return r.context.logger.error(`Failed to validate API key:`,e),Mme(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:BQ.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 GQ(r,s,c)),u.permissions=u.permissions?le(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function m$(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=BQ.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 h$(e){return!e||e==="default"}function g$(e,t){return h$(e)&&h$(t)?!0:e===t}let _$=null;async function v$(e,t=!1){_$&&!t&&(/* @__PURE__ */ new Date()).getTime()-_$.getTime()<1e4||(_$=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:b$,where:[{field:`expiresAt`,operator:`lt`,value:/* @__PURE__ */ new Date},{field:`expiresAt`,operator:`ne`,value:null}]}).catch(t=>{e.logger.error(`Failed to delete expired API keys:`,t)}))}function Zme({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:Pme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),verifyApiKey:Xme({configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),getApiKey:zme({configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),updateApiKey:Wme({configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),deleteApiKey:Lme({configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),listApiKeys:Hme({configurations:t,schema:n,deleteAllExpiredApiKeys:v$}),deleteAllExpiredApiKeys:Fme({deleteAllExpiredApiKeys:v$})}}const Qme=({defaultRateLimitMax:e,defaultTimeWindow:t})=>({apikey:{fields:{configId:{type:`string`,required:!0,defaultValue:`default`,input:!1,index:!0},name:{type:`string`,required:!1,input:!1},start:{type:`string`,required:!1,input:!1},referenceId:{type:`string`,required:!0,input:!1,index:!0},prefix:{type:`string`,required:!1,input:!1},key:{type:`string`,required:!0,input:!1,index:!0},refillInterval:{type:`number`,required:!1,input:!1},refillAmount:{type:`number`,required:!1,input:!1},lastRefillAt:{type:`date`,required:!1,input:!1},enabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:`number`,required:!1,input:!1,defaultValue:t},rateLimitMax:{type:`number`,required:!1,input:!1,defaultValue:e},requestCount:{type:`number`,required:!1,input:!1,defaultValue:0},remaining:{type:`number`,required:!1,input:!1},lastRequest:{type:`date`,required:!1,input:!1},expiresAt:{type:`date`,required:!1,input:!1},createdAt:{type:`date`,required:!0,input:!1},updatedAt:{type:`date`,required:!0,input:!1},permissions:{type:`string`,required:!1,input:!1},metadata:{type:`string`,required:!1,input:!0,transform:{input(e){return JSON.stringify(e)},output(e){return e?Tme(e):null}}}}}}),y$=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})},b$=`apikey`;function $me(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new D(`configId is required for each API key configuration in the api-key plugin.`);let t=e.map(e=>e.configId);if(new Set(t).size!==t.length)throw new D(`configId must be unique for each API key configuration in the api-key plugin.`)}let n=t??{schema:Array.isArray(e)?void 0:e?.schema},r=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??`x-api-key`,defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??`database`,rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],i=lG(Qme({defaultRateLimitMax:(r.length===1?r[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(r.length===1?r[0]?.rateLimit.timeWindow:void 0)??864e5}),n.schema),a=async e=>{let t=JH(e.length,`a-z`,`A-Z`);return`${e.prefix||``}${t}`};function o(e,t){if(t.customAPIKeyGetter)return t.customAPIKeyGetter(e);if(Array.isArray(t.apiKeyHeaders)){for(let n of t.apiKeyHeaders){let t=e.headers?.get(n);if(t)return t}return null}return e.headers?.get(t.apiKeyHeaders)??null}function s(e){for(let t of r){if(!t.enableSessionForAPIKeys)continue;let n=o(e,t);if(n)return{key:n,config:t}}return null}let c=Zme({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.10`,$ERROR_CODES:BQ,hooks:{before:[{matcher:e=>!!s(e),handler:zq(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw E.from(`BAD_REQUEST`,BQ.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw E.from(`FORBIDDEN`,BQ.INVALID_API_KEY);let{apiKey:a}=await f$({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=v$(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=BQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let c=await e.context.internalAdapter.findUserById(a.referenceId);if(!c){let e=BQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let l={user:c,session:{id:a.id,token:t,userId:a.referenceId,userAgent:e.request?.headers.get(`user-agent`)??null,ipAddress:e.request?xJ(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||u$(e.context.options.session?.expiresIn||604800,`ms`)}};return e.context.session=l,e.path===`/get-session`?l:{context:e}})}]},endpoints:{createApiKey:c.createApiKey,verifyApiKey:c.verifyApiKey,getApiKey:c.getApiKey,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,listApiKeys:c.listApiKeys,deleteAllExpiredApiKeys:c.deleteAllExpiredApiKeys},schema:i}}const x$=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await SH(e)).findMany({model:`jwks`}),getLatestKey:async n=>{let r=/* @__PURE__ */ new Date,i=e=>!e.expiresAt||e.expiresAt>r;return t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]:(await(await SH(e)).findMany({model:`jwks`}))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},getKeyById:async(n,r)=>t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.find(e=>e.id===r):await(await SH(e)).findOne({model:`jwks`,where:[{field:`id`,value:r}]})??void 0,getLatestKeyByAlg:async(n,r)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await SH(e)).findMany({model:`jwks`});if(!i)return;let a=t?.jwks?.keyPairConfig?.alg??`EdDSA`,o=/* @__PURE__ */ new Date;return i.filter(e=>e.alg===r||e.alg==null&&a===r).filter(e=>!e.expiresAt||e.expiresAt>o).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},createJwk:async(n,r)=>t?.adapter?.createJwk?await t.adapter.createJwk(r,n):await(await SH(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function S$(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+mG(e)}async function ehe(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Nde(t,{...n,extractable:!0});return{publicWebKey:await dI(r),privateWebKey:await dI(i),alg:t,cfg:n}}async function C$(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await ehe(t),o=a&&`crv`in a?a.crv:void 0,s=typeof n.crv==`string`?n.crv:void 0,c=o??s,l=JSON.stringify(r),u=!t?.jwks?.disablePrivateKeyEncryption,d={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(n),privateKey:u?JSON.stringify(await RW({key:e.context.secretConfig,data:l})):l,createdAt:/* @__PURE__ */ new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await x$(e.context.adapter,t).createJwk(e,d)}async function w$(e,t,n){if(t?.jwt?.sign)return null;let r=x$(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let e=t?.jwks?.keyPairConfig?.alg??`EdDSA`;if((i.alg??e)!==n.signingAlgorithm)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${e}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await r.getLatestKeyByAlg(e,n.signingAlgorithm),!i){let r=t?.jwks?.keyPairConfig?.alg??`EdDSA`,a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await C$(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new D(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${r}"; additional algs configured via keyPairConfigs: ${e}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let n=t?.jwks?.keyPairConfig?.alg??`EdDSA`;i=await r.getLatestKeyByAlg(e,n)??await r.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt</* @__PURE__ */ new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new D(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await C$(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await zW({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new D(`Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.`)}),o=i.alg??t?.jwks?.keyPairConfig?.alg??`EdDSA`,s=await yI(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function T$(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=S$(n?.jwt?.expirationTime??`15m`,a??i);o??=s;let c=r.nbf,l=typeof e.context.options.baseURL==`string`?e.context.options.baseURL:``,u=r.iss,d=n?.jwt?.issuer??l,f=r.aud,p=n?.jwt?.audience??l;if(n?.jwt?.sign){let e={...r,iat:a,exp:o,nbf:c,iss:u??d,aud:f??p};return n.jwt.sign(e,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:m,kid:h,privateKey:g}=t.resolvedKey??await w$(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new cI(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 E$(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await T$(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 D$(e){let t=e.context.options.baseURL;return typeof t==`string`?t||`better-auth:session-cache`:e.context.baseURL||`better-auth:session-cache`}async function the(e,t,n){let r=bI(t),i=r.kid;if(!i)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let a=await x$(e.context.adapter,n).getAllKeys(e);if(!a?.length)return e.context.logger.debug(`No JWKS keys available for cookie-cache JWT`),null;let o=a.find(e=>e.id===i);if(!o)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${i}`),null;let s=o.alg??n?.jwks?.keyPairConfig?.alg??r.alg;return s?{alg:s,publicKey:await yI(JSON.parse(o.publicKey),s)}:(e.context.logger.debug(`No JWT algorithm available for cookie-cache JWT kid: ${i}`),null)}async function nhe(e,t,n,r){let i=await w$(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 cI({...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(D$(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function rhe(e,t,n){try{if(bI(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await the(e,t,n);if(!r)return null;let{payload:i}=await oI(t,r.publicKey,{...DG({issuer:D$(e)}),algorithms:[r.alg]}),a=OG(i);return a?{payload:a,expiresAt:a.exp?a.exp*1e3:Date.now()}:null}catch(t){return e.context.logger.debug(`Cookie-cache JWT verification failed`,t),null}}function ihe(e){return{sign:(t,n,r)=>nhe(t,n,r,e),verify:(t,n)=>rhe(t,n,e)}}const ahe={jwks:{fields:{publicKey:{type:`string`,required:!0},privateKey:{type:`string`,required:!0},createdAt:{type:`date`,required:!0},expiresAt:{type:`date`,required:!1},alg:{type:`string`,required:!1},crv:{type:`string`,required:!1}}}};async function ohe(e,t){let n=pH();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(ue.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await x$(n.context.adapter,t).getAllKeys(n);if(!o||o.length===0)return n.context.logger.debug(`No JWKS keys available`),null;let s=o.find(e=>e.id===a);if(!s)return n.context.logger.debug(`No JWKS key found for kid: ${a}`),null;let c=await yI(JSON.parse(s.publicKey),s.alg??t?.jwks?.keyPairConfig?.alg??`EdDSA`),l=typeof n.context.options.baseURL==`string`?n.context.options.baseURL:void 0,{payload:u}=await oI(e,c,{issuer:t?.jwt?.issuer??l,audience:t?.jwt?.audience??l});return!u.sub||!u.aud?null:u}catch(e){return n.context.logger.debug(`JWT verification failed`,e),null}}const she=A({payload:Ie(k(),Ze()),overrideOptions:Ie(k(),Ze()).optional()}),che=A({token:k(),issuer:k().optional()}),lhe=e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new D(`options.jwks.remoteUrl must be set when using options.jwt.sign`);if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new D(`options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata`);let t=e?.jwks?.jwksPath??`/jwks`;if(typeof t!=`string`||t.length===0||!t.startsWith(`/`)||t.includes(`..`))throw new D(`options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'`);return{id:`jwt`,version:`1.7.10`,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!==`jwt`)throw new D('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new D("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let n=e.jwks?.gracePeriod,r=t.options.session.cookieCache.maxAge||300;return n!==void 0&&r>n&&t.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${r}s) exceeds the JWT plugin JWKS grace period (${n}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...t.sessionConfig,cookieCacheSigner:ihe(e)}}}},endpoints:{getJwks:X(t,{method:`GET`,metadata:{openapi:{operationId:`getJSONWebKeySet`,description:`Get the JSON Web Key Set`,responses:{200:{description:`JSON Web Key Set retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{keys:{type:`array`,description:`Array of public JSON Web Keys`,items:{type:`object`,properties:{kid:{type:`string`,description:`Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk`},kty:{type:`string`,description:`Key type (e.g., 'RSA', 'EC', 'OKP')`},alg:{type:`string`,description:`Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')`},use:{type:`string`,description:`Intended use of the public key (e.g., 'sig' for signature)`,enum:[`sig`],nullable:!0},n:{type:`string`,description:`Modulus for RSA keys (base64url-encoded)`,nullable:!0},e:{type:`string`,description:`Exponent for RSA keys (base64url-encoded)`,nullable:!0},crv:{type:`string`,description:`Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')`,nullable:!0},x:{type:`string`,description:`X coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0},y:{type:`string`,description:`Y coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0}},required:[`kid`,`kty`,`alg`]}}},required:[`keys`]}}}}}}}},async t=>{if(e?.jwks?.remoteUrl)throw new E(`NOT_FOUND`);let n=x$(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await C$(t,e),r=await n.getAllKeys(t)),!r?.length)throw new D(`No key sets found. Make sure you have a key in your database.`);let i=Date.now(),a=(e?.jwks?.gracePeriod??2592e3)*1e3,o=r.filter(e=>!e.expiresAt||e.expiresAt.getTime()+a>i),s=e?.jwks?.keyPairConfig,c=s&&`crv`in s?s.crv:void 0;return t.json({keys:o.map(t=>({alg:t.alg??e?.jwks?.keyPairConfig?.alg??`EdDSA`,crv:t.crv??c,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:X(`/token`,{method:`GET`,requireHeaders:!0,use:[VJ],metadata:{openapi:{operationId:`getJSONWebToken`,description:`Get a JWT token`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async t=>{let n=await E$(t,e);return t.json({token:n})}),signJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:she},async t=>{let n=await T$(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:n})}),verifyJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{},response:{}}},body:che},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await ohe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:zq(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await E$(t,e),r=t.context.responseHeaders?.get(`access-control-expose-headers`)||``,i=new Set(r.split(`,`).map(e=>e.trim()).filter(Boolean));i.add(`set-auth-jwt`),t.setHeader(`set-auth-jwt`,n),t.setHeader(`Access-Control-Expose-Headers`,Array.from(i).join(`, `))}})}]},schema:lG(ahe,e?.schema)}};var O$=Object.defineProperty,k$=(e,t)=>{let n={};for(var r in e)O$(n,r,{get:e[r],enumerable:!0});return t||O$(n,Symbol.toStringTag,{value:`Module`}),n};const A$=`ba_iat`,j$=`ba_pl`,M$=`ba_param`;function N$(e){let t=new URLSearchParams,n=[...e.entries()].sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r));for(let[e,r]of n)t.append(e,r);return t}function uhe(e){e.delete(M$);let t=[.../* @__PURE__ */ new Set([...e.keys(),M$])].sort();for(let n of t)e.append(M$,n)}function dhe(e){let t=new URLSearchParams(e).get(A$);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const fhe=[`authorization_code`,`client_credentials`,`refresh_token`],P$=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],phe=[`none`,...P$],mhe=new Set(phe);function F$(e,t){if(!(t.trim().length>0))throw new D(`OAuth Provider extension ${e} cannot be empty`)}function I$(e,t){F$(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new D(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function hhe(e){I$(`grant type`,e)}function ghe(e){if(F$(`token_endpoint_auth_method`,e),mhe.has(e))throw new D(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function _he(e){if(I$(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new D(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function vhe(e){let t=Object.keys(e.grants??{});for(let e of t)hhe(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){ghe(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new D(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)_he(t),r.push(t)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map(e=>e.id);for(let e of i)F$(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function L$(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 R$(e){let t=(e??[]).map(vhe);L$(`grant type`,t.flatMap(e=>e.grantTypes)),L$(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),L$(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),L$(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function z$(e){return e.extensions??[]}function B$(e){return z$(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function yhe(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new D(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];R$(i),n.options.extensions=i}function bhe(e){return z$(e).flatMap(e=>Object.keys(e.grants??{}))}function V$(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??fhe,...bhe(e)]))}function xhe(e,t){for(let n of z$(e)){let e=n.grants?.[t];if(e)return e}}function H$(e){return z$(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function U$(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...P$,...H$(e)]))}function W$(e,t){return t?H$(e).includes(t):!1}function She(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of z$(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 G$(e,t,n,r){let i={...r};for(let a of z$(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 K$(e,t){let n={};for(let r of z$(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?f.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function Che(e,t){return K$(e,e=>e.claims?.accessToken?.(t))}function whe(e,t){return K$(e,e=>e.claims?.idToken?.(t))}function The(e,t){return K$(e,e=>e.claims?.userInfo?.(t))}function Ehe(e){return z$(e).some(e=>e.claims?.userInfo)}function Dhe(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Ohe(){let e=/* @__PURE__ */ new Map;return{get(t){let n=e.get(t);if(n){if(n.expiresAt&&n.expiresAt</* @__PURE__ */ new Date)e.delete(t);else return n}},set(t,n){e.set(t,n)}}}const q$=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new D(`jwt_config`);return t},khe=/* @__PURE__ */ new Set([yP.code,gP.code,vP.code]);function J$(e){return e instanceof oP&&!khe.has(e.code)}function Y$(e){if(e!=null){if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==`number`){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==`string`){let t=e.trim();if(!t.length)return;let n=Number(t);if(Number.isFinite(n)){let e=new Date(n);return Number.isFinite(e.getTime())?e:void 0}let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}}}function Ahe(e){if(e instanceof Date||!e||typeof e!=`object`)return Y$(e);let t=Y$(e.createdAt)??Y$(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return Y$(n.createdAt)??Y$(n.created_at)}function X$(e){if(typeof e==`string`)return[e];if(e?.length)return e}function Z$(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const Q$=/* @__PURE__ */ new WeakMap;function jhe(e){let t=Q$.get(e);if(t)return t;let n=Ohe();return Q$.set(e,n),n}async function $$(e,t){let n=new URLSearchParams(e),r=n.get(`sig`),i=n.getAll(`sig`),a=Number(n.get(`exp`));n.delete(`sig`);let o=await VW(N$(n).toString(),t);return i.length===1&&!!r&&wU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}function e1(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 t1(e,t,n){let r=jhe(t),i=r.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let a=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??`oauthClient`,where:[{field:`clientId`,value:n}]}),o=B$(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 n1(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const r1=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})};async function i1(e,t,n){if(t===`encrypted`)return await zW({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new D(`Unsupported decryption storageMethod type '${t}'`)}async function Mhe(e,t,n,r){let i=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r&&t.prefix?.clientSecret){if(r.startsWith(t.prefix?.clientSecret))r=r.replace(t.prefix.clientSecret,``);else throw new O(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await r1(r):void 0;return!!e&&wU(e,n)}if(typeof i==`object`&&`hash`in i){if(i.verify)return!!r&&await i.verify(r,n);{let e=r?await i.hash(r):void 0;return!!e&&wU(e,n)}}if(i===`encrypted`)try{let t=await i1(e,i,n);return!!r&&wU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await i1(e,i,n);return!!r&&wU(t,r)}throw new D(`Unsupported verify storageMethod type '${i}'`)}async function a1(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await RW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await r1(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 o1(e=`hashed`,t,n){if(e===`hashed`)return await r1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`storeToken: unsupported storageMethod type '${e}'`)}async function s1(e=`hashed`,t,n){if(e===`hashed`)return await r1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`getStoredToken: unsupported storageMethod type '${e}'`)}const c1=/^Basic +/i,Nhe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Phe(e){return e.match(Nhe)?.[1]}const l1=[`client_secret`,`client_assertion`,`client_assertion_type`];function u1(e){throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Fhe(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&u1(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&u1(`${e} must be a string`),r[e]=t)};for(let e of l1)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&&u1(`client_id must not be repeated`),n=r[0];for(let e of l1){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&u1(`${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)&&u1(`A request must use only one client authentication method`),t.client_id=n;for(let e of l1)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Ihe(e){if(c1.test(e))try{let{clientId:t,clientSecret:n}=rX(e);return{client_id:t,client_secret:n}}catch{throw new O(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function d1(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 f1(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 p1(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 m1(e,t,n,r,i,a,o,s){let c=await t1(e,t,n);c||p1(`client not found`,{method:s}),c.disabled&&p1(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&p1(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||W$(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&&p1(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&p1(`public client, client secret should not be received`,{method:s}),r&&!await Mhe(e,t,c.clientSecret,r)&&p1(`invalid client_secret`,{method:s})),f1(c,i),o&&!d1(c,o))throw new O(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function h1(e){if(e)return typeof e==`string`?JSON.parse(e):e}function g1(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 _1(e,t,n){let r={...e.body??{}};await Fhe(e.request,r);let i=e.request?.headers.get(`authorization`)??void 0;if(r.client_assertion_type||r.client_assertion){if(!r.client_assertion||!r.client_assertion_type)throw new O(`BAD_REQUEST`,{error_description:`client_assertion and client_assertion_type must both be provided`,error:`invalid_client`});let i=r.client_assertion,a=r.client_assertion_type,o=She(t,a);if(o){let s=await o.strategy.authenticate({ctx:e,opts:t,assertion:i,assertionType:a,clientId:r.client_id,expectedAudience:n});return{kind:`pre_verified`,method:o.method,clientId:s.clientId,confirmation:s.confirmation}}let{verifyClientAssertion:s}=await Promise.resolve().then(()=>a_e).then(e=>e.o);return{kind:`pre_verified`,method:`private_key_jwt`,clientId:(await s(e,t,i,a,r.client_id,n)).clientId}}if(i&&!c1.test(i)){let e=Phe(i);if(!e)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});p1(`unsupported authorization scheme`,{scheme:e})}if(i&&c1.test(i)){let e=Ihe(i);if(e)return{kind:`client_secret`,method:`client_secret_basic`,clientId:e.client_id,clientSecret:e.client_secret}}return r.client_id&&r.client_secret?{kind:`client_secret`,method:`client_secret_post`,clientId:r.client_id,clientSecret:r.client_secret}:r.client_id?{kind:`public`,method:`none`,clientId:r.client_id}:null}function v1(e){let t=e.split(` `).map(e=>e.trim()),n=/* @__PURE__ */ new Set;for(let e of t)(e===`login`||e===`consent`||e===`create`||e===`select_account`||e===`none`)&&n.add(e);return new Set(n)}function Lhe(e){let t=e.redirectUris?.[0];if(!t)throw new D(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function Rhe(e,t,n){return VW(`${Lhe(t)}.${e}`,n)}async function y1(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Rhe(e,t,n.pairwiseSecret):e}async function b1(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function x1(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 S1(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 C1(e,t){if(!t)return!1;let n=Y$(e);return n?n.getTime()>=t.getTime():!1}function w1(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 T1(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function E1(e,t){if(e.tokenEndpointAuthMethod===`none`)return`pkce is required for public clients`;let n=t?.scopes??[],r=n.includes(`openid`),i=typeof t?.nonce==`string`&&t.nonce.length>0,a=r&&i;return n.includes(`offline_access`)&&!a?`pkce or OIDC nonce is required when requesting offline_access scope`:e.requirePKCE??!0?`pkce is required for this client`:!1}const zhe=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,Bhe=/* @__PURE__ */ new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function D1(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&zhe.test(t)}function Vhe(e){return Bhe.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function O1(e){return D1(e)||Vhe(e)}const k1=tee().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),Ue}xq.includes(n.protocol)?t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!SY(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))}),Hhe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function A1(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Hhe.has(r)?t.push(r):n[r]=i;return t.length>0&&f.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const j1=Ie(k(),et()).nullable(),Uhe=Ve({essential:Ge().optional(),value:k().optional(),values:Le(k()).optional()}).nullable(),Whe=A({acr:Uhe.optional()}).catchall(j1),Ghe=Ve({userinfo:Ie(k(),j1).optional(),id_token:Whe.optional()});function Khe(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function M1(e){let t=Khe(e),n=Ghe.safeParse(t);return n.success?n.data:void 0}const N1=Oe([k(),Ie(k(),et())]),qhe=N1,P1=N1.refine(e=>M1(e)!==void 0,{error:`claims must be a valid Claims request object`});function Jhe(e){return e===void 0||M1(e)!==void 0}function F1(e,t){let n=M1(e)?.userinfo;if(!n)return[];let r=Object.keys(n);if(!t)return r;let i=new Set(t);return r.filter(e=>i.has(e))}function Yhe(e,t){let n=M1(e);if(!n)return e===void 0;let r=n.id_token?.acr;if(!r||r.essential!==!0)return!0;let i=r.value===void 0||r.value===t,a=r.values===void 0||r.values.includes(t);return i&&a}function Xhe(e,t){let n=M1(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 I1(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const L1={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>I1(e.name).given},family_name:{scope:`profile`,resolve:e=>I1(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},R1=Object.keys(L1);function z1(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const Zhe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function Qhe(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))Zhe.has(r)?t.push(r):n[r]=i;return t.length>0&&f.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function B1(e){let{ctx:t,opts:n,user:r,client:i,scopes:a,resources:o,referenceId:s,metadata:c,grantType:l,sessionId:u,perRequestClaims:d,resourcePolicyClaims:f}=e,p=await Che(n,{ctx:t,opts:n,user:r,client:i,scopes:a,grantType:l,referenceId:s,sessionId:u,resources:o,metadata:c}),m=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:r,scopes:a,resources:o,referenceId:s,metadata:c}):{};return Qhe({...p,...d??{},...m,...f})}const $he=[`javascript:`,`data:`,`vbscript:`],V1=k().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),Ue;e.includes(`#`)?t.addIssue({code:`custom`,message:`resource must not contain a fragment`}):$he.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),ege=Je([`none`,`consent`,`login`,`create`,`select_account`]),tge=k().superRefine((e,t)=>{let n=e.split(` `).map(e=>e.trim()).filter(Boolean),r=/* @__PURE__ */ new Set;if(!n.length)t.addIssue({code:`custom`,message:`prompt must include at least one value`});else{for(let e of n){let n=ege.safeParse(e);n.success?r.add(n.data):t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`})}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}}),H1=A({keys:Le(Ie(k(),et())).min(1)}),nge=Oe([Fe(),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`}),Ue):n}),rge=k().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),U1=A({response_type:k().pipe(Je([`code`])).optional(),request:k().optional(),request_uri:k().optional(),redirect_uri:k1.optional(),scope:k().optional(),state:k().optional(),client_id:k().min(1,`client_id is required`),prompt:tge.optional(),display:k().optional(),ui_locales:k().optional(),max_age:nge.optional(),acr_values:k().optional(),login_hint:k().optional(),id_token_hint:k().optional(),code_challenge:k().optional(),code_challenge_method:k().pipe(Je([`S256`])).optional(),nonce:k().optional(),claims:qhe.optional(),dpop_jkt:rge.optional(),resource:Oe([V1,Le(V1).min(1)]).optional()}).passthrough(),ige=U1.extend({redirect_uri:k1.optional(),claims:P1.optional()}),age=A({type:Ke(`authorization_code`),query:ige,sessionId:k(),userId:k(),referenceId:k().optional(),authTime:Fe().optional(),resource:Le(k()).optional()}).passthrough(),W1=A({redirect_uris:Le(k1).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:Le(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:Le(k1).min(1).optional(),backchannel_logout_uri:k1.optional(),backchannel_logout_session_required:Ge().optional(),token_endpoint_auth_method:k().trim().min(1).optional(),jwks:H1.optional(),jwks_uri:k().optional(),grant_types:Le(k().trim().min(1)).min(1).optional(),response_types:Le(Je([`code`])).optional(),application_type:Je([`web`,`native`]).optional(),subject_type:Je([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:Ge().optional(),resources:Le(V1).optional(),skip_consent:Be({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),oge=W1.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:Fe().int().nonnegative().optional(),client_id_issued_at:Fe().int().nonnegative().optional()}).loose(),G1=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],sge=new Set(G1);async function K1(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=V1.safeParse(t);return r.success?{ok:!0}:{ok:!1,reason:`resource identifier ${t} is invalid: ${r.error.issues[0]?.message??`not an absolute URI`}`}}async function cge(e,t){let n=await K1(e,t);if(!n.ok)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const lge=e=>`${e}/oauth2/userinfo`;async function uge(e){if(!(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`))return;let t;try{t=await e.clone().text()}catch{return}if(!t)return;let n=new URLSearchParams(t).getAll(`resource`).filter(e=>e.length>0);return n.length>0?n:void 0}function dge(e){if(e!=null){if(typeof e==`string`)return[e];if(Array.isArray(e)){let t=e.filter(e=>typeof e==`string`&&e.length>0);return t.length>0?t:void 0}}}async function q1(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=>Q1(e,t,n)))).every(Boolean)}async function J1(e,t,n){let r=dge(n.resource),i=n.requestedScopes.includes(`openid`),a=lge(e.context.baseURL??``);if(!r)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let o=[...new Set(r)],s=[];for(let n of o){if(n===a)continue;let r=await Q1(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}=Y1(t);c&&s.length>0&&await fge(e,t,n.clientId,s);let l=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=l.filter(e=>t.has(e));if(n.length===0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});l=n}let u=null,d=null;for(let e of s)e.accessTokenTtl!=null&&(u=u===null?e.accessTokenTtl:Math.min(u,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(d=d===null?e.refreshTokenTtl:Math.min(d,e.refreshTokenTtl));let f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set;for(let e of s)e.signingAlgorithm&&f.add(e.signingAlgorithm),e.signingKeyId&&p.add(e.signingKeyId);if(f.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(p.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let m=f.values().next().value??null,h=p.values().next().value??null,g={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(g,e.customClaims);let _=s.some(e=>e.dpopBoundAccessTokensRequired===!0),v=i?[...o,a]:o,y=[...new Set(v)];return{audienceClaim:y.length===1?y[0]:y,accessTokenTtl:u,refreshTokenTtl:d,signingAlgorithm:m,signingKeyId:h,rawCustomClaims:g,dpopBoundAccessTokensRequired:_,effectiveScopes:l}}async function fge(e,t,n,r){if(r.length===0)return;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,a=await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n}]}),o=new Set(a?.map(e=>e.resourceId)??[]),s=r.filter(e=>!o.has(e.identifier));if(s.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function pge(e,t,n,r){if(r.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`;return((await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n},{field:`resourceId`,operator:`in`,value:r}],limit:1}))?.length??0)>0}async function mge(e,t,n){if(n.length===0)return{};let r=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,operator:`in`,value:n}]}),i=new Map(r.map(e=>[e.identifier,e])),a={};for(let e of n){let t=i.get(e);t?.customClaims&&typeof t.customClaims==`object`&&Object.assign(a,t.customClaims)}return a}function Y1(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const X1=/* @__PURE__ */ new Map;function Z1(e){e===void 0?X1.clear():X1.delete(e)}async function Q1(e,t,n){if(await t0(e.context,t),t.cachedResources?.has(n)){let e=X1.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)&&X1.set(n,Object.assign({},r)),r}function hge(e){return e.name??e.identifier}function gge(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function $1(e,t){return{identifier:e.identifier,name:hge(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function _ge(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=$1(e,n);return i}let r={updatedAt:n};return e.name!==void 0&&(r.name=e.name),e.accessTokenTtl!==void 0&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl!==void 0&&(r.refreshTokenTtl=e.refreshTokenTtl),e.signingAlgorithm!==void 0&&(r.signingAlgorithm=e.signingAlgorithm),e.signingKeyId!==void 0&&(r.signingKeyId=e.signingKeyId),e.allowedScopes!==void 0&&(r.allowedScopes=e.allowedScopes),e.customClaims!==void 0&&(r.customClaims=e.customClaims),e.dpopBoundAccessTokensRequired!==void 0&&(r.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired),e.disabled!==void 0&&(r.disabled=e.disabled),e.metadata!==void 0&&(r.metadata=e.metadata),r}const vge=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function yge(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=vge.test(r instanceof Error?r.message:String(r)),r=r instanceof Error?r.cause:void 0;n?e.logger.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`):e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}let e0=/* @__PURE__ */ new WeakMap;function bge(e,t){let n=e.adapter,r=e0.get(n);r||(r=/* @__PURE__ */ new WeakMap,e0.set(n,r));let i=r.get(t);if(i)return i;let a={completed:!1,promise:null};return r.set(t,a),a}async function xge(e,t){let n=gge(t);if(n.length===0)return;let r=t.resourceSeedMode??`insertOnly`,i=t.schema?.oauthResource?.modelName??`oauthResource`;for(let a of n){let n=await K1(t,a.identifier);if(!n.ok){f.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!sge.has(o.signingAlgorithm)){f.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${G1.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:$1(o,l)});continue}catch(t){if(!await e.adapter.findOne({model:i,where:s}).catch(()=>null))throw t}r!==`insertOnly`&&await e.adapter.update({model:i,where:s,update:_ge(o,r,l)})}}async function t0(e,t){let n=bge(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=xge(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Sge(e){let t=Y1(e);f.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function n0(e){return e.headers?.get(`dpop`)??void 0}function r0(e,t){let{baseURL:n}=e.context,r=n.length;for(;r>0&&n[r-1]===`/`;)r--;let i=n.slice(0,r);if(!e.request||!i)return`${i}${t}`;let a=new URL(i).pathname.replace(/\/$/,``),o=new URL(e.request.url).pathname;return`${i}${o.startsWith(`${a}/`)?o.slice(a.length):t}`}const Cge=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function i0(e){return Cge.has(e)}function a0(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function o0(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)||i0(e));if(a.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}function wge(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(L1))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function s0(e,t){let n={};for(let[r,i]of Object.entries(e??{}))i!==void 0&&(t&&r in t||(n[r]=i));return n}function Tge(e){let t=e.headers?.get(`authorization`),n=oZ(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new E(`BAD_REQUEST`,{error_description:`Multiple access token transport methods are not allowed`,error:`invalid_request`});let i=n??(r?{scheme:`Bearer`,token:r}:void 0);return{authorization:i,token:i?.token}}async function Ege(e,t){let{authorization:n}=Tge(e);if(!n?.token)throw new E(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await k0(e,t,n.token);if(fZ(r)&&!e.request)throw new E(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await SZ({payload:r,authorization:n,proofJwt:n0(e),method:e.request?.method??`GET`,url:r0(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:rZ(e.context.internalAdapter)})}catch(e){throw xZ(e)?new E(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new E(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=wge(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||Ehe(t))?await t1(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await y1(o.id,l,t));let u=a?.length?await The(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:l??void 0,requestedClaims:i}):{},d=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...s0(u,s),...s0(d),sub:s.sub}}const Dge=Object.fromEntries(R1.map(e=>[e,void 0]));function c0(e){return dZ(e)?`DPoP`:`Bearer`}async function Oge(e,t){let n=e.body.grant_type;if(!V$(t).includes(n))throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return Yge(e,t);case`client_credentials`:return Xge(e,t);case`refresh_token`:return Zge(e,t);default:{let r=xhe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:kge(e,t,n)});throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function kge(e,t,n){return{getClient:n=>t1(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=g1(await _1(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 m1(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 x0(e,t,{...r,grantType:n})},hashToken:(e,n)=>o1(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>S0);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>S0);return i(e,t,n,r)}}}async function Age(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=q$(e.context).options,u=n?.id??r.clientId;return T$(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:Z$(i),client_id:r.clientId,azp:r.clientId,scope:a.join(` `),sid:o?.sid,iss:l?.jwt?.issuer??e.context.baseURL,iat:s,exp:c,jti:JH(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function jge(e,t){let n;n=t===`EdDSA`?`SHA-512`:t.endsWith(`384`)?`SHA-384`:t.endsWith(`512`)?`SHA-512`:`SHA-256`;let r=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(e)));return xP(r.slice(0,r.length/2))}async function Mge(e,t,n,r,i,a,o,s,c,l){let u=Math.floor(Date.now()/1e3),d=u+(t.idTokenExpiresIn??36e3),f=await y1(n.id,r,t),p=s==null?void 0:Math.floor(s.getTime()/1e3),m=A1(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:h1(r.metadata)}):void 0),h=t.disableJwtPlugin?void 0:q$(e.context).options,g=!t.disableJwtPlugin&&!h?.jwt?.sign?await w$(e,h):void 0,_=t.disableJwtPlugin?`HS256`:g?.alg??h?.jwks?.keyPairConfig?.alg,v=c?await jge(c,_):void 0,y=!!(r.enableEndSession||r.backchannelLogoutUri),b={...Dge,auth_time:p,acr:`0`,...m,at_hash:v,iss:h?.jwt?.issuer??e.context.baseURL,sub:f,aud:r.clientId,nonce:a,iat:u,exp:d,sid:y?o:void 0},x=A1(l);if(Object.assign(b,s0(x,b)),t.disableJwtPlugin&&!r.clientSecret)return;let S=t.disableJwtPlugin?await new cI(b).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await i1(e,t.storeClientSecret,r.clientSecret))):await T$(e,{options:h,payload:b,resolvedKey:g??void 0});if(S&&v&&h?.jwt?.sign){let e=bI(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 l0(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function u0(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new E(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function Nge(e,t,n,r,i,a,o,s,c,l,u,d){let f=a.iat??Math.floor(Date.now()/1e3),p=a?.exp??f+(t.accessTokenExpiresIn??3600),m=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():JH(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await o1(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 d0(e,t,n){let r=await e.context.adapter.findMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]});r.length&&await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,operator:`in`,value:r.map(e=>e.id)}]}),await e.context.adapter.deleteMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]})}async function Pge(e,t){let n=async n=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:`authorizationCodeId`,value:t}]})}catch(t){e.context.logger.error(`authorization code replay cleanup failed`,t)}};await n(`oauthAccessToken`),await n(`oauthRefreshToken`)}async function f0(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=s.iat??Math.floor(Date.now()/1e3),m=s?.exp??p+(t.refreshTokenExpiresIn??2592e3),h=t.generateRefreshToken?await t.generateRefreshToken():JH(32,`A-Z`,`a-z`),g=s?.sid,_={token:await o1(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 l0(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 l0(t,h,g)}}async function p0(e,t,n){let r=await J1(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 m0(e){throw new E(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Fge(e){let t=h1(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function h0(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=dZ(n.refreshToken?.confirmation),a=i??r,o=n0(e),s=Fge(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&m0(`DPoP proof header is required`);else try{return{jkt:(await yZ({proofJwt:o,method:`POST`,url:r0(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:rZ(e.context.internalAdapter)})).jkt}}catch(e){throw aZ(e)&&m0(e.message),e}}function g0(e){return e?[...new Set(e)].sort():void 0}function _0(e,t){let n=g0(e),r=g0(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function v0(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Ige(e,t){return v0(e)===v0(t)}function Lge(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.jkt==`string`&&t[`x5t#S256`]===void 0||typeof t[`x5t#S256`]==`string`&&t.jkt===void 0}function Rge(e){return e===`Bearer`||e===`DPoP`}function zge(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.access_token==`string`&&typeof t.expires_in==`number`&&typeof t.expires_at==`number`&&Rge(t.token_type)&&typeof t.scope==`string`&&(t.refresh_token===void 0||typeof t.refresh_token==`string`)&&(t.id_token===void 0||typeof t.id_token==`string`)}function Bge(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every(e=>typeof e==`string`)&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every(e=>typeof e==`string`))&&(n.confirmation===void 0||Lge(n.confirmation))&&zge(t.response)}function y0(e){let t=g0(e.requestedResources);return{effectiveScopes:g0(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function Vge(e,t){return _0(e.effectiveScopes,t.effectiveScopes)&&_0(e.requestedResources,t.requestedResources)&&Ige(e.confirmation,t.confirmation)}async function Hge(e,t){return RW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Uge(e,t){let n=await zW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(Bge(r))return r}function b0(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function Wge(e,t,n,r,i){(t.refreshTokenReuseInterval??0)<=0||await e.context.adapter.update({model:`oauthRefreshToken`,where:[{field:`id`,value:n.id}],update:{rotationReplayResponse:await Hge(e,{request:r,response:i})}})}async function Gge(e,t,n){if(b0(t)&&t.rotationReplayResponse)try{let r=await Uge(e,t.rotationReplayResponse);return!r||!Vge(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Kge(e,t,n){let r=Math.floor(Date.now()/1e3),i=await p0(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await h0(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return y0({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function qge(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function x0(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]?S$(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await p0(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&&d1(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,ee=a&&v.includes(`openid`),C=h1(r.metadata),te=ee&&a?{...await whe(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:C}),...n.idTokenClaims??{}}:void 0,ne=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:C,verificationValue:f}):void 0,w=g.refreshResources,T=n.confirmation??await h0(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),re=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],ie=x&&a&&!S?await f0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,w,T,re):void 0,ae=S?await B1({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:C,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[oe,se]=await Promise.all([S?Age(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ae,confirmation:T}):Nge(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,ie?.id,T,re),ie||(x&&a?f0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,w,T,re):void 0)]),ce=ee?await Mge(e,t,a,r,v,l,c,d,oe,te):void 0,le={...ne,...n.tokenResponse??{},access_token:oe,expires_in:y-p,expires_at:y,token_type:c0(T),refresh_token:se?.token,scope:v.join(` `),id_token:ce};if(u?.id&&se?.id)try{await Wge(e,t,u,y0({effectiveScopes:v,requestedResources:n.resources,confirmation:T}),le)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(le)}async function Jge(e,t,n,r,i,a){let o=await o1(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await Pge(e,o),new E(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=age.safeParse(c);if(!l.success)throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new E(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=X$(u.resource)??X$(u.query.resource),p=a??f;if(a&&f){let e=new Set(a),t=new Set(f);for(let n of e)if(!t.has(n))throw new E(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function Yge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=g1(await _1(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=X$(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 m1(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await Jge(e,t,o,n,c,u),v=m.query.scope?.split(` `);if(!v)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});if(f1(p,v),E1(p,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!f)throw new E(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new E(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let y=!!m.query?.code_challenge,b=!!s;if(y||b){if(y&&!b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await JY(s):void 0)!==m.query?.code_challenge)throw new E(`BAD_REQUEST`,{error_description:`code verification failed`,error:`invalid_grant`})}if(!m.userId)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let x=await e.context.internalAdapter.findUserById(m.userId);if(!x)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!S||S.expiresAt</* @__PURE__ */ new Date)throw new E(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let ee=m.authTime==null?Ahe(S):Y$(m.authTime),C=F1(m.query.claims,z1(t));return x0(e,t,{client:p,scopes:m.query.scope?.split(` `)??[],user:x,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:S.id,nonce:m.query?.nonce,authTime:ee,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:C,resources:h,originalResources:g})}async function Xge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=g1(await _1(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=X$(s);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await m1(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)||i0(t));if(t.length)throw new E(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],x0(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function Zge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=g1(await _1(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=X$(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 m1(e,t,n,r,void 0,i,`refresh_token`,a),d=await u0(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await s1(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(f1(u,m??p),f.revoked){if(b0(f)){let n=await Gge(e,f,await Kge(e,t,{client:u,refreshToken:f,scopes:m??p,resources:l??f.resources}));if(n)return qge(e,n);throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await d0(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:Y$(f.authTime);return x0(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 S0=/* @__PURE__ */ k$({introspectEndpoint:()=>j0,requireActiveAccessToken:()=>i_e,requireActiveAccessTokenWithClaims:()=>k0,validateAccessToken:()=>O0});const C0=`Invalid access token`,Qge=`Bearer error="invalid_token", error_description="${C0}"`;function w0(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function $ge(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function T0(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&pge(e,t,r,a)}async function e_e(e,t,n,r){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let i=q$(e.context),a=i.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await oI(n,hI(await zZ(n,{jwksFetch:a?.jwks?.remoteUrl?a.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(e))?.response,jwksCacheKey:i})),{issuer:s})).payload}catch(e){if(e instanceof cP||e instanceof mP)return{active:!1};throw e instanceof TypeError||J$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let l=c.aud;if(!await q1(e,t,l,[o])||!c.azp)return{active:!1};let u=await t1(e,t,c.azp);if(!u||u?.disabled||!await T0(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:$ge(l,o)}))return{active:!1};let d=c.sid;if(d){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:d}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=c0(c.cnf),c}async function t_e(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await s1(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 w0();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await t1(e,t,a.clientId),!s||s?.disabled||!await T0(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return w0();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 w0()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await q1(e,t,o,[u]))return w0();let d=o?[...o]:void 0;d?.length&&a.scopes?.includes(`openid`)&&(d.includes(u)||d.push(u));let f=o?.length?await mge(e,t,o):{},p=s?await B1({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:h1(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:f}):{},m=(t.disableJwtPlugin?void 0:q$(e.context))?.options;return{payload:{...p,active:!0,iss:m?.jwt?.issuer??e.context.baseURL,aud:Z$(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:c0(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function n_e(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await s1(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:q$(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:c0(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function E0(){return new O(`UNAUTHORIZED`,{error_description:C0,error:`invalid_token`},{"WWW-Authenticate":Qge})}function r_e(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function D0(e,t,n,r){try{return{payload:await e_e(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(e)}try{return await t_e(e,t,n,r)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw E0()}async function O0(e,t,n,r){return(await D0(e,t,n,r)).payload}async function i_e(e,t,n,r){let i=await O0(e,t,n,r);if(i.active)return i;throw E0()}async function k0(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await D0(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw E0()}async function A0(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 t1(e,t,i);if(!a)return n;let o=await y1(n.sub,a,t);return{...n,sub:o}}async function j0(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}=g1(await _1(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=sZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await m1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return A0(e,t,await O0(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 A0(e,t,await n_e(e,t,(await u0(t,n)).token,c.clientId),c)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(r_e(e))return{active:!1};throw e}throw e instanceof Error?(f.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(f.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}function M0(e){return e?.get(`sec-fetch-mode`)===`cors`}var a_e=/* @__PURE__ */ e({a:()=>B2,c:()=>d2,d:()=>t2,f:()=>$0,h:()=>e2,i:()=>o4,l:()=>l2,n:()=>e4,o:()=>R_e,r:()=>r4,s:()=>w2,t:()=>f4,u:()=>Z0});async function o_e(e,t,n){let r=await n4.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=z1(t),c=F1(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:F1(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:s4(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,f4(e,t))};let p=await zJ(e),m=v1(a.get(`prompt`)??``).has(`login`),h=m&&C1(p?.session.createdAt,r?.signedQueryIssuedAt);if(m&&!h)return e?.headers?.set(`accept`,`application/json`),e.query=S1(a),await n(e);let g=await b1(t,{user:p?.user,session:p?.session,scopes:u??o}),_=await x1(e,l,p?.user.id,g),v=Math.floor(Date.now()/1e3),y=a.getAll(`resource`),b={clientId:l,userId:p?.user.id,scopes:u??o,requestedUserInfoClaims:f,createdAt:/* @__PURE__ */ new Date(v*1e3),updatedAt:/* @__PURE__ */ new Date(v*1e3),resources:y.length?y:void 0,referenceId:g};if(_?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:_.id}],update:{resources:b.resources,scopes:b.scopes,requestedUserInfoClaims:b.requestedUserInfoClaims,updatedAt:/* @__PURE__ */ new Date(v*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...b,scopes:b.scopes}}),u&&a.set(`scope`,b.scopes.join(` `)),d!==void 0){let e=Xhe(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let x=w1(a,`consent`);return h&&(x=w1(x,`login`),x=T1(x)),e.query=S1(x),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id})}async function s_e(e,t){if(e.body.selected===!0)return await c_e(e,t);if(e.body.created===!0)return await l_e(e,t);if(e.body.postLogin===!0)return await u_e(e,t);throw new E(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function c_e(e,t){let n=(await n4.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=S1(w1(new URLSearchParams(n),`select_account`)),await t(e)}async function l_e(e,t){let n=(await n4.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=S1(w1(r,`create`)),await t(e)}async function u_e(e,t){let n=await n4.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=S1(i);let a=await zJ(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}async function d_e(e,t,n,r){return T$(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function f_e(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await SH(e.context.adapter),o=[{field:`sessionId`,value:r}],[s,c]=await Promise.all([n.findMany({model:`oauthAccessToken`,where:o}),n.findMany({model:`oauthRefreshToken`,where:o})]),l=/* @__PURE__ */ new Set;for(let e of s)l.add(e.clientId);for(let e of c)l.add(e.clientId);if(l.size===0)return null;let u=await n.findMany({model:`oauthClient`,where:[{field:`clientId`,operator:`in`,value:Array.from(l)}]}),d=s.filter(e=>!e.revoked).map(e=>e.id),f=c.filter(e=>!e.revoked&&!e.scopes?.includes(`offline_access`)).map(e=>e.id),p=t.disableJwtPlugin?[]:u.filter(e=>!!e.backchannelLogoutUri&&!e.disabled);return{accessTokenIds:d,refreshTokenIds:f,sessionId:r,targets:(await Promise.all(p.map(async e=>{try{return{client:e,sub:await y1(i,e,t)}}catch(t){return a.warn(`back-channel logout: unable to resolve subject for client ${e.clientId}`,t),null}}))).filter(e=>e!==null)}}catch(e){return a.error(`back-channel logout planning failed`,e),null}}async function p_e(e,t){let n=/* @__PURE__ */ new Date,r=await SH(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?r.updateMany({model:`oauthAccessToken`,where:[{field:`id`,operator:`in`,value:t.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),t.refreshTokenIds.length>0?r.updateMany({model:`oauthRefreshToken`,where:[{field:`id`,operator:`in`,value:t.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let t of i)t.status===`rejected`&&e.context.logger.error(`back-channel logout: token revocation update failed`,t.reason);t.targets.length>0&&await m_e(e,t)}async function m_e(e,t){let n=e.context.logger,r=q$(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 w$(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=JH(32,`a-z`,`A-Z`,`0-9`),d=await d_e(e,r,s,{iss:i,aud:c.clientId,sub:l,sid:t.sessionId,iat:a,exp:o,jti:u}),f=await fetch(c.backchannelLogoutUri,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:new URLSearchParams({logout_token:d}),signal:AbortSignal.timeout(5e3),redirect:`error`});f.status!==200&&f.status!==204&&n.warn(`back-channel logout to client ${c.clientId} returned ${f.status}`)}catch(e){n.warn(`back-channel logout to client ${c.clientId} failed`,e)}}))}function N0(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function P0(e){let t=e.request?.headers??e.headers;if(!t||M0(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 F0(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${N0(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 I0(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function h_e(e){try{return new URL(I0(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function L0(e){return F0(`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="${N0(I0(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function R0(e){return F0(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${N0(e)}`:`Logged out.`}</p></main>`)}function g_e(e,t){return F0(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${N0(e)}</p></main>`,t)}function z0(e,t,n,r){if(P0(e))return g_e(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new O(t,{error:n,error_description:r})}function B0(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function V0(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:h_e(e),sameSite:`lax`}}async function H0(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(B0(e),JSON.stringify(r),e.context.secret,V0(e,300))}async function __e(e){let t=await e.getSignedCookie(B0(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 U0(e){e.setCookie(B0(e),``,V0(e,0))}async function W0(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=`string`||t.length===0)return null;try{let n=await e.context.internalAdapter.findSession(t);return n?{session:n.session}:null}catch(t){throw e.context.logger.error(`Failed to read the current logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function v_e(e,t){try{return await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:t}]})}catch(t){throw e.context.logger.error(`Failed to read the hinted logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function G0(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 K0(e,t,n){try{return await t1(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 q0(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function y_e(e){if(typeof e.aud==`string`&&e.aud.length>0)return e.aud;if(typeof e.azp==`string`&&e.azp.length>0)return e.azp;let t=q0(e.aud);return t.length===1?t[0]:null}async function b_e(e,t,n,r){if(r)return K0(e,t,r);let i;try{i=xI(n)}catch{return null}let a=y_e(i);return a?K0(e,t,a):null}async function x_e(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await i1(e,t.storeClientSecret,r.clientSecret),{payload:o}=await UF(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=q$(e.context).options,{payload:r}=await UF(n,hI(await zZ(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==f4(e,t)||!q0(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 J0(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 Y0(e,t){return t.post_logout_redirect_uri?J0(e,t.post_logout_redirect_uri,t.state).invalid?{redirectInvalid:!0}:{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state===void 0?{}:{state:t.state}}:{}}async function S_e(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await K0(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:J0(r,n.postLogoutRedirectUri,n.state)}async function X0(e,t,n={}){return t?P0(e)?(await H0(e,t.session.id,n),L0(e)):z0(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):P0(e)?(await H0(e,void 0,n),L0(e)):z0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function C_e(e,t){let n=await __e(e),r=await W0(e);if(!n||n.expiresAt<=Date.now())return z0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await S_e(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?z0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await G0(e,r.session),lq(e),U0(e),i.uri?l4(e,i.uri):P0(e)?R0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(U0(e),i.uri?l4(e,i.uri):P0(e)?R0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):z0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function w_e(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await W0(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await K0(e,t,i.client_id);if(!r)return z0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return z0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return z0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=Y0(r,i)}return X0(e,a,n)}let o=await b_e(e,t,i.id_token_hint,i.client_id);if(!o)return a&&P0(e)?X0(e,a):z0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return z0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return z0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await x_e(e,t,i.id_token_hint,o);if(!s)return a&&P0(e)?X0(e,a,i.client_id?Y0(o,i):{}):z0(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await v_e(e,c),u=a?.session.id===c;if(a&&!u)return X0(e,a,Y0(o,i));let d=J0(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await G0(e,f),u&&lq(e),U0(e),d.uri?l4(e,d.uri):P0(e)?R0(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function T_e(e,t){return C_e(e,t)}function Z0(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:d4(t?.jwt?.issuer??r),authorization_endpoint:`${r}/oauth2/authorize`,token_endpoint:`${r}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${r}${t?.jwks?.jwksPath??`/jwks`}`,registration_endpoint:n?.dynamic_client_registration_supported?`${r}/oauth2/register`:void 0,introspection_endpoint:`${r}/oauth2/introspect`,revocation_endpoint:`${r}/oauth2/revoke`,response_types_supported:n?.grant_types_supported&&!n.grant_types_supported.includes(`authorization_code`)?[]:[`code`],response_modes_supported:[`query`],grant_types_supported:n?.grant_types_supported??[`authorization_code`,`client_credentials`,`refresh_token`],token_endpoint_auth_methods_supported:n?.token_endpoint_auth_methods_supported??[...n?.public_client_supported?[`none`]:[],`client_secret_basic`,`client_secret_post`,`private_key_jwt`],token_endpoint_auth_signing_alg_values_supported:[...iX],introspection_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],introspection_endpoint_auth_signing_alg_values_supported:[...iX],revocation_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],revocation_endpoint_auth_signing_alg_values_supported:[...iX],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...tZ],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function Q0(e,t){let n=t.disableJwtPlugin?void 0:q$(e.context).options,r=B$(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:Z0(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:V$(t),token_endpoint_auth_methods_supported:U$(t,{includeNone:i}),endpoint_auth_methods_supported:U$(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function $0(e,t){let{clientDiscoveries:n,authMetadata:r}=Q0(e,t);return G$(e,t,`oauth-authorization-server`,{...n1(n),...r})}function e2(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=Q0(e,t),o={...a,claims_supported:z1(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 G$(e,t,`openid-configuration`,{...n1(i),...o})}function t2(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 n2(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`,{...r2(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({...r2(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 r2(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?De(r.path):``;return{error:E_e(r,o,n),error_description:O_e(r,s)}}function E_e(e,t,n){return typeof t==`string`?t:D_e(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function D_e(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function O_e(e,t){if(!t)return e.message;if(e.code===`invalid_type`)return e.message.endsWith(`received undefined`)?`${t} is required`:e.message.endsWith(`received array`)?`${t} must not appear more than once`:`${t} must be a ${e.expected??`valid value`}`;if(e.code===`invalid_value`){let n=e.values;if(Array.isArray(n)&&n.length>0)return`${t} must be one of: ${n.join(`, `)}`}return`${t}: ${e.message}`}const k_e=e=>zq(async t=>{if(!e.allowPublicClientPrelogin)throw new E(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await $$(n,t.context.secret))throw new E(`UNAUTHORIZED`,{error:`invalid_signature`})}),i2={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},A_e=[`Ed25519`],j_e=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function a2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function o2(e,t){return typeof e[t]==`string`&&e[t].length>0}function s2(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(i2,e)}function c2(e){return A_e.some(t=>t===e)}function M_e(e){switch(e.kty){case`RSA`:return o2(e,`n`)&&o2(e,`e`);case`EC`:return s2(e.crv)&&o2(e,`x`)&&o2(e,`y`);case`OKP`:return c2(e.crv)&&o2(e,`x`);default:return!1}}function N_e(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!iX.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return s2(e.crv)&&i2[e.crv]===e.alg;case`OKP`:return c2(e.crv)&&e.alg===`EdDSA`;default:return!1}}function l2(e){let t=a2(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(!a2(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||j_e.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!M_e(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!N_e(e))return{valid:!1,error:`jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve`}}return{valid:!0,jwks:{keys:t}}}function u2(e){let t=l2(e);if(!t.valid)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}const P_e=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),F_e=/* @__PURE__ */ `client_id.client_secret.client_secret_expires_at.scope.user_id.client_id_issued_at.client_name.client_uri.logo_uri.contacts.tos_uri.policy_uri.jwks.jwks_uri.software_id.software_version.software_statement.redirect_uris.post_logout_redirect_uris.backchannel_logout_uri.backchannel_logout_session_required.token_endpoint_auth_method.grant_types.response_types.application_type.disabled.skip_consent.enable_end_session.require_pkce.dpop_bound_access_tokens.subject_type.reference_id`.split(`.`),I_e=/* @__PURE__ */ new Set([...P_e,...F_e,`public`,`type`,`resources`,`client_credentials_scopes`]),L_e=/* @__PURE__ */ new Set(/* @__PURE__ */ `disabled.client_secret.client_secret_expires_at.client_id_issued_at.skip_consent.enable_end_session.require_pkce.reference_id.user_id.resources.clientSecret.clientDiscoveryId.skipConsent.enableEndSession.requirePKCE.referenceId.userId.clientId.applicationType.tokenEndpointAuthMethod.redirectUris.postLogoutRedirectUris.grantTypes.responseTypes.scopes.expiresAt.createdAt.updatedAt.softwareId.softwareVersion.softwareStatement.backchannelLogoutUri.backchannelLogoutSessionRequired.jwksUri.dpopBoundAccessTokens.subjectType`.split(`.`));function d2(e){return L_e.has(e)}function f2(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!I_e.has(e)))}async function p2(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 m2(e,t,n,r,i){if(!t)throw new E(`UNAUTHORIZED`);if(!e.headers)throw new E(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new E(`UNAUTHORIZED`)}var R_e=/* @__PURE__ */ k$({consumeClientAssertion:()=>w2,isPrivateHostname:()=>x2,verifyClientAssertion:()=>T2});const h2=/* @__PURE__ */ new WeakMap,g2=65536,z_e=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function _2(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 v2(e){let t=h2.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return h2.set(e,n),n}function y2(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const b2=[...iX];function x2(e){return!CY(e)}function B_e(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(x2(r.hostname))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not point to a private or reserved address`,error:`invalid_client`});if(!(n&&r.origin===n)&&!e.context.isTrustedOrigin(r.href))throw new O(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function V_e(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function H_e(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>g2)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>g2)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 S2(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);try{let r=await t(e,{signal:n.signal,headers:{accept:`application/json`},redirect:`error`});if(r.redirected)throw Error(`JWKS fetch redirected`);if(r.status!==200)throw Error(`JWKS fetch returned ${r.status}`);let i=r.headers.get(`content-type`);if(!i||!z_e.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await H_e(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=l2(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function C2(){return new O(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function U_e(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new O(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?B$(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new O(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});B_e(e,n.jwksUri,n.clientDiscoveryId?V_e(n.clientId):void 0);let i=Date.now(),a=y2(n),o=v2(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await S2(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw C2()}if(!c.valid)throw C2();return _2(o,a,c.jwks,i),c.jwks}async function W_e(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?B$(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await S2(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(_2(v2(e),y2(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function w2(e,t,n){let{namespace:r,payload:i,expectedAudience:a}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud==null?[]:[i.aud]).includes(a))throw new O(`BAD_REQUEST`,{error_description:`client assertion aud does not match the endpoint`,error:`invalid_client`});let o=t.assertionMaxLifetime??300,s=Math.floor(Date.now()/1e3);if(typeof i.exp!=`number`)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new O(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion exp is too far in the future (max ${o}s)`,error:`invalid_client`});if(typeof i.iat==`number`&&s-i.iat>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion iat is too far in the past (max ${o}s)`,error:`invalid_client`});if(typeof i.jti!=`string`||i.jti.length===0)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await MU(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=xe(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:`oauthClientAssertion`,data:{id:l,expiresAt:/* @__PURE__ */ new Date(i.exp*1e3)},forceAllowId:!0})}catch(t){let n=!1;try{n=!!await e.context.adapter.findOne({model:`oauthClientAssertion`,where:[{field:`id`,value:l}]})}catch{}throw n?new O(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function T2(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=bI(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!b2.includes(s.alg))throw new O(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=xI(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 t1(e,t,l);if(!u)throw new O(`BAD_REQUEST`,{error_description:`client not found`,error:`invalid_client`});if(u.disabled)throw new O(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(u.tokenEndpointAuthMethod!==`private_key_jwt`)throw new O(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});o?.assertClient?.(u);let d=await U_e(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=f4(e,t),m=o?.endpointAudienceOnly?[f]:[.../* @__PURE__ */ new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:b2},g;try{({payload:g}=await oI(n,hI(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await W_e(t,u);if(e)try{({payload:g}=await oI(n,hI(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 w2(e,t,{namespace:`private_key_jwt:${l}`,payload:g,expectedAudience:_}),{clientId:l,client:u}}function E2(e,t,n){return new O(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...Iq})}async function G_e(e,t,n){let r=e.headers,i;try{i=Dhe(r?.get(`authorization`))}catch{throw E2(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw E2(`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 E2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const K_e=[`authorization_code`];function D2(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function O2(e){let t=e.grant_types??[...K_e];if(t.length>0)return t;throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function q_e(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function k2(e,t){let n=new Set(V$(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 A2(e,t=`web`){let n=O2(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??`client_secret_basic`,application_type:e.application_type??(t===null?void 0:t),grant_types:n,response_types:q_e(e,n)}}function J_e(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function Y_e(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function j2(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>Y_e(e)||N2(e))?`native`:`web`:n}function M2(e){throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function X_e(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let n=t.slice(t.lastIndexOf(`@`)+1);if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e<0?null:n.slice(0,e+1).toLowerCase()}return(n.split(`:`)[0]??``).toLowerCase()}function N2(e){let t=X_e(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function Z_e(e,t){let n=/* @__PURE__ */ new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function Q_e(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of i){let r=await Q1(e,t,n);if(!r)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function $_e(e,t){let n;try{n=new URL(e)}catch{M2(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&M2(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&M2(`redirect URI localhost must not include trailing dots: ${e}`);let a=xY(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&M2(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&M2(`native clients must not use https loopback redirect URIs: ${e}`):r?N2(e)||M2(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):O1(n)||M2(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}async function eve(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await zJ(e),i=r?void 0:await G_e(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new E(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...Iq});let o=n.grant_types?.length?k2(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 p2(e,r,t,`create`);let u=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),d=await z2(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 P2(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=A2(e,r?null:n?.registrationSource===`dynamic`?j2(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(U$(t,{includeNone:!0})).has(a))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported token_endpoint_auth_method ${a}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=`boolean`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`dpop_bound_access_tokens must be a boolean`});let o=i.grant_types??[],s=i.response_types,c=i.application_type;if(c!==void 0&&c!==`web`&&c!==`native`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`application_type must be web or native`});if(o.includes(`authorization_code`)&&(!i.redirect_uris||i.redirect_uris.length===0))throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:`Redirect URIs are required for authorization_code and implicit grant types`});for(let e of i.redirect_uris??[])$_e(e,c??(r?`native`:`web`));if(r)k2(t,o);else{let e=new Set(V$(t));for(let t of o)if(!e.has(t))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${t}`})}if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'authorization_code' grant type is used, 'code' response type must be included`});if(!o.includes(`authorization_code`)&&s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'code' response type is used, 'authorization_code' grant type must be included`});if(i.subject_type!==void 0){if(i.subject_type!==`public`&&i.subject_type!==`pairwise`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some(J_e))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients cannot use custom-scheme redirect URIs that include a host`});if(i.subject_type===`pairwise`&&i.redirect_uris&&i.redirect_uris.length>1&&new Set(i.redirect_uris.map(e=>new URL(e).host)).size>1)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host.`})}let l=(i?.scope)?.split(` `).filter(e=>e.length),u=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,d=u?D2(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(x2(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&&u2(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(x2(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 F2=Symbol(`client-registration-collision`);function I2(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[F2]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function L2(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=A2(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?j2(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=W$(t,i.token_endpoint_auth_method);await P2(i,t,{registrationSource:n.registrationSource,ctx:e});let c=n.clientId??t.generateClientId?.()??JH(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`),u=l?await a1(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:D2(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=U2({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?S$(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:u,client_id_issued_at:p,require_pkce:f,user_id:g?.referenceId?void 0:g?.userId,reference_id:g?.referenceId});_.clientCredentialsScopes=n.registrationSource===`clientMetadataDocument`?n.existingClient?.clientCredentialsScopes??[]:n.registrationSource===`managed`?n.clientCredentialsScopes??[]:[],_.clientDiscoveryId=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&Z_e(t,v);let y=await Q_e(e,t,v),b=t.schema?.oauthClient?.modelName??`oauthClient`,x=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,S=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,ee=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,C=await wH(e.context.adapter,async()=>{let t=await SH(e.context.adapter),r,i=!1;if(S){let e=await t.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:ee}],update:{..._,disabled:S.disabled,skipConsent:S.skipConsent,enableEndSession:S.enableEndSession,createdAt:S.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!e)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=e}else{try{r=await t.create({model:b,data:{..._,createdAt:/* @__PURE__ */ new Date(p*1e3),updatedAt:/* @__PURE__ */ new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&V2(e)?{[F2]:!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`&&V2(t)?{[F2]:!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 R2(e,t){let n=W2({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function tve(e,t){return{...R2(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function z2(e,t,n){return R2(await L2(e,t,n),t)}async function nve(e,t,n){return tve(await L2(e,t,n),t)}function rve(e,t){if(e&&e.clientDiscoveryId!==t)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}async function B2(e,t,n){if(rve(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Documents cannot register a back-channel logout target`});if((n.metadata.token_endpoint_auth_method??`none`)!==`none`&&n.metadata.token_endpoint_auth_method!==`private_key_jwt`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Document clients cannot use a shared secret`});let r={...n,metadata:{...n.metadata,token_endpoint_auth_method:n.metadata.token_endpoint_auth_method??`none`,client_secret:void 0,client_secret_expires_at:void 0},registrationSource:`clientMetadataDocument`};try{return await L2(e,t,r)}catch(i){if(!I2(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 L2(e,t,{...r,existingClient:s})}catch(e){throw I2(e)?e.cause:e}}}function V2(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 H2(e,t,n){let r=await zJ(e);if(await p2(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?a0(a??[]):[];o0(s,O2(o),o.token_endpoint_auth_method,t),s.length>0&&await p2(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await m2(e,r,t,`link`,n);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s,...c?{requestedResources:c}:{}},u=n?.admin?await nve(e,t,l):await z2(e,t,l);return e.setStatus(201),e.json(u)}function U2(e){let{client_id:t,client_secret:n,client_secret_expires_at:r,scope:i,user_id:a,client_id_issued_at:o,client_name:s,client_uri:c,logo_uri:l,contacts:u,tos_uri:d,policy_uri:f,jwks:p,jwks_uri:m,software_id:h,software_version:g,software_statement:_,redirect_uris:v,post_logout_redirect_uris:y,backchannel_logout_uri:b,backchannel_logout_session_required:x,token_endpoint_auth_method:S,grant_types:ee,response_types:C,application_type:te,disabled:ne,skip_consent:w,enable_end_session:T,require_pkce:re,dpop_bound_access_tokens:ie,subject_type:ae,reference_id:oe,metadata:se}=e,ce=r?/* @__PURE__ */ new Date(Number(r)*1e3):void 0,le=o?/* @__PURE__ */ new Date(o*1e3):void 0,ue=i?.split(` `),de=f2(se??{}),fe=de&&Object.keys(de).length?JSON.stringify(de):void 0;return{clientId:t,clientSecret:n,disabled:ne,scopes:ue,userId:a,createdAt:le,expiresAt:ce,name:s,uri:c,icon:l,contacts:u,tos:d,policy:f,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:te,skipConsent:w,enableEndSession:T,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:fe}}function W2(e){let{clientId:t,clientSecret:n,disabled:r,scopes:i,userId:a,createdAt:o,updatedAt:s,expiresAt:c,name:l,uri:u,icon:d,contacts:f,tos:p,policy:m,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,applicationType:te,jwks:ne,jwksUri:w,skipConsent:T,enableEndSession:re,requirePKCE:ie,dpopBoundAccessTokens:ae,subjectType:oe,referenceId:se,metadata:ce}=e,le=c?Math.round(new Date(c).getTime()/1e3):void 0,ue=o?Math.round(new Date(o).getTime()/1e3):void 0,de=i?.join(` `);return{...f2(h1(ce)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?le??0:void 0,scope:de??void 0,user_id:a??void 0,client_id_issued_at:ue??void 0,client_name:l??void 0,client_uri:u??void 0,logo_uri:d??void 0,contacts:f??void 0,tos_uri:p??void 0,policy_uri:m??void 0,jwks:ne?JSON.parse(ne):void 0,jwks_uri:w??void 0,software_id:h??void 0,software_version:g??void 0,software_statement:_??void 0,redirect_uris:v??[],post_logout_redirect_uris:y??void 0,backchannel_logout_uri:b??void 0,backchannel_logout_session_required:x??void 0,token_endpoint_auth_method:S??void 0,grant_types:ee??void 0,response_types:C??void 0,application_type:te??void 0,disabled:r??void 0,skip_consent:T??void 0,enable_end_session:re??void 0,require_pkce:ie??void 0,dpop_bound_access_tokens:ae??void 0,subject_type:oe??void 0,reference_id:se??void 0}}async function ive(e,t){let n=await zJ(e);if(await p2(e,n,t,`read`,e.query.client_id),!n)throw new E(`UNAUTHORIZED`);let r=await t1(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=W2(r);return i.client_secret=void 0,i}async function G2(e,t,n){let r=await t1(e,t,n);if(!r||r.disabled)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return W2({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function ave(e,t){let n=await zJ(e);if(await p2(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=W2(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=W2(e);return t.client_secret=void 0,t}):null);throw new E(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function ove(e,t){let n=await zJ(e);if(await p2(e,n,t,`delete`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;e1(t,r);let i=await t1(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 K2(e,t,n){let r=await zJ(e);if(await p2(e,r,t,`update`,e.body.client_id),!r)throw new E(`UNAUTHORIZED`);let i=e.body.client_id;e1(t,i);let a=await t1(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 p2(e,r,t,`configure-client-credentials-scopes`,i),Object.keys(s).length===0&&o===void 0){let e=W2(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:a0(o);f!==void 0&&(o0(f,u,d,t),f.length>0&&!l&&await p2(e,r,t,`configure-client-credentials-scopes`,i)),await P2({...W2(a),...s},t,{ctx:e});let p={...U2(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 a1(e,t,t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`))));let m=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...p,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!m)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let h=W2(m);return h.client_secret=void 0,n?.admin?{...h,client_credentials_scopes:[...m.clientCredentialsScopes??[]]}:h}async function sve(e,t){let n=await zJ(e);if(await p2(e,n,t,`rotate`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;e1(t,r);let i=await t1(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new E(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`),o=a?await a1(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 W2({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function cve(e,t){if(!t.allowClientKeyRotation)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;u2(n.jwks);let{client:r}=await T2(e,t,n.client_assertion,n.client_assertion_type,void 0,r0({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>lve(t,e)});if(!await e.context.adapter.incrementOne({model:`oauthClient`,where:[{field:`clientId`,value:r.clientId},{field:`jwks`,value:r.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:/* @__PURE__ */ new Date}}))throw new E(`CONFLICT`,{error:`invalid_request`,error_description:`client keys changed while rotating; retry with a fresh client assertion`});return{client_id:r.clientId,jwks:n.jwks}}function lve(e,t){if(e1(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 q2=k().trim().min(1),J2=Le(k().trim().min(1)).min(1),uve=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:A({redirect_uris:Le(k1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Le(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:Le(k1).min(1).optional(),backchannel_logout_uri:k1.optional(),backchannel_logout_session_required:Ge().optional(),token_endpoint_auth_method:q2.optional(),application_type:Je([`web`,`native`]).optional(),jwks:H1.optional(),jwks_uri:k().optional(),grant_types:J2.optional(),client_credentials_scopes:Le(k().trim().min(1)).optional(),resources:Le(V1).optional(),response_types:Le(Je([`code`])).optional(),client_secret_expires_at:Oe([k(),Fe()]).optional().default(0),skip_consent:Ge().optional(),enable_end_session:Ge().optional(),require_pkce:Ge().optional(),dpop_bound_access_tokens:Ge().optional(),subject_type:Je([`public`,`pairwise`]).optional(),metadata:Ie(k(),et()).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=>H2(t,e,{admin:!0})),dve=e=>X(`/oauth2/create-client`,{method:`POST`,use:[VJ],body:A({redirect_uris:Le(k1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Le(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:Le(k1).min(1).optional(),backchannel_logout_uri:k1.optional(),backchannel_logout_session_required:Ge().optional(),token_endpoint_auth_method:q2.optional(),application_type:Je([`web`,`native`]).optional(),jwks:H1.optional(),jwks_uri:k().optional(),grant_types:J2.optional(),response_types:Le(Je([`code`])).optional(),dpop_bound_access_tokens:Ge().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=>H2(t,e)),fve=e=>X(`/oauth2/get-client`,{method:`GET`,use:[VJ],query:A({client_id:k()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>ive(t,e)),pve=e=>X(`/oauth2/public-client`,{method:`GET`,use:[VJ],query:A({client_id:k()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return G2(t,e,n)}),mve=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[k_e(e)],body:A({client_id:k(),oauth_query:k().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return G2(t,e,n)}),hve=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[VJ],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>ave(t,e)),gve=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:A({client_id:k(),update:A({redirect_uris:Le(k1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Le(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:Le(k1).min(1).optional(),backchannel_logout_uri:k1.optional(),backchannel_logout_session_required:Ge().optional(),application_type:Je([`web`,`native`]).optional(),grant_types:J2.optional(),client_credentials_scopes:Le(k().trim().min(1)).optional(),response_types:Le(Je([`code`])).optional(),client_secret_expires_at:Oe([k(),Fe()]).optional(),skip_consent:Ge().optional(),enable_end_session:Ge().optional(),disabled:Ge().optional(),dpop_bound_access_tokens:Ge().optional(),metadata:Ie(k(),et()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>K2(t,e,{admin:!0})),_ve=e=>X(`/oauth2/update-client`,{method:`POST`,use:[VJ],body:A({client_id:k(),update:A({redirect_uris:Le(k1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Le(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:Le(k1).min(1).optional(),backchannel_logout_uri:k1.optional(),backchannel_logout_session_required:Ge().optional(),application_type:Je([`web`,`native`]).optional(),grant_types:J2.optional(),response_types:Le(Je([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>K2(t,e)),vve=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[VJ],body:A({client_id:k()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>sve(t,e)),yve=e=>n2(`/oauth2/client/rotate-keys`,{method:`POST`,body:A({client_assertion:k(),client_assertion_type:k(),jwks:H1}),errorCodesByField:{client_assertion:`invalid_client`,client_assertion_type:`invalid_client`,jwks:`invalid_client_metadata`},metadata:{noStore:!0,openapi:{description:`Replaces the signing keys of a private_key_jwt client. The request is authenticated by a client assertion signed with one of the client's current keys and addressed to this endpoint. Keys left out of the new set stop verifying at once.`}}},async t=>cve(t,e)),bve=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[VJ],body:A({client_id:k()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>ove(t,e));async function Y2(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function xve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Y2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);return i}async function Sve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Cve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Y2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function wve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Y2(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 t1(e,t,i.clientId);if(!a)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,c=s.scopes;if(c&&!c.every(e=>o?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let l=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:/* @__PURE__ */ new Date(l*1e3)}})}const Tve=e=>X(`/oauth2/get-consent`,{method:`GET`,query:A({id:k()}),use:[VJ],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>xve(t,e)),Eve=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[VJ],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Sve(t,e)),Dve=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[VJ],body:A({id:k(),update:A({scopes:Le(k())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>wve(t,e)),Ove=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[VJ],body:A({id:k()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Cve(t,e)),X2=e=>e.schema?.oauthResource?.modelName??`oauthResource`,Z2=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,kve=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function Q2(e){try{return decodeURIComponent(e)}catch{return e}}function Ave(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function jve(e,t){await m2(e,await zJ(e),t,`create`);let n=e.body;if(!n?.identifier)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await cge(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:X2(t),data:Ave(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return Z1(i.identifier),e.json(i,{status:201})}async function Mve(e,t){await m2(e,await zJ(e),t,`list`);let n=await e.context.adapter.findMany({model:X2(t)});return e.json(n??[])}async function Nve(e,t){let n=Q2(e.params.identifier);await m2(e,await zJ(e),t,`read`,n);let r=await e.context.adapter.findOne({model:X2(t),where:[{field:`identifier`,value:n}]});if(!r)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function Pve(e,t){let n=Q2(e.params.identifier);if(await m2(e,await zJ(e),t,`update`,n),!await e.context.adapter.findOne({model:X2(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:X2(t),where:[{field:`identifier`,value:n}],update:r}),Z1(n);let i=await e.context.adapter.findOne({model:X2(t),where:[{field:`identifier`,value:n}]});if(!i)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function Fve(e,t){let n=Q2(e.params.identifier);if(await m2(e,await zJ(e),t,`delete`,n),!await e.context.adapter.findOne({model:X2(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:X2(t),where:[{field:`identifier`,value:n}]}),Z1(n),e.json({deleted:!0})}async function Ive(e,t){let n=await zJ(e),r=Q2(e.params.identifier),i=Q2(e.params.client_id);if(await m2(e,n,t,`link`,r),!await e.context.adapter.findOne({model:X2(t),where:[{field:`identifier`,value:r}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:kve(t),where:[{field:`clientId`,value:i}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:Z2(t),data:{clientId:i,resourceId:r,createdAt:/* @__PURE__ */ new Date}})}catch(t){let n=t instanceof Error?t.message:String(t);if(/unique|duplicate|UNIQUE/i.test(n))return e.json({linked:!0,alreadyLinked:!0});throw t}return e.json({linked:!0})}async function Lve(e,t){let n=await zJ(e),r=Q2(e.params.identifier),i=Q2(e.params.client_id);return await m2(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:Z2(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const $2=A({identifier:k().min(1).optional(),name:k().optional(),accessTokenTtl:Fe().int().positive().nullable().optional(),refreshTokenTtl:Fe().int().positive().nullable().optional(),signingAlgorithm:Je(G1).nullable().optional(),signingKeyId:k().nullable().optional(),allowedScopes:Le(k()).nullable().optional(),customClaims:Ie(k(),et()).nullable().optional(),dpopBoundAccessTokensRequired:Ge().optional(),disabled:Ge().optional(),metadata:Ie(k(),et()).nullable().optional()}),Rve=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:$2.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>jve(t,e)),zve=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Mve(t,e)),Bve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Nve(t,e)),Vve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:$2,metadata:{SERVER_ONLY:!0}},async t=>Pve(t,e)),Hve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Fve(t,e)),Uve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>Ive(t,e)),Wve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Lve(t,e));async function Gve(e,t,n){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let r=q$(e.context),i=r.options,a;try{a=(await oI(n,hI(await zZ(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL})).payload}catch(e){if(e instanceof cP||e instanceof mP)return null;throw e instanceof TypeError||J$(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 q1(e,t,a.aud,[o]))return null;throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function Kve(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await s1(t.storeTokens,i,`access_token`)}]});if(!a)throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`});if(!a.clientId||a.clientId!==r)return null;a.id?await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`id`,value:a.id}]}):await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`token`,value:a.token}]})}async function qve(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await s1(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 d0(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 d0(e,r,i.userId),new O(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,value:i.id}]})}async function Jve(e,t,n,r){try{return await Gve(e,t,r)}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await Kve(e,t,r,n)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new O(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function Yve(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=g1(await _1(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=sZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await m1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await Jve(e,t,c.clientId,n)}catch(e){if(e instanceof O){if(r===`access_token`||e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return await qve(e,t,(await u0(t,n)).token,c.clientId)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(f.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(f.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}const Xve={oauthClient:{modelName:`oauthClient`,fields:{clientId:{type:`string`,unique:!0,required:!0},clientSecret:{type:`string`,required:!1},clientDiscoveryId:{type:`string`,required:!1},disabled:{type:`boolean`,defaultValue:!1,required:!1},skipConsent:{type:`boolean`,required:!1},enableEndSession:{type:`boolean`,required:!1},subjectType:{type:`string`,required:!1},scopes:{type:`string[]`,required:!1},clientCredentialsScopes:{type:`string[]`,required:!1,defaultValue:[]},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},name:{type:`string`,required:!1},uri:{type:`string`,required:!1},icon:{type:`string`,required:!1},contacts:{type:`string[]`,required:!1},tos:{type:`string`,required:!1},policy:{type:`string`,required:!1},softwareId:{type:`string`,required:!1},softwareVersion:{type:`string`,required:!1},softwareStatement:{type:`string`,required:!1},redirectUris:{type:`string[]`,required:!0},postLogoutRedirectUris:{type:`string[]`,required:!1},backchannelLogoutUri:{type:`string`,required:!1},backchannelLogoutSessionRequired:{type:`boolean`,required:!1},tokenEndpointAuthMethod:{type:`string`,required:!1},applicationType:{type:`string`,required:!1},jwks:{type:`string`,required:!1},jwksUri:{type:`string`,required:!1},grantTypes:{type:`string[]`,required:!1},responseTypes:{type:`string[]`,required:!1},requirePKCE:{type:`boolean`,required:!1},dpopBoundAccessTokens:{type:`boolean`,required:!1,defaultValue:!1},referenceId:{type:`string`,required:!1},metadata:{type:`json`,required:!1}}},oauthResource:{modelName:`oauthResource`,fields:{identifier:{type:`string`,required:!0,unique:!0},name:{type:`string`,required:!0},accessTokenTtl:{type:`number`,required:!1},refreshTokenTtl:{type:`number`,required:!1},signingAlgorithm:{type:`string`,required:!1},signingKeyId:{type:`string`,required:!1},allowedScopes:{type:`string[]`,required:!1},customClaims:{type:`json`,required:!1},dpopBoundAccessTokensRequired:{type:`boolean`,required:!1,defaultValue:!1},disabled:{type:`boolean`,required:!1,defaultValue:!1},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},policyVersion:{type:`number`,required:!1,defaultValue:1},metadata:{type:`json`,required:!1}}},oauthClientResource:{modelName:`oauthClientResource`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`,onDelete:`cascade`},index:!0},resourceId:{type:`string`,required:!0,references:{model:`oauthResource`,field:`identifier`,onDelete:`cascade`},index:!0},metadata:{type:`json`,required:!1},createdAt:{type:`date`,required:!1}},indexes:[{fields:[`clientId`,`resourceId`],unique:!0}]},oauthRefreshToken:{fields:{token:{type:`string`,required:!0,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!0,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},rotatedAt:{type:`date`,required:!1},rotationReplayResponse:{type:`string`,required:!1},rotationReplayExpiresAt:{type:`date`,required:!1},authTime:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthAccessToken:{modelName:`oauthAccessToken`,fields:{token:{type:`string`,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},refreshId:{type:`string`,required:!1,references:{model:`oauthRefreshToken`,field:`id`},index:!0},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthConsent:{modelName:`oauthConsent`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},scopes:{type:`string[]`,required:!0},createdAt:{type:`date`},updatedAt:{type:`date`}}},oauthClientAssertion:{modelName:`oauthClientAssertion`,fields:{expiresAt:{type:`date`,required:!0}}}},e4=[`openid`,`profile`,`email`,`offline_access`],t4=A({id_token_hint:k().optional(),client_id:k().optional(),post_logout_redirect_uri:k1.optional(),state:k().optional()}),n4=yH(()=>null),r4=n4.get,i4=/* @__PURE__ */ new WeakMap,a4=`signedQueryIssuedAtMs`;function Zve(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):void 0;if(!(!t||!Number.isFinite(t)||t<=0))return new Date(t)}const o4=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??e4).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`,...R1.filter(e=>n.has(L1[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(R$(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:q$(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=t2(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(e2(s,a))}:{response:f($0(s,a))};if(d)return{response:f(e2(s,a))}},s=n2(`/oauth2/authorize`,{method:[`GET`,`POST`],body:A({}).passthrough(),redirectOnError:_4(a),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body`,parameters:[{name:`response_type`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 response type (e.g., 'code')`},{name:`client_id`,in:`query`,required:!0,schema:{type:`string`},description:`OAuth 2.1 client ID`},{name:`redirect_uri`,in:`query`,required:!1,schema:{type:`string`,format:`uri`},description:`OAuth 2.1 redirect URI`},{name:`scope`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 scopes (space-separated)`},{name:`state`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 state parameter`},{name:`request_uri`,in:`query`,required:!1,schema:{type:`string`},description:`Pushed Authorization Request URI referencing stored parameters`},{name:`code_challenge`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge`},{name:`code_challenge_method`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge method`},{name:`nonce`,in:`query`,required:!1,schema:{type:`string`},description:`OpenID Connect nonce`},{name:`max_age`,in:`query`,required:!1,schema:{type:`integer`,minimum:0},description:`Maximum authentication age in seconds; forces re-authentication when exceeded`},{name:`resource`,in:`query`,required:!1,schema:{type:`array`,items:{type:`string`}},description:`Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings.`},{name:`prompt`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth2 prompt parameter`}],responses:{302:{description:`Redirect to client with code or error`,headers:{Location:{description:`Redirect URI with code or error`,schema:{type:`string`,format:`uri`}}}},400:{description:`Invalid request`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},state:{type:`string`}},required:[`error`]}}}}}}}},async e=>aye(e,a,e.authorizeSettings??{isAuthorize:!0})),c=(e,t)=>SQ(s,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.10`,options:a,onRequest:o,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new D("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(a.allowClientKeyRotation){let t=e.adapter.id===`memory`?`the memory adapter`:e.options.advanced?.database?.generateId===`serial`?'`advanced.database.generateId: "serial"`':void 0;if(t)throw new D(`\`allowClientKeyRotation\` requires single-use client assertions, which ${t} does not enforce`)}if(await t0(e,a).catch(t=>yge(e,t)),Sge(a),!a.disableJwtPlugin){let t=q$(e)?.options,n=t?.jwt?.issuer??e.baseURL,r=t?.jwt?.issuer==null&&typeof e.options.baseURL==`object`&&e.options.baseURL!==null&&`allowedHosts`in e.options.baseURL;try{new URL(n)}catch(e){if(!r||n!==``)throw e}}return{options:{databaseHooks:{session:{delete:{async before(e,t){if(!t)return;let n=await f_e(t,a,{sessionId:e.id,userId:e.userId});if(!n)return;let r=i4.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),i4.set(t,r)},async after(e,t){if(!t)return;let n=i4.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&i4.delete(t),!r)return;let i=p_e(t,r).catch(e=>{t.context.logger.error(`Back-channel logout failed after session deletion`,e)});await t.context.runInBackgroundOrAwait(i)}}}}}}},hooks:{before:[{matcher(e){return e.body?.oauth_query},handler:zq(async e=>{let t=e.body.oauth_query;if(!await $$(t,e.context.secret))throw new E(`BAD_REQUEST`,{error:`invalid_signature`});let n=dhe(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(A$),r.delete(j$),await n4.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Aq({query:r.toString(),...n?{[a4]:n.getTime()}:{}})})}],after:[{matcher(e){return xG(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:zq(async e=>{let t=xG(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await n4.get(),r=(await Dq())?.serverContext,i=n?.query??r?.query;if(!i)return;let a=new URLSearchParams(i),o=await e.context.internalAdapter.findSession(t);if(!o)return;e.context.session=o;let s=e.request?.headers?.get(`sec-fetch-mode`)?.toLowerCase(),l=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(l.includes(`text/html`)||l.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let u=n?.signedQueryIssuedAt??Zve(r?.[a4]),d=w1(a,`login`);return C1(o.session.createdAt,u)&&(d=T1(d)),e.query=S1(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`)?e2(e,a):$0(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 e2(e,a)}),oauth2Authorize:s,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:A({accept:Ge().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:P1.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[VJ],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>o_e(e,a,c)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:A({selected:Ge().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:Ge().optional().meta({description:`Confirms an account was registered`}),postLogin:Ge().optional().meta({description:`Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[VJ],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>s_e(e,c)),oauth2Token:n2(`/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:k1.optional(),refresh_token:k().optional(),resource:Oe([V1,Le(V1).min(1)]).optional(),scope:k().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:`invalid_request`,invalid:`unsupported_grant_type`},resource:{invalid:`invalid_target`}},metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Obtain an OAuth2.1 access token`,parameters:[{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens`}],requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{grant_type:{type:`string`,description:`OAuth2 grant type`},client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},code:{type:`string`,description:`Authorization code (for authorization_code grant)`},code_verifier:{type:`string`,description:`PKCE code verifier (for authorization_code grant)`},redirect_uri:{type:`string`,format:`uri`,description:`Redirect URI (for authorization_code grant)`},refresh_token:{type:`string`,description:`Refresh token (for refresh_token grant)`},resource:{oneOf:[{type:`string`,description:`Single resource (URL)`},{type:`array`,items:{type:`string`},description:`Multiple resources (URLs)`}],description:`Requested protected resource(s) for the access token`},scope:{type:`string`,description:`Requested scopes (for client_credentials grant)`}},required:[`grant_type`]}}}},responses:{200:{description:`Access token response`,content:{"application/json":{schema:{type:`object`,properties:{access_token:{type:`string`,description:`The access token issued by the authorization server`},token_type:{type:`string`,description:`The type of the token issued`,enum:[`Bearer`,`DPoP`]},expires_in:{type:`number`,description:`Lifetime in seconds of the access token`},refresh_token:{type:`string`,description:`Refresh token, if issued`},scope:{type:`string`,description:`Scopes granted by the access token`},id_token:{type:`string`,description:`ID Token (if OpenID Connect)`}},required:[`access_token`,`token_type`,`expires_in`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>{if(e.request){let t=await uge(e.request);t&&t.length>1&&(e.body.resource=t)}return Oge(e,a)}),oauth2Introspect:n2(`/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=>j0(e,a)),oauth2Revoke:n2(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:A({client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),token:k(),token_type_hint:k().optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Revoke an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to revoke (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token revoked successfully. The response body is empty.`,content:{"application/json":{schema:{type:`object`,description:`Empty object on success`}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>Yve(e,a)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:A({access_token:k().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Get OpenID Connect user information (UserInfo endpoint)`,security:[{bearerAuth:[]},{OAuth2:[`openid`,`profile`,`email`]}],parameters:[{name:`Authorization`,in:`header`,required:!1,schema:{type:`string`},description:`Bearer or DPoP access token`},{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT when using a DPoP-bound access token`}],responses:{200:{description:`User information retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{sub:{type:`string`,description:`Subject identifier (user ID)`},email:{type:`string`,format:`email`,nullable:!0,description:`User's email address, included if 'email' scope is granted`},name:{type:`string`,nullable:!0,description:`User's full name, included if 'profile' scope is granted`},picture:{type:`string`,format:`uri`,nullable:!0,description:`User's profile picture URL, included if 'profile' scope is granted`},given_name:{type:`string`,nullable:!0,description:`User's given name, included if 'profile' scope is granted`},family_name:{type:`string`,nullable:!0,description:`User's family name, included if 'profile' scope is granted`},email_verified:{type:`boolean`,nullable:!0,description:`Whether the email is verified, included if 'email' scope is granted`}},required:[`sub`]}}}},401:{description:`Unauthorized - invalid or missing access token`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}},403:{description:`Forbidden - insufficient scope`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}}}}}},async e=>Ege(e,a)),oauth2EndSession:n2(`/oauth2/end-session`,{method:[`GET`,`POST`],body:t4.optional(),query:t4.optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},query:{}},openapi:{description:`RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.`,responses:{200:{description:`Logout completed, or an HTML confirmation page was returned for browser navigation. A redirect is used only for an exact registered post_logout_redirect_uri.`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`URI to redirect to after logout (if post_logout_redirect_uri was provided)`},message:{type:`string`,description:`Success message`}}}},"text/html":{schema:{type:`string`}}}}}}}},async e=>w_e(e,a)),oauth2EndSessionConfirmation:n2(`/oauth2/end-session/confirm`,{method:`POST`,body:A({action:Ke(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>T_e(e,a)),registerOAuthClient:n2(`/oauth2/register`,{method:`POST`,body:W1,errorCodesByField:{redirect_uris:`invalid_redirect_uri`,post_logout_redirect_uris:`invalid_redirect_uri`,software_statement:`invalid_software_statement`,resources:`invalid_target`},defaultError:`invalid_client_metadata`,metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`Name of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URL for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},post_logout_redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed logout redirect uris`},backchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL to receive signed Logout Tokens when the end-user's OP session terminates`},backchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires a `sid` claim in every Logout Token"},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final resource identifiers linked to the registered client`},disabled:{type:`boolean`,description:`Whether the client is disabled`}},required:[`client_id`]}}}}}}}},async e=>eve(e,a)),adminCreateOAuthClient:uve(a),createOAuthClient:dve(a),getOAuthClient:fve(a),getOAuthClientPublic:pve(a),getOAuthClientPublicPrelogin:mve(a),getOAuthClients:hve(a),adminUpdateOAuthClient:gve(a),updateOAuthClient:_ve(a),rotateClientSecret:vve(a),rotateClientKeys:yve(a),deleteOAuthClient:bve(a),getOAuthConsent:Tve(a),getOAuthConsents:Eve(a),updateOAuthConsent:Dve(a),deleteOAuthConsent:Ove(a),adminCreateOAuthResource:Rve(a),adminListOAuthResources:zve(a),adminGetOAuthResource:Bve(a),adminUpdateOAuthResource:Vve(a),adminDeleteOAuthResource:Hve(a),adminLinkClientResource:Uve(a),adminUnlinkClientResource:Wve(a)},schema:lG(structuredClone(Xve),a?.schema),rateLimit:[...a.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:a.rateLimit?.token?.window??60,max:a.rateLimit?.token?.max??20}],...a.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:a.rateLimit?.authorize?.window??60,max:a.rateLimit?.authorize?.max??30}],...a.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:a.rateLimit?.introspect?.window??60,max:a.rateLimit?.introspect?.max??100}],...a.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:a.rateLimit?.revoke?.window??60,max:a.rateLimit?.revoke?.max??30}],...a.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:a.rateLimit?.register?.window??60,max:a.rateLimit?.register?.max??5}],...a.rateLimit?.rotateClientKeys===!1?[]:[{pathMatcher:e=>e===`/oauth2/client/rotate-keys`,window:a.rateLimit?.rotateClientKeys?.window??60,max:a.rateLimit?.rotateClientKeys?.max??5}],...a.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:a.rateLimit?.userinfo?.window??60,max:a.rateLimit?.userinfo?.max??60}]]}};function Qve(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function $ve(e){let{max_age:t,...n}=e;return n}function s4(e,t,n,r,i,a=`query`){let o=new URLSearchParams({error:t,error_description:n});return r&&o.append(`state`,r),i&&o.append(`iss`,i),a===`fragment`?`${e}#${o.toString()}`:bq(e,o)}function eye(e){let t=typeof e.response_mode==`string`?e.response_mode:void 0;if(t===`fragment`)return`fragment`;if(t===`query`)return`query`;let n=typeof e.response_type==`string`?e.response_type:void 0;return n&&/\b(token|id_token)\b/.test(n)?`fragment`:`query`}const tye={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function nye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c4(e){return typeof e==`string`?e:void 0}function rye(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...nye(n)?n:{}}}const l4=(e,t)=>{let n=M0(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 u4(e,t,n,r,i){return l4(e,s4(n.redirect_uri,r,i,n.state,f4(e,t)))}function d4(e){try{let t=new URL(e);return t.protocol!==`https:`&&!SY(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function f4(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=q$(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return d4(n)}function p4(e,t,n){return s4(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function m4(e){let t;try{t=new URL(e)}catch{return}let n=xY(t.hostname)||t.hostname===`localhost`;if(t.protocol!==`http:`||!n)return;let r=e.indexOf(`://`);if(r<0)return;let i=r+3,a=e.slice(i).search(/[/?#]/u),o=e.length;a>=0&&(o=i+a);let s=e.slice(i,o),c;if(s.startsWith(`[`)){let t=s.indexOf(`]`);if(t<0)return;if(s[t+1]!==`:`)return e;c=t+1}else if(c=s.lastIndexOf(`:`),c<0)return e;let l=s.slice(c+1);if(!/^\d*$/u.test(l))return;let u=i+c;return`${e.slice(0,u)}${e.slice(o)}`}function h4(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=m4(t);return e.find(e=>e===t?!0:a?m4(e)===a:!1)}function g4(e){if(!k1.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function iye(e,t,n,r){if(!n||!r)return null;let i;try{i=await t1(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=h4(a,r);if(t.validateRedirectUri){if(!g4(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function _4(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await iye(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?l4(r,s4(a,t,n,typeof i.state==`string`?i.state:void 0,f4(r,e),eye(i))):l4(r,p4(r,t,n))}}async function aye(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new O(`NOT_FOUND`);if(!e.request)throw new O(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=rye(e,n);e.query=i;let a=c4(i.request),o=c4(i.request_uri);if(a!==void 0&&o!==void 0)return _4(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return _4(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=c4(i.client_id);if(!n)return _4(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return _4(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 _4(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=U1.safeParse(i);if(!s.success){let n=r2(s.error.issues,tye);return _4(t)({...n,ctx:e})}if(i=s.data,e.query=i,await n4.set({query:v4(i).toString()}),!i.response_type)return _4(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?v1(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return l4(e,p4(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return l4(e,p4(e,`unsupported_response_type`,`unsupported response type`));let u=await t1(e,t,i.client_id);if(!u)return l4(e,p4(e,`invalid_client`,`client not found`));if(u.disabled)return l4(e,p4(e,`client_disabled`,`client is disabled`));if(!d1(u,`authorization_code`))return l4(e,p4(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=!!h4(d,i.redirect_uri);if(t.validateRedirectUri&&g4(i.redirect_uri))try{f=await t.validateRedirectUri(i.redirect_uri,d,e)}catch{f=!1}else t.validateRedirectUri||(f=e)}if(!f)return l4(e,p4(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 l4(e,s4(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,f4(e,t)))}p||(p=u.scopes??t.scopes??[],i.scope=p.join(` `));let m=p.includes(`openid`);if(i.claims!==void 0&&!m)return l4(e,s4(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,f4(e,t)));if(m&&!Jhe(i.claims))return l4(e,s4(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,f4(e,t)));if(m&&!Yhe(i.claims,`0`))return l4(e,s4(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,f4(e,t)));let h=F1(i.claims,z1(t));if(i.resource!==void 0)try{await J1(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 l4(e,s4(i.redirect_uri,r,a,i.state,f4(e,t)))}throw n}let g=E1(u,{scopes:p,nonce:i.nonce});if(g&&(!i.code_challenge||!i.code_challenge_method))return l4(e,s4(i.redirect_uri,`invalid_request`,g.valueOf(),i.state,f4(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return l4(e,s4(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,f4(e,t)));if(![`S256`].includes(i.code_challenge_method))return l4(e,s4(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,f4(e,t)))}let _=X$(i.resource)??[],v=await zJ(e),y=i.max_age,b=v!=null&&y!==void 0&&Qve(new Date(v.session.createdAt),y,/* @__PURE__ */ new Date);if(!v||v!=null&&y!==void 0&&!b||c?.has(`login`)||c?.has(`create`))return l?u4(e,t,i,`login_required`,`authentication required`):b4(e,t,c?.has(`create`)?`create`:`login`);if(b&&(i=$ve(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return b4(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?u4(e,t,i,`account_selection_required`,`End-User account selection is required`):b4(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?u4(e,t,i,`interaction_required`,`End-User interaction is required`):b4(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?u4(e,t,i,`interaction_required`,`End-User interaction is required`):b4(e,t,`post_login`);if(c?.has(`consent`))return b4(e,t,`consent`,{sessionId:v.session.id});let x=await b1(t,{user:v.user,session:v.session,scopes:p});if(u.skipConsent)return y4(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 x1(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?u4(e,t,i,`consent_required`,`End-User consent is required`):b4(e,t,`consent`,{sessionId:v.session.id});let ee=S?.resources??[];return _.some(e=>!ee.includes(e))?l?u4(e,t,i,`consent_required`,`End-User consent is required`):b4(e,t,`consent`,{sessionId:v.session.id}):y4(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 v4(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 y4(e,t,n){let r=JH(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await o1(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`,f4(e,t)),l4(e,s.toString())}async function b4(e,t,n,r){let i=await oye(e,t,{postLoginClearedForSession:n===`consent`&&t.postLogin?r?.sessionId:void 0}),a=t.loginPage;if(n===`select_account`)a=t.selectAccount?.page??t.loginPage;else if(n===`post_login`){if(!t.postLogin?.page)throw new O(`INTERNAL_SERVER_ERROR`,{error_description:`postLogin should have been defined`});a=t.postLogin?.page}else n===`consent`?a=t.consentPage:n===`create`&&(a=t.signup?.page??t.loginPage);return l4(e,`${r?.page??a}?${i}`)}async function oye(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=v4(e.query);a.set(`exp`,String(i)),a.set(A$,String(r)),a.delete(`sig`),a.delete(j$),n?.postLoginClearedForSession&&a.set(j$,n.postLoginClearedForSession),uhe(a);let o=await VW(N$(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const sye=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,cye=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function x4(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function lye(e){if(sye.test(e))return`client_id URL MUST NOT contain dot segments`;if(e.includes(`#`))return`client_id URL MUST NOT contain a fragment`;let t;try{t=new URL(e)}catch{return`client_id is not a valid URL`}if(t.protocol!==`https:`)return`client_id URL must use HTTPS`;let n=/^https:\/\//i.exec(e);if(!n||e.includes(`\\`))return`client_id URL MUST use an explicit HTTPS authority form`;let r=e.slice(n[0].length),i=r.search(/[/?#]/);return i===0?`client_id URL MUST use an explicit HTTPS authority form`:i<0||r[i]!==`/`?`client_id URL MUST contain an explicit path component`:t.username||t.password?`client_id URL MUST NOT contain credentials`:CY(t.hostname)?null:`client_id URL must not target a private or reserved address`}function uye(e){let t=[];try{let n=new URL(e);n.pathname===`/`&&t.push(`client_id URL path / is NOT RECOMMENDED (§3)`),n.search&&t.push(`client_id URL SHOULD NOT contain a query string (§3)`)}catch{}return t}function dye(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||O1(t)}catch{return!1}}function fye(e,t,n={}){if(!t||typeof t!=`object`)return{valid:!1,error:`metadata document is not a JSON object`};for(let e of Object.keys(t))if(d2(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=oge.strip().safeParse(t);if(!r.success){let e=r.error.issues[0];return{valid:!1,error:`${e?.path.join(`.`)||`metadata document`}: ${e?.message??`invalid client metadata`}`}}let i=r.data,a=[];if(i.client_id!==e)return{valid:!1,error:`client_id "${String(i.client_id)}" does not match the metadata document URL`};if(n.metadataProfile===`mcp-2026-07-28`&&!i.client_name?.trim())return{valid:!1,error:`client_name must be a non-empty string`};for(let e of[`backchannel_logout_uri`,`backchannel_logout_session_required`])if(i[e]!==void 0)return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let o=/* @__PURE__ */ new Set([`none`,`private_key_jwt`]);if(typeof i.token_endpoint_auth_method==`string`){if(cye.has(i.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${i.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!o.has(i.token_endpoint_auth_method))return{valid:!1,error:`token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients`};if(i.token_endpoint_auth_method===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)return{valid:!1,error:`private_key_jwt requires either jwks or jwks_uri in the metadata document`}}if(i.jwks&&!l2(i.jwks).valid)return{valid:!1,error:`jwks must contain only structurally valid public keys`};if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.username||e.password)return{valid:!1,error:`jwks_uri must not contain credentials`};if(i.jwks_uri.includes(`#`))return{valid:!1,error:`jwks_uri must not contain a fragment`}}catch{return{valid:!1,error:`jwks_uri must be a valid URL`}}if(n.metadataProfile===`mcp-2026-07-28`&&!i.redirect_uris||i.redirect_uris&&!i.redirect_uris.every(e=>dye(e)))return{valid:!1,error:`redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs`};for(let e of[`client_uri`,`logo_uri`,`tos_uri`,`policy_uri`]){if(i[e]!==void 0&&typeof i[e]!=`string`)return{valid:!1,error:`${e} must be a string`};if(typeof i[e]==`string`)try{let t=new URL(i[e]);if(t.protocol!==`https:`&&t.protocol!==`http:`)return{valid:!1,error:`${e} must use HTTP(S)`};if(t.username||t.password)return{valid:!1,error:`${e} must not contain credentials`};if(!CY(t.hostname))return{valid:!1,error:`${e} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${e} is not a valid URL`}}}let s=n.originBoundFields??[`post_logout_redirect_uris`,`client_uri`],c;try{c=new URL(e).origin}catch{return{valid:!1,error:`client_id is not a valid URL`}}for(let e of s){let t=i[e];if(t===void 0)continue;let n;if(typeof t==`string`)n=[t];else if(Array.isArray(t)){if(!t.every(e=>typeof e==`string`))return{valid:!1,error:`${e} must be a string or an array of strings`};n=t}else return{valid:!1,error:`${e} must be a string or an array of strings`};for(let t of n){let n;try{n=new URL(t)}catch{return{valid:!1,error:`${e} contains an invalid URL: "${t}"`}}let r=e===`redirect_uris`||e===`post_logout_redirect_uris`,i=r&&O1(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`||D1(n)))continue;let a=r&&(n.protocol===`http:`||n.protocol===`https:`)&&SY(n.hostname);if(n.origin!==c&&!a)return{valid:!1,error:`${e} value "${t}" must have the same origin as client_id (${c})`}}}return a.push(...uye(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const S4=5e3,C4=5120,pye=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,w4=`Failed to fetch metadata document (network error or redirect blocked)`,T4=`cimd`;function E4(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function D4(){return E4(`Metadata document exceeds ${C4/1024}KB size limit`)}async function mye(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw D4();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(),D4();i.push(n)}}finally{n.removeEventListener(`abort`,c),r.releaseLock()}let l=new Uint8Array(a),u=0;for(let e of i)l.set(e,u),u+=e.byteLength;return new TextDecoder().decode(l)}function hye(e){return{cacheControl:e.get(`cache-control`)??void 0,vary:e.get(`vary`)??void 0,expires:e.get(`expires`)??void 0,date:e.get(`date`)??void 0,age:e.get(`age`)??void 0,etag:e.get(`etag`)??void 0,lastModified:e.get(`last-modified`)??void 0}}async function gye(e,t,n,r){let i=lye(t);if(i)throw E4(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw E4(`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()},S4);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw E4(c?`Metadata document fetch timed out after ${S4}ms`:w4)}if(o.redirected)throw E4(`Metadata document fetch must not follow redirects`);let i=hye(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw E4(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw E4(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!pye.test(l))throw E4(`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>C4)throw await o.body?.cancel(),D4()}u=await mye(o,C4,s.signal)}catch(e){throw c?E4(`Metadata document fetch timed out after ${S4}ms`):e instanceof O?e:E4(w4)}let d;try{d=JSON.parse(u)}catch{throw E4(`Metadata document is not valid JSON`)}let f=fye(t,d,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!f.valid)throw E4(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 O4(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await B2(e,i,{clientId:t,clientDiscoveryId:T4,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 k4={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function _ye(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function A4(e){return new O(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function vye(e,t){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw new D(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`);return e*1e3}try{let t=Math.floor(Date.now()/1e3),n=(S$(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 j4(e,t){if(!Number.isInteger(e)||e<1)throw new D(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function yye(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:vye(t?.minimumFetchInterval??k4.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:j4(t?.maximumConcurrentFetches??k4.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:j4(t?.maximumConcurrentFetchesPerOrigin??k4.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:j4(t?.maximumFetchesPerMinute??k4.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:j4(t?.maximumFetchesPerOriginPerMinute??k4.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function M4(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function bye(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(S$(e,n)-n)*1e3)}function xye(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;for(let r of e?.split(`,`)??[]){let[e,...i]=r.trim().split(`=`),a=e?.toLowerCase();if(!a)continue;t.has(a)&&n.add(a);let o=i.join(`=`).trim();t.set(a,!o||o.replace(/^"|"$/g,``))}return{directives:t,duplicates:n}}function N4(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Sye(e,t,n){let{directives:r,duplicates:i}=xye(e.cacheControl),a=e.vary?.split(`,`).some(e=>e.trim()===`*`);if(r.has(`no-store`)||r.has(`private`)||a)return{cacheable:!1,expiresAt:n};let o=bye(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=N4(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=N4(r.get(`s-maxage`)),m=r.has(`max-age`),h=N4(r.get(`max-age`)),g=f?p===null||i.has(`s-maxage`):m&&(h===null||i.has(`max-age`)),_=f?p:h;if(g)d=0;else if(_!==null)d=Math.max(0,_*1e3-u);else if(e.expires){let t=Date.parse(e.expires);Number.isFinite(t)&&(d=Math.max(0,t-(Number.isFinite(c)?c:n)-u))}return{cacheable:!0,expiresAt:n+Math.min(o,d??o)}}function Cye(e,t){return{cacheControl:t.cacheControl??e.cacheControl,vary:t.vary??e.vary,expires:t.expires??e.expires,date:t.date??e.date,age:t.age??e.age,etag:t.etag??e.etag,lastModified:t.lastModified??e.lastModified}}function wye(e,t,n,r){let i=Sye(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function Tye(e){let t=e.metadataRevalidationInterval??`60m`,n=e.maxCacheEntries??1e3;if(!Number.isInteger(n)||n<1)throw new D(`cimd maxCacheEntries must be a positive integer`);let r=yye(e),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=[],l=0,u=e=>{let t=i.get(e);if(t)return i.delete(e),i.set(e,t),t},d=(e,t)=>{for(i.delete(e);i.size>=n;){let e=i.keys().next().value;if(typeof e!=`string`)break;i.delete(e)}i.set(e,t)},f=(e,t)=>{if(!o.has(e))for(;o.size>=n;){let e=!1;for(let[n,i]of o)if(!a.has(n)&&!(r.minimumFetchIntervalMs>0&&t-i<r.minimumFetchIntervalMs)){o.delete(n),e=!0;break}if(!e)throw A4(`metadata fetch client state is at capacity`)}},p=(e,t)=>{let r=s.get(e);if(r)return M4(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(M4(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw A4(`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 A4(`metadata document fetch is within the per-client minimum interval`);f(e,t);let i=new URL(e).origin,a=p(i,t);if(M4(c,t),l>=r.maximumConcurrentFetches)throw A4(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw A4(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw A4(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw A4(`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(!x4(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||O4(n,r,f.metadata,e,l);let h=a.get(r);if(h!==void 0)return h;let g=m(r),_=(async()=>{let a=await gye(n,r,e,f?{etag:f.etag,lastModified:f.lastModified}:void 0);if(a.status===`not-modified`&&!f)throw _ye(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:f.metadata,u=await O4(n,r,c,e,l,s??void 0),p=wye(c,a.status===`modified`?a.cacheHeaders:Cye(f.responseCacheHeaders,a.cacheHeaders),t,Date.now());return p?d(r,p):i.delete(r),o.delete(r),u})();a.set(r,_);try{return await _}catch(e){throw o.delete(r),o.set(r,Date.now()),e}finally{a.get(r)===_&&a.delete(r),g()}}}function Eye(e){return{id:T4,matches:x4,resolve:Tye(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const Dye=e=>{let t=Eye(e);return{id:`cimd`,version:`1.7.10`,init(e){yhe(e,{clientDiscovery:t})}}},Oye=/* @__PURE__ */ new Set([204,205,304]);function kye(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.append(n,r);return t}const Aye=async(e,t)=>{let n=new Request(e,t),r=new URL(n.url);if(r.protocol!==`https:`)throw TypeError(`CIMD Node transport requires an HTTPS URL`);if(n.method!==`GET`&&n.method!==`HEAD`)throw TypeError(`CIMD Node transport supports only GET and HEAD`);let i=await _ee(r.hostname,{all:!0,verbatim:!0});if(i.length===0)throw TypeError(`metadata hostname returned no DNS addresses`);for(let e of i)if(!CY(e.address))throw TypeError(`metadata hostname must resolve only to public-routable addresses`);let a=i[0],o=Object.fromEntries(n.headers.entries());o.host=r.host;let s=t?.signal??(e instanceof Request?e.signal:n.signal);return new Promise((e,t)=>{let i=pee(r,{agent:!1,headers:o,method:n.method,servername:St(r.hostname.replace(/^\[|\]$/g,``))===0?r.hostname:void 0,signal:s,lookup:(e,t,n)=>{t.all?n(null,[a]):n(null,a.address,a.family)}},t=>{let r=t.statusCode??500,i=n.method===`HEAD`||Oye.has(r)?null:yt.toWeb(t);e(new Response(i,{headers:kye(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function jye(e,t=8){let n=0;return(r,i)=>{let a=i?.signal??(r instanceof Request?r.signal:void 0);return a?.aborted?Promise.reject(a.reason):n>=t?Promise.reject(/* @__PURE__ */ Error(`CIMD transport capacity reached`)):(n++,new Promise((t,o)=>{let s=!1,c=()=>{s=!0,o(a?.reason)};a?.addEventListener(`abort`,c,{once:!0});let l=()=>{n--,a?.removeEventListener(`abort`,c)};Promise.resolve().then(()=>(a?.throwIfAborted(),e(r,i))).then(e=>{l(),s?e.body?.cancel().catch(()=>{}):t(e)},e=>{l(),o(e)})}))}}var P4=class e extends P()(`clankerauth/CimdTransport`){static layer=of(e,{fetch:jye(Aye)});static layerWith=t=>t===void 0?e.layer:of(e,{fetch:t})};const F4=`x-clankerauth-peer`,Mye=e=>dee({requestTimeout:15e3,headersTimeout:1e4},e),Nye=(e,t)=>{t.writeHead(503).end()},Pye=sm(`NodeHttp.listen`)(function*(e,t){let n=Nye,r=Mye((e,t)=>n(e,t)),i=Yf(e=>{r.close(()=>e(L)),r.closeAllConnections()});yield*Ip(Yf(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=>Lp(()=>i).pipe(ip(()=>I(()=>n=e)))}:yield*$f(/* @__PURE__ */ Error(`Expected a TCP listener`))}),Fye=ah(65536),Iye=/^\/forward-auth(?:\?|$)/,Lye=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Ni(t,()=>`unknown`)},Rye=({baseURL:e,trustProxy:t})=>n=>R(function*(){let r=yield*_M,i=r.source,a=i instanceof xt?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return pj({status:400});let o=It(r.headers,Iye.test(a)?_g(`forwarded`):vg([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),mg(`host`,new URL(e).host),mg(F4,Lye(r.headers,r.remoteAddress,t)),_g(`x-forwarded-for`)),s=yield*n.pipe(Np(_M,r.modify({headers:o})),Np(FA,Fye));return i instanceof xt?AO(s.body).pipe(MO(`Stream`,e=>Ej(s,sA(e.stream.pipe(zE(()=>I(()=>i.socket.destroy()))),e.contentType,e.contentLength))),RO(()=>s)):s}).pipe(Gp),I4=e=>`${L4}${e}`,L4=`resource:`,R4=(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})`,z4=sm(`Authorization.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:I4(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*R4(e,n,r),yield*e`DELETE FROM oauthAccessToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*e`DELETE FROM oauthRefreshToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`}),zye=yoe(W({message:Ix(U),error_description:Ix(U)})),Bye=e=>Ni(Bi(zye(e.body),e=>Fi(e.message??e.error_description)),()=>`Request could not be completed`),B4=e=>new nV({message:e}),V4=e=>new XB({message:e}),H4=(e,t={})=>Kf({try:e,catch:e=>{if(!Fq(e))return YB.of(e);let n=e.statusCode,r=n===400||n===422?t.refused:n===404?t.missing:n===409?t.conflict:n===503?t.unavailable:void 0;return r?r(Bye(e)):YB.of(e)}}),U4=(e,t)=>new kI({message:t,issues:[{path:e,message:t}]}),Vye=Ex(K(GV)),Hye=on(`RequestParseError`),Uye=e=>Vye(e)?e:oce(e)&&Hye(e.reason)?new rV({message:`Request body could not be read`}):YB.of(e),Wye=new Map(GV.map(e=>[e,ub(`httpApiStatus`)(e.ast)??500])),Gye=Use(K(GV)),W4=e=>{let t=Uye(e),n=GV.find(e=>Ex(e)(t));return Gye(t,{status:Wye.get(n)??500}).pipe(hp)},G4=(e,t)=>e===t||e.endsWith(`.${t}`),Kye=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!St(e)}catch{return!1}},K4=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),q4=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,J4=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&K4(new URL(e),t),Y4=H(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return J4(n,t)?ag(e.secret).length<32?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>J4(e,t))?r!==void 0&&(!Kye(r)||!G4(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 ${q4}`)):yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${q4}`))}),qye=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*Y4(e)});var X4=class e extends P()(`clankerauth/Settings`){static layer=lf(e,qye)};const Z4=`Exactly one configured resource is required`,Q4=[`offline_access`],Jye=tH(wS(G(U))),Yye=tH(W({identifier:U,name:U,allowedScopes:U})),$4=tH(G(OV)),e3=(e,t)=>[.../* @__PURE__ */ new Set([...Q4,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],t3=sm(`ResourceCatalog.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*U4([`resources`,n],`Unknown Resource`)}),n3=sm(`ResourceCatalog.accessForClient`)(function*(e,t){return yield*$4(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)});var r3=class e extends P()(`clankerauth/ResourceCatalog`){static layer=lf(e,R(function*(){let{sql:e}=yield*aH,t=lV((yield*X4).baseURL),n=sm(`ResourceCatalog.decode`)(function*(e){let n=yield*Yye(e),r=yield*Jye(n.allowedScopes);return{identifier:n.identifier,name:n.name,scopes:r.filter(e=>!Q4.includes(e)),builtIn:n.identifier===t}}),r=sm(`ResourceCatalog.list`)(function*(){let t=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*Uf(t,n)}),i=sm(`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:sm(`ResourceCatalog.access`)(function*(){return yield*$4(yield*e`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),hasAccess:sm(`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:sm(`ResourceCatalog.scopesFor`)(function*(e){let t=yield*r();return yield*t3(t,e),e3(t,e)})}}))};const Xye=voe(W({typ:U,payload:Yx(U,QS)})),Zye=e=>({id:`signer`,endpoints:{signDocument:X.serverOnly({method:`POST`,body:Xye},async t=>t.json({token:await T$(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),Qye=e=>typeof e==`string`,$ye=(e,t,n,r,i,a)=>{let o={disableSettingJwtHeader:!0,jwt:{issuer:`${e.baseURL}/api/auth`},jwks:{keyPairConfig:{alg:`EdDSA`,crv:`Ed25519`}}},s=o4({loginPage:`/login`,consentPage:`/consent`,scopes:[...Q4],resources:[{identifier:lV(e.baseURL),name:`clankerauth administration`,allowedScopes:[...Q4,uV.read,uV.write]}],resourceSeedMode:`merge`,rateLimit:{register:{window:60,max:10}},postLogin:{page:`/consent`,shouldRedirect:()=>!1,consentReferenceId:async({scopes:e})=>{let t=await r4(),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:Z4});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 I4(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:ag(e.secret),database:{db:t,type:`sqlite`,transaction:!0},trustedOrigins:[e.baseURL],logger:{disabled:!0},disabledPaths:[`/token`],emailAndPassword:{enabled:!0,minPasswordLength:8,maxPasswordLength:128},databaseHooks:{user:{create:{before:async()=>{if(await a())throw new E(`CONFLICT`,{message:`Setup already completed`})}}}},hooks:{before:zq(async e=>{if(e.path===`/oauth2/register`){let t=e.body.redirect_uris;!e.body.application_type&&Array.isArray(t)&&t.some(e=>{if(!Qye(e))return!1;try{return new URL(e).protocol!==`https:`}catch{return!1}})&&(e.body.application_type=`native`),delete e.body.resources}})},session:{expiresIn:2592e3,updateAge:86400},advanced:{ipAddress:{ipAddressHeaders:[F4]}},rateLimit:{enabled:!0,storage:`database`,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:5}}},plugins:[$me({defaultPrefix:`clankerauth_`,maximumNameLength:100,enableSessionForAPIKeys:!1,keyExpiration:{defaultExpiresIn:null,minExpiresIn:0},rateLimit:{enabled:!1}}),lhe(o),Zye(o),s,Dye({fetchClientMetadataResource:r,metadataProfile:`mcp-2026-07-28`,metadataRevalidationInterval:300,maxCacheEntries:1e3,metadataFetchPolicy:{maximumConcurrentFetches:8,maximumConcurrentFetchesPerOrigin:2,maximumFetchesPerMinute:60,maximumFetchesPerOriginPerMinute:15}})]},oauthPlugin:s}};var i3=class e extends P()(`clankerauth/Issuer`){static layer=lf(e,R(function*(){let e=yield*X4,{kysely:t}=yield*aH,n=yield*r3,{fetch:r}=yield*P4,i=mie(yield*Ep()),{options:a,oauthPlugin:o}=$ye(e,t,n,r,i,async()=>await(await SH((await s.$context).adapter)).count({model:`user`})>0),{auth:s,context:c}=yield*sm(`Auth.initialize`)(function*(){let e=yield*Kf(()=>kQ(a));if(e.schemaProblems.length)return yield*z(/* @__PURE__ */ Error(`Database schema requires manual repair`));yield*Kf(()=>e.runMigrations());let t=vme(a);return{auth:t,context:yield*Kf(()=>t.$context)}},qp)();return{auth:s,context:c,publishScopes:e=>I(()=>{o.options.scopes=[...e]})}}))};const ebe=Dx(jV),tbe=Dx(W({id:U,key:U,referenceId:U,expiresAt:tS(FS),permissions:tS(wS(jV))})),a3=H(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*ebe(e.permissions??{}).pipe(lp(()=>sp(um(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?lh(e.expiresAt):null,createdAt:lh(e.createdAt)}});var o3=class e extends P()(`clankerauth/ApiKeys`){static layer=lf(e,R(function*(){let{auth:e}=yield*i3,{sql:t}=yield*aH,n=yield*r3,r=sm(`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*U4([`permissions`,t],`Administration requires OAuth access tokens, not API keys`);if(!e||r.some(t=>!e.scopes.includes(t)))return yield*U4([`permissions`,t],`Select explicitly granted, currently available Resource scopes`)}});return{list:sm(`ApiKeys.list`)(function*(){let{providerHeaders:t}=yield*aV,n=yield*t,r=yield*H4(()=>e.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*Uf(r.apiKeys,a3)}}),create:sm(`ApiKeys.create`)(function*(t){let n=yield*aV;yield*r(t.permissions);let i=t.expiresAt===null?null:(ph(t.expiresAt)-(yield*Sf))/1e3;if(i!==null&&i<1)return yield*U4([`expiresAt`],`Expiry must be in the future`);let a=yield*H4(()=>e.api.createApiKey({body:{userId:n.userId,name:t.name.trim(),permissions:wa(t.permissions,e=>[...e]),expiresIn:i}}),{refused:B4});return{...yield*a3(a),key:a.key}}),update:sm(`ApiKeys.update`)(function*(t){let n=yield*aV;return yield*r(t.permissions),yield*a3(yield*H4(()=>e.api.updateApiKey({body:{userId:n.userId,keyId:t.keyId,name:t.name?.trim(),enabled:t.enabled,permissions:t.permissions&&wa(t.permissions,e=>[...e])}}),{refused:B4,missing:()=>$B.of(t.keyId)}))}),delete:sm(`ApiKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*aV,r=yield*n;return yield*H4(()=>e.api.deleteApiKey({headers:r,body:{keyId:t}}),{missing:()=>$B.of(t)}),{deleted:!0}}),keyList:sm(`ApiKeys.keyList`)(function*(r){let i=yield*Sf,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*Uf(o,e=>R(function*(){let t=yield*tbe(e),n=(t.permissions?.[r]??[]).filter(e=>a.includes(e));return n.length?[yield*Kf(()=>Ide(new Uint8Array(Buffer.from(t.key,`base64url`)),r,{keyId:t.id,ownerId:t.referenceId,scopes:n,expiresAt:t.expiresAt===null?null:ph(t.expiresAt)}))]:[]}).pipe(lp(()=>sp(um(`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*H4(()=>e.api.signDocument({body:{typ:SI,payload:{aud:r,iat:c,exp:c+86400,keys:s.flat()}}}));return{list:l}})}}))};const s3=e=>e.userId===null,nbe=tH(G(W({userId:tS(U)}))),c3=sm(`Clients.requireManaged`)(function*(e,t){let[n]=yield*nbe(yield*t`SELECT userId FROM oauthClient WHERE clientId = ${e}`);if(!n)return yield*z(ZB.of(e));if(s3(n))return yield*z(eV.of(e))}),rbe=tH(G(W({clientId:U}))),l3=e=>({identifier:encodeURIComponent(e)}),ibe=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},abe=sm(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!ibe(t))return yield*U4([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>Q4.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*U4([`scopes`,i],`offline_access is reserved`)});var u3=class e extends P()(`clankerauth/Resources`){static layer=lf(e,R(function*(){let{sql:e,transaction:t}=yield*aH,{auth:n,publishScopes:r}=yield*i3,i=yield*r3,a=yield*Pw(1),o=e=>a.withPermit(e),s=sm(`Resources.syncClient`)(function*(e,t,n){let r=yield*n3(n,e),i=JSON.stringify(e3(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*Sf} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),c=sm(`Resources.synchronize`)(function*(){let t=yield*i.list(),n=e3(t,t.map(e=>e.identifier));yield*r(n),yield*e`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*Sf} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*rbe(yield*e`SELECT clientId FROM oauthClient WHERE userId IS NOT NULL ORDER BY clientId`))yield*s(e,t,n.clientId)}),l=e=>e?.builtIn?z(U4([`identifier`],`The administration Resource is fixed`)):L,u=B(aV,e=>e.providerHeaders);yield*c();let d=sm(`Resources.link`)(function*(n,r){let a=yield*i.list();yield*t3(a,r);let o=yield*Sf;return yield*t(e=>R(function*(){let t=(yield*n3(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*z4(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*n3(n,e)},o);return{link:d,get:sm(`Resources.get`)(function*({identifier:e}){return(yield*i.get(e))??(yield*QB.of(e))}),put:sm(`Resources.put`)(function*(e){let r=yield*abe(e),a=yield*i.get(r.identifier);yield*l(a);let o=yield*u,s=[...Q4,...r.scopes];return a===void 0?(yield*t(e=>z4(e,{resource:r.identifier})),yield*H4(()=>n.api.adminCreateOAuthResource({headers:o,body:{identifier:r.identifier,name:r.name,allowedScopes:s}}),{refused:B4})):yield*H4(()=>n.api.adminUpdateOAuthResource({headers:o,params:l3(r.identifier),body:{name:r.name,allowedScopes:s}}),{refused:B4}),yield*c(),{resource:r,created:a===void 0}},o),delete:sm(`Resources.delete`)(function*({identifier:e}){yield*l(yield*i.get(e));let r=yield*u;return yield*H4(()=>n.api.adminDeleteOAuthResource({headers:r,params:l3(e)}),{missing:()=>QB.of(e)}),yield*t(t=>z4(t,{resource:e})),yield*c(),{deleted:!0}},o),setAccess:sm(`Resources.setAccess`)(function*({client_id:t,resources:n}){return yield*c3(t,e),{clientAccess:yield*d(t,n)}})}}))};const obe=tH(G(W({client_id:U,resource:U,scopes:wS(G(U)),approvedAt:tS(FS),refreshedAt:tS(FS)}))),sbe=tH(G(W({clientId:U,name:tS(U),redirectUris:wS(G(U)),tokenEndpointAuthMethod:tS(U),applicationType:tS(U),scopes:tS(wS(G(U))),grantTypes:tS(wS(G(U))),disabled:tS(Wx),clientDiscoveryId:tS(U),userId:tS(U)})));var d3=class e extends P()(`clankerauth/Clients`){static layer=lf(e,R(function*(){let{sql:e,transaction:t}=yield*aH,{auth:n}=yield*i3,{baseURL:r}=yield*X4,i=yield*r3,a=yield*u3,o=sm(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*z(ZB.of(e))}),s=sm(`Clients.revoke`)(function*(e,t,n){return yield*o(e,n),yield*z4(n,{clientId:e,resource:t}),{revoked:!0}}),c=sm(`Clients.connections`)(function*(){let t=new Date(yield*Sf).toISOString();return(yield*obe(yield*e`WITH live AS (
|
|
516
|
-
SELECT clientId, referenceId, scopes, createdAt FROM oauthRefreshToken
|
|
517
|
-
WHERE revoked IS NULL AND expiresAt > ${t}
|
|
518
|
-
), held AS (
|
|
519
|
-
SELECT clientId, referenceId FROM oauthConsent
|
|
520
|
-
UNION SELECT clientId, referenceId FROM live
|
|
521
|
-
)
|
|
522
|
-
SELECT h.clientId AS client_id, r.identifier AS resource, c.updatedAt AS approvedAt,
|
|
523
|
-
COALESCE(c.scopes, (SELECT l.scopes FROM live l WHERE l.clientId = h.clientId
|
|
524
|
-
AND l.referenceId = h.referenceId ORDER BY l.createdAt DESC LIMIT 1)) AS scopes,
|
|
525
|
-
(SELECT MAX(l.createdAt) FROM live l WHERE l.clientId = h.clientId
|
|
526
|
-
AND l.referenceId = h.referenceId) AS refreshedAt
|
|
527
|
-
FROM held h
|
|
528
|
-
JOIN oauthResource r ON h.referenceId = ${L4} || 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=>!Q4.includes(e))}))});return{connections:c,list:sm(`Clients.list`)(function*(){let{email:t}=yield*aV,n=yield*e`
|
|
531
|
-
SELECT clientId, name, redirectUris, tokenEndpointAuthMethod, applicationType, scopes,
|
|
532
|
-
grantTypes, disabled, clientDiscoveryId, userId
|
|
533
|
-
FROM oauthClient ORDER BY createdAt, clientId
|
|
534
|
-
`,a=(yield*sbe(n)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?s3(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*Hf({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:sm(`Clients.create`)(function*(e){let{providerHeaders:t}=yield*aV,r=yield*i.scopesFor(e.resources),o=yield*t,s=yield*H4(()=>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:B4});return yield*a.link(s.client_id,e.resources).pipe(gp(()=>H4(()=>n.api.deleteOAuthClient({headers:o,body:{client_id:s.client_id}})))),s}),update:sm(`Clients.update`)(function*(t){yield*c3(t.client_id,e);let{providerHeaders:r}=yield*aV,i=yield*r;return yield*H4(()=>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:B4,missing:()=>ZB.of(t.client_id)})}),rotate:sm(`Clients.rotate`)(function*(t){yield*c3(t.client_id,e);let{providerHeaders:r}=yield*aV,i=yield*r;return yield*H4(()=>n.api.rotateClientSecret({headers:i,body:t}),{refused:B4,missing:()=>ZB.of(t.client_id)})}),revoke:({client_id:e,resource:n})=>t(t=>s(e,n,t)),delete:({client_id:e})=>t(t=>R(function*(){return yield*o(e,t),yield*R4(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*Sf} WHERE clientId = ${e}`,{blocked:n}}))}}))};const cbe=[`/`,`/resources`,`/keys`,`/login`,`/setup`,`/consent`],lbe=({readOnly:e,mcp:t})=>({readOnlyHint:e,destructiveHint:t.destructiveHint??!e,idempotentHint:t.idempotentHint??!1,openWorldHint:t.openWorldHint??!0}),f3=`~effect/ai/AiError/Reason`;var ube=class extends (/*#__PURE__*/ KS(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ aS(`ToolParameterValidationError`),toolName:U,description:U})){[f3]=f3;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}};const p3=`~effect/rpc/RpcMiddleware`,dbe=()=>(e,t)=>{let n=er(),r;n!==0&&(tr(2),r=new globalThis.Error,tr(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[p3]=p3,a.error=t?.error??Vx,a.requiredForClient=t?.requiredForClient??!1,i},m3=(e,t)=>{let n=I(t);return Ix(e).pipe(joe({decode:rv(n),encode:Q_()}),iS(n))},Z=e=>Ix(e).pipe(rS(Rx(Lx(e)),{decode:Q_(),encode:tv(Bi(Ii))})),fbe=/*#__PURE__*/ K([U,fS]),h3=/*#__PURE__*/ K([U,fS]);var g3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ Xx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ Z(h3)}),[q]))}))){},_3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){},v3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){};const pbe=U;({...g3.fields});var y3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({..._3.fields,nextCursor:/*#__PURE__*/ Z(pbe)}))){};const b3=/*#__PURE__*/ eS([`user`,`assistant`]);var x3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({audience:/*#__PURE__*/ Z(/*#__PURE__*/ G(b3)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(U)}))){},S3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Icon`)({src:U,mimeType:/*#__PURE__*/ Z(U),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ eS([`light`,`dark`]))})){},C3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),version:U,icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(S3)),description:/*#__PURE__*/ Z(U),websiteUrl:/*#__PURE__*/ Z(U)}))){},w3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(/*#__PURE__*/ Bx([U,`/`,U]),QS)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Gx)})),sampling:/*#__PURE__*/ Z(/*#__PURE__*/ W({context:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))})),elicitation:/*#__PURE__*/ Z(/*#__PURE__*/ W({form:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),url:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))}))})){},mbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(/*#__PURE__*/ Bx([U,`/`,U]),QS)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Gx)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ Z(Gx),listChanged:/*#__PURE__*/ Z(Gx)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Gx)}))}))){},T3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/McpErrorBase`)({code:hS,message:U,data:/*#__PURE__*/ Z(Hx)})){};const E3=-32601,D3=-32602,O3=-32603,k3=-32020;var A3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/ParseError`)({...T3.fields,_tag:/*#__PURE__*/ aS(`ParseError`),code:/*#__PURE__*/ aS(-32700)})){},j3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InvalidRequest`)({...T3.fields,_tag:/*#__PURE__*/ aS(`InvalidRequest`),code:/*#__PURE__*/ aS(-32600)})){},M3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/MethodNotFound`)({...T3.fields,_tag:/*#__PURE__*/ aS(`MethodNotFound`),code:/*#__PURE__*/ aS(E3)})){},N3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InvalidParams`)({...T3.fields,_tag:/*#__PURE__*/ aS(`InvalidParams`),code:/*#__PURE__*/ aS(D3)})){},P3=class e extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InternalError`)({...T3.fields,_tag:/*#__PURE__*/ aS(`InternalError`),code:/*#__PURE__*/ aS(O3)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const F3=/*#__PURE__*/ K([A3,j3,M3,N3,P3,T3]);var hbe=class extends (/*#__PURE__*/ J(`ping`,{success:/*#__PURE__*/ W({}),error:F3,payload:/*#__PURE__*/ nS(g3)})){},gbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({..._3.fields,protocolVersion:U,capabilities:mbe,serverInfo:C3,instructions:/*#__PURE__*/ Z(U)}))){},_be=class extends (/*#__PURE__*/ J(`initialize`,{success:gbe,error:F3,payload:{...g3.fields,protocolVersion:U,capabilities:w3,clientInfo:C3}})){},I3=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...v3.fields,requestId:fbe,reason:/*#__PURE__*/ Z(U)}})){},L3=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...v3.fields,progressToken:h3,progress:fS,total:/*#__PURE__*/ Z(fS),message:/*#__PURE__*/ Z(U)}})){},vbe=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(x3),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(S3)),size:/*#__PURE__*/ Z(hS),_meta:/*#__PURE__*/ Z(q)})){},R3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)}))){},ybe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({...R3.fields,text:U}))){},bbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({...R3.fields,blob:OS}))){};({...y3.fields}),{...y3.fields},{..._3.fields},{...g3.fields};var z3=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ nS(v3)})){};({...g3.fields}),{...g3.fields};var B3=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...v3.fields,uri:U}})){},xbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),required:/*#__PURE__*/ Z(Gx)}))){},Sbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Prompt`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ G(xbe)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(S3)),_meta:/*#__PURE__*/ Z(q)})){},V3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({type:/*#__PURE__*/ aS(`text`),text:U,annotations:/*#__PURE__*/ Z(x3),_meta:/*#__PURE__*/ Z(q)}))){},H3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({type:/*#__PURE__*/ aS(`image`),data:OS,mimeType:U,annotations:/*#__PURE__*/ Z(x3),_meta:/*#__PURE__*/ Z(q)}))){},U3=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({type:/*#__PURE__*/ aS(`audio`),data:OS,mimeType:U,annotations:/*#__PURE__*/ Z(x3),_meta:/*#__PURE__*/ Z(q)}))){};const W3=/*#__PURE__*/ K([V3,H3,U3,class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({type:/*#__PURE__*/ aS(`resource`),resource:/*#__PURE__*/ K([ybe,bbe]),annotations:/*#__PURE__*/ Z(x3),_meta:/*#__PURE__*/ Z(q)}))){},class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({...vbe.fields,type:/*#__PURE__*/ aS(`resource_link`)}))){}]);({...y3.fields}),{..._3.fields},{...g3.fields};var G3=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ nS(v3)})){},Cbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({title:/*#__PURE__*/ Z(U),readOnlyHint:/*#__PURE__*/ m3(Gx,Nt),destructiveHint:/*#__PURE__*/ m3(Gx,Mt),idempotentHint:/*#__PURE__*/ m3(Gx,Nt),openWorldHint:/*#__PURE__*/ m3(Gx,Mt)}))){};const K3=/*#__PURE__*/ Xx(/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(U,q)),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),[q]),q3=q;var J3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Tool`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),inputSchema:K3,outputSchema:/*#__PURE__*/ Z(q3),annotations:/*#__PURE__*/ Z(Cbe),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(S3)),_meta:/*#__PURE__*/ Z(q)})){};({...y3.fields});var Y3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/CallToolResult`)({..._3.fields,content:/*#__PURE__*/ G(W3),structuredContent:/*#__PURE__*/ Z(QS),isError:/*#__PURE__*/ Z(Gx)})){};({...g3.fields});var X3=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ nS(v3)})){};const Z3=/*#__PURE__*/ eS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({...g3.fields});var Q3=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:/*#__PURE__*/ W({...v3.fields,level:Z3,logger:/*#__PURE__*/ Z(U),data:Hx})})){};const $3=/*#__PURE__*/ K([V3,H3,U3,class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolUseContent`)({type:/*#__PURE__*/ aS(`tool_use`),id:U,name:U,input:/*#__PURE__*/ Yx(U,Ux),_meta:/*#__PURE__*/ Z(q)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolResultContent`)({type:/*#__PURE__*/ aS(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(W3),structuredContent:/*#__PURE__*/ Z(QS),isError:/*#__PURE__*/ Z(Gx),_meta:/*#__PURE__*/ Z(q)})){}]);var wbe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({role:b3,content:/*#__PURE__*/ K([$3,/*#__PURE__*/ G($3)]),_meta:/*#__PURE__*/ Z(q)}))){},Tbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ eS([`auto`,`required`,`none`]))})){},Ebe=class extends (/*#__PURE__*/ sS()(/*#__PURE__*/ W({name:/*#__PURE__*/ Z(U)}))){},Dbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ G(Ebe)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1})))})){},Obe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/CreateMessageResult`)({role:b3,content:/*#__PURE__*/ K([$3,/*#__PURE__*/ G($3)]),_meta:/*#__PURE__*/ Z(q),model:U,stopReason:/*#__PURE__*/ Z(U)})){},e6=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Obe,error:F3,payload:{messages:/*#__PURE__*/ G(wbe),modelPreferences:/*#__PURE__*/ Z(/*#__PURE__*/ W(Dbe.fields)),systemPrompt:/*#__PURE__*/ Z(U),includeContext:/*#__PURE__*/ Z(/*#__PURE__*/ eS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ Z(fS),maxTokens:hS,stopSequences:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(U,Ux)),tools:/*#__PURE__*/ Z(/*#__PURE__*/ G(/*#__PURE__*/ W(J3.fields))),toolChoice:/*#__PURE__*/ Z(/*#__PURE__*/ W(Tbe.fields))}})){};({..._3.fields});var kbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Root`)({uri:U,name:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)})){},t6=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ListRootsResult`)({roots:/*#__PURE__*/ G(kbe)})){},n6=class extends (/*#__PURE__*/ J(`roots/list`,{success:t6,error:F3,payload:/*#__PURE__*/ nS(g3)})){};const Abe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Z(U),type:/*#__PURE__*/ aS(`object`),properties:/*#__PURE__*/ Yx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ aS(`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__*/ aS(`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__*/ aS(`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__*/ aS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(hS),maxItems:/*#__PURE__*/ Z(hS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ aS(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ aS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(hS),maxItems:/*#__PURE__*/ Z(hS),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__*/ aS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minLength:/*#__PURE__*/ Z(hS),maxLength:/*#__PURE__*/ Z(hS),format:/*#__PURE__*/ Z(/*#__PURE__*/ eS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ eS([`number`,`integer`]),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minimum:/*#__PURE__*/ Z(fS),maximum:/*#__PURE__*/ Z(fS),default:/*#__PURE__*/ Z(fS)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ aS(`boolean`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),default:/*#__PURE__*/ Z(Gx)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),jbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitRequestFormParams`)({...g3.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ zx(`form`)),message:U,requestedSchema:Abe})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitRequestURLParams`)({...g3.fields,mode:/*#__PURE__*/ zx(`url`),message:U,elicitationId:U,url:U})){}]),Mbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitAcceptResult`)({..._3.fields,action:/*#__PURE__*/ zx(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ Yx(U,/*#__PURE__*/ K([U,fS,Gx,/*#__PURE__*/ G(U)])))})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitDeclineResult`)({..._3.fields,action:/*#__PURE__*/ eS([`cancel`,`decline`])})){}]);var r6=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Mbe,error:F3,payload:jbe})){},Nbe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};r6.payloadSchema;var i6=class extends (/*#__PURE__*/ Po(`McpReverseOperationUnsupported`)){},Pbe=class extends (/*#__PURE__*/ Po(`McpReverseOperationError`)){},a6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpRequestContext`)){},o6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpServerClient`)){},s6=class extends (/*#__PURE__*/ dbe()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},Fbe=class extends (/*#__PURE__*/ xN(I3,L3,Q3,B3,z3,X3,G3,Nbe)){},c6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/EnabledWhen`)){};const l6={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var Ibe=class extends (/*#__PURE__*/ Po(`ResourceNotFound`)){},Lbe=class extends (/*#__PURE__*/ Po(`ToolNotFound`)){},Rbe=class extends (/*#__PURE__*/ Po(`InvalidToolInput`)){},zbe=class extends (/*#__PURE__*/ Po(`InvalidToolContinuation`)){},Bbe=class extends (/*#__PURE__*/ Po(`ToolExecutionError`)){},u6=class extends (/*#__PURE__*/ Po(`UnsupportedByProtocol`)){},Vbe=class extends (/*#__PURE__*/ Po(`PromptNotFound`)){};const d6=/*#__PURE__*/ jo(),f6=/*#__PURE__*/ jo(),Hbe=/*#__PURE__*/ I(()=>{let e=/* @__PURE__ */ new Map,t=[],n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{tools:{register:t=>I(()=>{e.set(t.descriptor.name,t)}),list:t=>I(()=>{let n=[];for(let r of e.values())r.isVisible(t)&&n.push(r.descriptor);return n}),call:(t,n)=>Jf(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new Lbe({name:t.name}):r.handle(t,n)})},resources:{register:e=>I(()=>{let n=t.findIndex(t=>t.descriptor.uri===e.descriptor.uri);n===-1?t.push(e):t[n]=e}),registerTemplate:e=>I(()=>{let t=n.findIndex(t=>t.descriptor.uriTemplate===e.descriptor.uriTemplate);t===-1?n.push(e):n[t]=e}),list:e=>I(()=>t.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),listTemplates:e=>I(()=>n.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),read:H(function*(e,r){let i=t.find(t=>t.descriptor.uri===e);if(i!==void 0&&i.isVisible(r.protocol))return yield*i.read(r);for(let t of n){let n=t.match(e);if(n!==void 0&&t.isVisible(r.protocol))return yield*t.read(e,n,r)}return yield*new Ibe({uri:e})})},prompts:{register:e=>I(()=>{r.set(e.descriptor.name,e)}),list:e=>I(()=>Array.from(r.values()).filter(t=>t.isVisible(e)).map(e=>e.descriptor)),get:H(function*(e,t,n){let i=r.get(e);return i===void 0||!i.isVisible(n.protocol)?yield*new Vbe({name:e}):yield*i.get(t,n)})},completions:{register:(e,t)=>I(()=>{i.set(e,t)}),complete:H(function*(e,t){let n=e.reference.type===`prompt`?`prompt/${e.reference.name}/${e.argument.name}`:`resource/${e.reference.uriTemplate}/${e.argument.name}`,r=i.get(n);if(r===void 0)return yield*new N3({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=vte(a.values,100);return{...a,values:o,hasMore:a.hasMore===!0||o.length<a.values.length}})},registrationPresence:I(()=>({tools:e.size>0,resources:t.length>0||n.length>0,prompts:r.size>0}))}}),Ube=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),p6={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}},m6=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=gh(e.slice(9,-2));if(!xa(r))try{return Ube.decode(r.success)}catch{return}},h6=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),g6=e=>({clientId:e.clientId,protocol:h6(e),requestContext:a6.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),_6=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),v6=(e,t)=>t._tag===`Complete`?F(t.value):z(new u6({protocolVersion:e,feature:`Client input`})),y6=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},b6=e=>rn(e)&&(e.type===`tool_use`||e.type===`tool_result`),x6=e=>rn(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!rn(e))return!1;let t=e.content;return Array.isArray(t)?t.some(b6):b6(t)}):!1:!1;var S6=class e extends (/*#__PURE__*/ Po(`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`?O3:D3,message:n})}static fromFeature(t){if(N(t,`_tag`)){if(t._tag===`PromptNotFound`&&N(t,`name`)&&Gt(t.name))return new e({code:D3,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&N(t,`uri`)&&Gt(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=Wbe(t);return Sa(n)?new e(n.success):new e({code:O3,message:`MCP feature handler failed`})}};const Wbe=/*#__PURE__*/ boe(/* @__PURE__ */ W({code:fS,message:U,data:/*#__PURE__*/ Ix(Ux)})),Gbe=e=>on(e,`McpReverseOperationUnsupported`),C6=e=>t=>Gbe(t)?t:new Pbe({operation:e,cause:t}),w6=(e,t,n)=>jx(e)(n).pipe(B(Dx(t))),Kbe=(e,t,n)=>jx(e)(n).pipe(B(Dx(t,{onExcessProperty:`error`}))),T6=/*#__PURE__*/ sm(function*(e,t){return f6.$match(t,{Cancelled:e=>({tag:I3._tag,payload:I3.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:L3._tag,payload:L3.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:Q3._tag,payload:Q3.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:B3._tag,payload:B3.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:z3._tag,payload:z3.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:X3._tag,payload:X3.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:G3._tag,payload:G3.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),E6=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},D6=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=YS(e.payloadSchema);n={decode:Dx(r),encode:Ax(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`?$f(`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=>Tle(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(V(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},O6=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,qbe=/*#__PURE__*/ H(function*(e){if(e.length===0)return yield*new yd(`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 yd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(O6(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(O6(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(O6(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${O6(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(`${O6(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*$f(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),k6=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),Jbe=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=(n,r)=>{let i=r[`mcp-session-id`];return i===void 0?t.get(n):e.get(i)};return{registerHttp:(t,n)=>{let r=k6(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=k6(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 S6({code:E3,message:`Resource subscriptions are not supported`})):I(()=>i.add(e)).pipe(cp)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new S6({code:E3,message:`Resource subscriptions are not supported`})):I(()=>i.delete(e)).pipe(cp)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?p6[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`?p6[n.level].order>=p6[e.level].order:TD(p6[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)}}},A6=`mcp-session-id`,j6=`mcp-protocol-version`,M6=`io.modelcontextprotocol/protocolVersion`,N6=`io.modelcontextprotocol/clientCapabilities`,P6=-32022,F6=e=>typeof e==`object`&&e?e:void 0,I6=e=>{let t=F6(e);return t!==void 0&&M6 in t?{present:!0,value:t[M6]}:{present:!1,value:void 0}},Ybe=e=>I6(F6(F6(e)?.params)?._meta).present,Xbe=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},L6=e=>({_tag:`Rejected`,status:400,error:{code:k3,message:e}}),R6=/*#__PURE__*/ xN(hbe),z6=e=>({_tag:`Stateful`,transport:e});var B6=class extends (/*#__PURE__*/ P()(`effect/ai/McpRuntime/ServerRuntime`)){};const V6=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),Zbe=/*#__PURE__*/ H(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:Jbe(),n=e.map(e=>e.protocolVersion),r,i;for(let t of e)if(t.runtime._tag===`Stateless`){if(r!==void 0)return yield*new yd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*qbe(e),o=/* @__PURE__ */ new Set,s=e=>({code:P6,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[j6],a=e[A6],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 L6(`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[j6],a=F6(n),o=F6(F6(a?.params)?._meta),l=I6(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 L6(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:D3,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return L6(`MCP-Protocol-Version header does not match request metadata`);if(!f&&F6(o?.[N6])===void 0)return{_tag:`Rejected`,status:400,error:{code:D3,message:`${N6} 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 L6(`Mcp-Method header does not match request method`);let n=Xbe(t);if(n!==void 0){let t=F6(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||m6(r)!==t)return L6(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return B6.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:H(function*(e,n,o){let c=F6(o.payload)?._meta,l=I6(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=V6(a.protocols,e);if(t===void 0)return yield*new S6({code:P6,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?V6(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*$f(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new S6(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=a6.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?pj({status:e}):vj({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(xa(r)){let t=e[j6];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 A3({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new j3({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(Ybe)||a.some(e=>N(e,`method`)&&e.method===`initialize`)||t.binding?.protocol.runtime.transport.jsonRpc.acceptsBatches!==!0?i(400):{_tag:`Accepted`,acknowledge:!a.some(e=>N(e,`method`)&&N(e,`id`)),isSubscription:!1}}let o=N(a,`id`),c=o&&(typeof a.id==`string`||typeof a.id==`number`)?a.id:null,u=N(a,`jsonrpc`)&&a.jsonrpc===`2.0`,d=!o||typeof a.id==`string`||typeof a.id==`number`,f=u&&d&&N(a,`method`)&&typeof a.method==`string`,p=o&&(typeof a.id==`string`||typeof a.id==`number`||a.id===null),m=N(a,`result`),h=N(a,`error`),g=u&&p&&m!==h,_=l(e,a);if(_._tag===`Rejected`)return i(_.status,_.error,c);if(!f&&!g)return i(200,new j3({message:`Invalid Request`}),c);let v=N(a,`method`)&&a.method===`initialize`,y=e[A6]!==void 0;return v&&y?i(400,new j3({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 j3({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 M3({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=>Jf(()=>{let n=e[A6];if(n===void 0)return F(pj({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return F(pj({status:r.status}));let i=r.binding;return t.terminateSession(n),sp(Uf(o,e=>e(i),{discard:!0}),pj({status:204}))}),onSessionTerminated:e=>Ip(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*$f(`MCP sessionful runtime invariant failed`);yield*o.install(n,R6,R6.of({ping:()=>F({})}));let r={initialize:H(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*tp(s=>{let c=oa(s.context,_M),l={completions:!0,logging:!0,...o.tools?{tools:{listChanged:!0}}:{},...o.resources?{resources:{listChanged:!0,subscribe:c===void 0}}:{},...o.prompts?{prompts:{listChanged:!0}}:{},...e.serverInfo.extensions?{extensions:e.serverInfo.extensions}:{}},u={initializePayload:_be.payloadSchema.make({protocolVersion:r,capabilities:i.clientCapabilities,clientInfo:i.clientInfo,_meta:i.requestMetadata}),negotiatedProfile:i,protocol:n,supportsResourceSubscriptions:c===void 0&&l.resources?.subscribe===!0,logLevel:e.defaultLogLevel};if(c!==void 0){let e=crypto.randomUUID();t.registerHttp(e,u),TM(c,(t,r)=>F(Cj(r,{[A6]:e,[j6]:n.protocolVersion})))}else t.registerConnection(a,u);return F({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:C3.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 $i(r)})})}),H6=e=>lf(B6)(Zbe(e)),U6=e=>Ix(e).pipe(rS(Rx(Lx(e)),{decode:Q_(),encode:tv(Bi(Ii))})),W6=q,Qbe=/*#__PURE__*/ K([U,fS]),G6=/*#__PURE__*/ K([U,fS]),K6=/*#__PURE__*/ eS([`user`,`assistant`]),q6=/*#__PURE__*/ eS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),J6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ U6(/*#__PURE__*/ Xx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ U6(G6)}),[q]))}),Y6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ U6(W6)}),X6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ U6(W6)}),Z6=/*#__PURE__*/ W({...J6.fields,cursor:/*#__PURE__*/ U6(U)}),Q6=/*#__PURE__*/ W({...X6.fields,nextCursor:/*#__PURE__*/ U6(U)}),$be=/*#__PURE__*/ W({extensions:/*#__PURE__*/ U6(/*#__PURE__*/ Yx(/*#__PURE__*/ Bx([U,`/`,U]),QS)),experimental:/*#__PURE__*/ U6(/*#__PURE__*/ Yx(U,W6)),roots:/*#__PURE__*/ U6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ U6(Gx)})),sampling:/*#__PURE__*/ U6(W6)}),exe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ U6(/*#__PURE__*/ Yx(/*#__PURE__*/ Bx([U,`/`,U]),QS)),experimental:/*#__PURE__*/ U6(/*#__PURE__*/ Yx(U,W6)),logging:/*#__PURE__*/ U6(W6),prompts:/*#__PURE__*/ U6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ U6(Gx)})),resources:/*#__PURE__*/ U6(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ U6(Gx),listChanged:/*#__PURE__*/ U6(Gx)})),tools:/*#__PURE__*/ U6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ U6(Gx)}))}),$6=/*#__PURE__*/ W({code:hS,message:U,data:/*#__PURE__*/ U6(Hx)}),e8=/*#__PURE__*/ W({audience:/*#__PURE__*/ U6(/*#__PURE__*/ G(K6)),priority:/*#__PURE__*/ U6(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1})))}),txe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ U6(U),text:U}),nxe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ U6(U),blob:U}),rxe=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`text`),text:U,annotations:/*#__PURE__*/ U6(e8)}),ixe=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`image`),data:U,mimeType:U,annotations:/*#__PURE__*/ U6(e8)}),axe=/*#__PURE__*/ W({uri:U,name:U,description:/*#__PURE__*/ U6(U),mimeType:/*#__PURE__*/ U6(U),size:/*#__PURE__*/ U6(fS),annotations:/*#__PURE__*/ U6(e8)}),oxe=/*#__PURE__*/ W({uriTemplate:U,name:U,description:/*#__PURE__*/ U6(U),mimeType:/*#__PURE__*/ U6(U),annotations:/*#__PURE__*/ U6(e8)}),t8=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ U6(U),required:/*#__PURE__*/ U6(Gx)}),sxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ U6(U),arguments:/*#__PURE__*/ U6(/*#__PURE__*/ G(t8))}),cxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ U6(U),inputSchema:/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ U6(/*#__PURE__*/ Yx(U,W6)),required:/*#__PURE__*/ U6(/*#__PURE__*/ G(U))})}),n8=/*#__PURE__*/ W({hints:/*#__PURE__*/ U6(/*#__PURE__*/ G(/* @__PURE__ */ W({name:/*#__PURE__*/ U6(U)}))),costPriority:/*#__PURE__*/ U6(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ U6(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ U6(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1})))}),lxe=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`ref/prompt`),name:U}),r8=/*#__PURE__*/ W({uri:U,name:/*#__PURE__*/ U6(U)});({...X6.fields}),{...Q6.fields},{...Q6.fields},{...X6.fields},{...Q6.fields},{...X6.fields},{...Q6.fields},{...X6.fields},{...X6.fields};const uxe=/*#__PURE__*/ W({...X6.fields,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U),total:/*#__PURE__*/ U6(fS),hasMore:/*#__PURE__*/ U6(Gx)})}),dxe=/*#__PURE__*/ W({...X6.fields,roots:/*#__PURE__*/ G(r8)});var i8=class extends (/*#__PURE__*/ J(`ping`,{success:X6,error:$6,payload:/*#__PURE__*/ nS(J6)})){};({...J6.fields}),{...J6.fields};var a8=class extends (/*#__PURE__*/ J(`logging/setLevel`,{success:X6,error:$6,payload:{...J6.fields,level:q6}})){};({...J6.fields}),{...J6.fields};var o8=class extends (/*#__PURE__*/ J(`resources/subscribe`,{success:X6,error:$6,payload:{...J6.fields,uri:U}})){},s8=class extends (/*#__PURE__*/ J(`resources/unsubscribe`,{success:X6,error:$6,payload:{...J6.fields,uri:U}})){};({...J6.fields}),{...J6.fields};var c8=class extends (/*#__PURE__*/ J(`roots/list`,{success:dxe,error:$6,payload:/*#__PURE__*/ nS(J6)})){},l8=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...Y6.fields,requestId:Qbe,reason:/*#__PURE__*/ U6(U)}})){};({...Y6.fields});var u8=class extends (/*#__PURE__*/ J(`notifications/initialized`,{payload:/*#__PURE__*/ nS(Y6)})){},d8=class extends (/*#__PURE__*/ J(`notifications/roots/list_changed`,{payload:/*#__PURE__*/ nS(Y6)})){},f8=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...Y6.fields,level:q6,logger:/*#__PURE__*/ U6(U),data:Hx}})){},p8=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...Y6.fields,uri:U}})){},m8=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ nS(Y6)})){},h8=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ nS(Y6)})){},g8=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ nS(Y6)})){};const _8=U6,fxe=/*#__PURE__*/ W({...exe.fields,completions:/*#__PURE__*/ _8(/*#__PURE__*/ W({}))}),pxe=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`audio`),data:U,mimeType:U,annotations:/*#__PURE__*/ _8(e8)}),v8=/*#__PURE__*/ W({title:/*#__PURE__*/ _8(U),readOnlyHint:/*#__PURE__*/ _8(Gx),destructiveHint:/*#__PURE__*/ _8(Gx),idempotentHint:/*#__PURE__*/ _8(Gx),openWorldHint:/*#__PURE__*/ _8(Gx)});({...cxe.fields}),{...X6.fields},{...X6.fields},{...Q6.fields},{...X6.fields},{...X6.fields},{...J6.fields},{...J6.fields},{...J6.fields},{...J6.fields};var y8=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...Y6.fields,progressToken:G6,progress:fS,total:/*#__PURE__*/ _8(fS),message:/*#__PURE__*/ _8(U)}})){};const b8=`2025-06-18`,x8=U6,S8=q,C8=/*#__PURE__*/ x8(S8),w8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ x8(U),version:U}),T8=/*#__PURE__*/ W({...$be.fields,elicitation:/*#__PURE__*/ x8(/*#__PURE__*/ W({}))}),E8=/*#__PURE__*/ W({audience:/*#__PURE__*/ x8(/*#__PURE__*/ G(K6)),priority:/*#__PURE__*/ x8(/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1})))}),D8=/*#__PURE__*/ W({...axe.fields,title:/*#__PURE__*/ x8(U),annotations:/*#__PURE__*/ x8(E8),_meta:C8}),O8=/*#__PURE__*/ W({...oxe.fields,title:/*#__PURE__*/ x8(U),annotations:/*#__PURE__*/ x8(E8),_meta:C8}),k8=/*#__PURE__*/ K([/* @__PURE__ */ W({...txe.fields,_meta:C8}),/* @__PURE__ */ W({...nxe.fields,_meta:C8})]),mxe=/*#__PURE__*/ W({...t8.fields,title:/*#__PURE__*/ x8(U)}),A8=/*#__PURE__*/ W({...sxe.fields,title:/*#__PURE__*/ x8(U),arguments:/*#__PURE__*/ x8(/*#__PURE__*/ G(mxe)),_meta:C8}),j8=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`resource`),resource:k8,annotations:/*#__PURE__*/ x8(E8),_meta:C8}),hxe=/*#__PURE__*/ W({...D8.fields,type:/*#__PURE__*/ zx(`resource_link`)}),M8=/*#__PURE__*/ W({...rxe.fields,annotations:/*#__PURE__*/ x8(E8),_meta:C8}),N8=/*#__PURE__*/ W({...ixe.fields,annotations:/*#__PURE__*/ x8(E8),_meta:C8}),P8=/*#__PURE__*/ W({...pxe.fields,annotations:/*#__PURE__*/ x8(E8),_meta:C8}),F8=/*#__PURE__*/ K([M8,N8,P8,j8,hxe]),I8=/*#__PURE__*/ K([M8,N8,P8]),gxe=/*#__PURE__*/ W({role:K6,content:F8}),_xe=/*#__PURE__*/ W({role:K6,content:I8}),vxe=/*#__PURE__*/ W({...fxe.fields}),L8=/*#__PURE__*/ W({...X6.fields,protocolVersion:U,capabilities:vxe,serverInfo:w8,instructions:/*#__PURE__*/ x8(U)});var R8=class extends (/*#__PURE__*/ J(`initialize`,{success:L8,error:$6,payload:{...J6.fields,protocolVersion:U,capabilities:T8,clientInfo:w8}})){};const z8=/*#__PURE__*/ Xx(/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ x8(/*#__PURE__*/ Yx(U,S8)),required:/*#__PURE__*/ x8(/*#__PURE__*/ G(U))}),[q]),B8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ x8(U),description:/*#__PURE__*/ x8(U),inputSchema:z8,outputSchema:/*#__PURE__*/ x8(z8),annotations:/*#__PURE__*/ x8(v8),_meta:C8}),V8=/*#__PURE__*/ W({...X6.fields,content:/*#__PURE__*/ G(F8),structuredContent:/*#__PURE__*/ x8(S8),isError:/*#__PURE__*/ x8(Gx)}),yxe=/*#__PURE__*/ W({...X6.fields,role:K6,content:I8,model:U,stopReason:/*#__PURE__*/ x8(U)});var H8=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:yxe,error:$6,payload:{...J6.fields,messages:/*#__PURE__*/ G(_xe),modelPreferences:/*#__PURE__*/ x8(n8),systemPrompt:/*#__PURE__*/ x8(U),includeContext:/*#__PURE__*/ x8(/*#__PURE__*/ eS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ x8(fS),maxTokens:fS,stopSequences:/*#__PURE__*/ x8(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ x8(S8)}})){};const U8=/*#__PURE__*/ W({...lxe.fields,title:/*#__PURE__*/ x8(U)}),W8=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`ref/resource`),uri:U}),G8=uxe;var K8=class extends (/*#__PURE__*/ J(`completion/complete`,{success:G8,error:$6,payload:{...J6.fields,ref:/*#__PURE__*/ K([U8,W8]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ x8(/*#__PURE__*/ W({arguments:/*#__PURE__*/ x8(/*#__PURE__*/ Yx(U,U))}))}})){};const q8=/*#__PURE__*/ W({...Q6.fields,resources:/*#__PURE__*/ G(D8)}),J8=/*#__PURE__*/ W({...Q6.fields,resourceTemplates:/*#__PURE__*/ G(O8)}),Y8=/*#__PURE__*/ W({...X6.fields,contents:/*#__PURE__*/ G(k8)}),X8=/*#__PURE__*/ W({...Q6.fields,prompts:/*#__PURE__*/ G(A8)}),Z8=/*#__PURE__*/ W({...X6.fields,description:/*#__PURE__*/ x8(U),messages:/*#__PURE__*/ G(gxe)}),Q8=/*#__PURE__*/ W({...Q6.fields,tools:/*#__PURE__*/ G(B8)});var bxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:q8,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},xxe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:J8,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},$8=class extends (/*#__PURE__*/ J(`resources/read`,{success:Y8,error:$6,payload:{...J6.fields,uri:U}})){},Sxe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:X8,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},Cxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:Z8,error:$6,payload:{...J6.fields,name:U,arguments:/*#__PURE__*/ x8(/*#__PURE__*/ Yx(U,U))}})){},wxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:Q8,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},e5=class extends (/*#__PURE__*/ J(`tools/call`,{success:V8,error:$6,payload:{...J6.fields,name:U,arguments:/*#__PURE__*/ x8(S8)}})){};const Txe=/*#__PURE__*/ W({...X6.fields,action:/*#__PURE__*/ eS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ x8(/*#__PURE__*/ Yx(U,/*#__PURE__*/ K([U,fS,Gx])))}),Exe=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ Yx(U,/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ x8(U),description:/*#__PURE__*/ x8(U),minLength:/*#__PURE__*/ x8(hS),maxLength:/*#__PURE__*/ x8(hS),format:/*#__PURE__*/ x8(/*#__PURE__*/ eS([`email`,`uri`,`date`,`date-time`]))}),/* @__PURE__ */ W({type:/*#__PURE__*/ eS([`number`,`integer`]),title:/*#__PURE__*/ x8(U),description:/*#__PURE__*/ x8(U),minimum:/*#__PURE__*/ x8(fS),maximum:/*#__PURE__*/ x8(fS)}),/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`boolean`),title:/*#__PURE__*/ x8(U),description:/*#__PURE__*/ x8(U),default:/*#__PURE__*/ x8(Gx)}),/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ x8(U),description:/*#__PURE__*/ x8(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ x8(/*#__PURE__*/ G(U))})])),required:/*#__PURE__*/ x8(/*#__PURE__*/ G(U))});var t5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Txe,error:$6,payload:{...J6.fields,message:U,requestedSchema:Exe}})){},Dxe=class extends (/*#__PURE__*/ xN(i8,R8,K8,a8,Cxe,Sxe,bxe,xxe,$8,o8,s8,e5,wxe)){},n5=class extends (/*#__PURE__*/ xN(l8,y8,u8,d8)){},Oxe=class extends (/*#__PURE__*/ xN(i8,H8,c8,t5)){},kxe=class extends (/*#__PURE__*/ xN(l8,y8,f8,p8,m8,h8,g8)){};const r5=/*#__PURE__*/ (/* @__PURE__ */ Dxe.omit(`ping`).middleware(s6).add(i8)).merge(n5),i5=/*#__PURE__*/ r5.omit(`ping`),Axe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||rn(e.properties)&&Object.values(e.properties).every(rn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Gt);return t&&n},jxe=e=>({protocolVersion:b8,clientCapabilities:w3.make(e.capabilities),clientInfo:C3.make(e.clientInfo),requestMetadata:e._meta}),a5=(e,t)=>new i6({operation:e,protocolVersion:b8,reason:t}),o5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(a5(t,`Client did not advertise the ${n} capability`)),s5=/*#__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:hh(e.data),annotations:e.annotations,_meta:e._meta})),jO({type:`resource`},e=>{let t=e.resource;return`text`in t?j8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):j8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:hh(t.blob)},annotations:e.annotations,_meta:e._meta})}),zO)}),Mxe=e=>`text`in e?{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,text:e.text}:{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,blob:hh(e.blob)},Nxe=e=>e===void 0||Pxe(e)?e:void 0,Pxe=e=>rn(e),Fxe=/*#__PURE__*/ D6({protocolVersion:b8,runtime:/*#__PURE__*/ z6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:r5,clientNotificationRpcs:n5,serverRequestRpcs:Oxe,serverNotificationRpcs:kxe,handlerRpcs:i5,makeHandlers:(e,t)=>i5.of({initialize:(e,{client:n})=>t.initialize(b8,jxe(e),n.id).pipe(V(e=>L8.make({protocolVersion:b8,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(sp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(d6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(d6.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(d6.RootsChanged(),n.id,r),"resources/list":t=>o6.use(t=>e.resources.list(h6(t))).pipe(V(e=>q8.make({resources:e}))),"resources/templates/list":t=>o6.use(t=>e.resources.listTemplates(h6(t))).pipe(V(e=>J8.make({resourceTemplates:e}))),"resources/read":H(function*({uri:t}){let n=yield*o6,r=yield*e.resources.read(t,g6(n)).pipe(mp(S6.fromFeature));return Y8.make({contents:r.contents.map(Mxe),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(sp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(sp({})),"prompts/list":t=>o6.use(t=>e.prompts.list(h6(t))).pipe(V(e=>X8.make({prompts:e}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*o6,i=yield*e.prompts.get(n,t??{},g6(r)).pipe(mp(S6.fromFeature));if(i._tag===`InputRequired`)return yield*S6.fromFeature(new u6({protocolVersion:b8,feature:`prompt input requirements`}));let a=i.value,o=yield*Uf(a.messages,e=>s5(e.content).pipe(V(t=>({role:e.role,content:t})),mp(S6.fromTool)));return Z8.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*o6,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},g6(n)).pipe(mp(S6.fromFeature));return G8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*o6,n=yield*e.tools.list(h6(t));return Q8.make({tools:n.map(e=>B8.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:Axe(e.outputSchema)?e.outputSchema:void 0,annotations:e.annotations===void 0?void 0:v8.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*o6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},g6(n)).pipe(B(e=>v6(b8,e)),mp(S6.fromTool)),i=yield*Uf(y6(r),s5).pipe(mp(S6.fromTool)),a=Nxe(r.structuredContent);return V8.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*o5(e,`roots/list`,`roots`);let r=yield*w6(n6.payloadSchema,c8.payloadSchema,n).pipe(mp(()=>a5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(mp(C6(`roots/list`)));return new t6({roots:i})}),createMessage:H(function*(n){yield*o5(e,`sampling/createMessage`,`sampling`);let r=yield*Kbe(e6.payloadSchema,H8.payloadSchema,n).pipe(mp(()=>a5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(mp(C6(`sampling/createMessage`)));return yield*w6(H8.successSchema,e6.successSchema,i).pipe(mp(()=>a5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*o5(e,`elicitation/create`,`elicitation`);let r=n.mode===`form`?doe(n,[`mode`]):n,i=yield*Dx(t5.payloadSchema,{onExcessProperty:`error`})(r).pipe(mp(()=>a5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(mp(C6(`elicitation/create`)));return yield*w6(t5.successSchema,r6.successSchema,a).pipe(mp(()=>a5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>T6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Dx(l8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),c5=`2025-11-25`,Q=U6,l5=q,u5=/*#__PURE__*/ Q(l5),d5=/*#__PURE__*/ W({src:U,mimeType:/*#__PURE__*/ Q(U),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ eS([`light`,`dark`]))}),f5=/*#__PURE__*/ W({...w8.fields,description:/*#__PURE__*/ Q(U),websiteUrl:/*#__PURE__*/ Q(U),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(d5))}),Ixe=/*#__PURE__*/ W({...T8.fields,sampling:/*#__PURE__*/ Q(/*#__PURE__*/ W({context:/*#__PURE__*/ Q(l5),tools:/*#__PURE__*/ Q(l5)})),elicitation:/*#__PURE__*/ Q(/*#__PURE__*/ W({form:/*#__PURE__*/ Q(l5),url:/*#__PURE__*/ Q(l5)}))}),p5=/*#__PURE__*/ W({...E8.fields,lastModified:/*#__PURE__*/ Q(U)}),m5=/*#__PURE__*/ W({...D8.fields,annotations:/*#__PURE__*/ Q(p5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(d5))}),h5=/*#__PURE__*/ W({...O8.fields,annotations:/*#__PURE__*/ Q(p5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(d5))}),g5=/*#__PURE__*/ W({...A8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(d5))}),_5=/*#__PURE__*/ W({...M8.fields,annotations:/*#__PURE__*/ Q(p5)}),v5=/*#__PURE__*/ W({...N8.fields,annotations:/*#__PURE__*/ Q(p5)}),y5=/*#__PURE__*/ W({...P8.fields,annotations:/*#__PURE__*/ Q(p5)}),b5=/*#__PURE__*/ W({...j8.fields,annotations:/*#__PURE__*/ Q(p5)}),x5=/*#__PURE__*/ K([_5,v5,y5,/* @__PURE__ */ W({...m5.fields,type:/*#__PURE__*/ zx(`resource_link`)}),b5]),Lxe=/*#__PURE__*/ W({role:K6,content:x5}),S5=/*#__PURE__*/ W({...B8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(d5))}),C5=/*#__PURE__*/ W({...V8.fields,content:/*#__PURE__*/ G(x5)});var Rxe=class extends (/*#__PURE__*/ J(`tools/call`,{success:C5,error:$6,payload:e5.payloadSchema})){};const w5=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`tool_use`),id:U,name:U,input:l5,_meta:u5}),T5=/*#__PURE__*/ K([_5,v5,y5,w5,/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(x5),structuredContent:/*#__PURE__*/ Q(l5),isError:/*#__PURE__*/ Q(Gx),_meta:u5})]),E5=/*#__PURE__*/ W({role:K6,content:/*#__PURE__*/ K([T5,/*#__PURE__*/ G(T5)]),_meta:u5}),D5=/*#__PURE__*/ W({mode:/*#__PURE__*/ Q(/*#__PURE__*/ eS([`auto`,`required`,`none`]))}),zxe=/*#__PURE__*/ W({...X6.fields,...E5.fields,model:U,stopReason:/*#__PURE__*/ Q(U)});var O5=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:zxe,error:$6,payload:{...H8.payloadSchema.fields,messages:/*#__PURE__*/ G(E5),maxTokens:hS,tools:/*#__PURE__*/ Q(/*#__PURE__*/ G(S5)),toolChoice:/*#__PURE__*/ Q(D5)}})){};const k5=/*#__PURE__*/ W({...r8.fields,_meta:u5}),Bxe=/*#__PURE__*/ W({...X6.fields,roots:/*#__PURE__*/ G(k5)});var A5=class extends (/*#__PURE__*/ J(`roots/list`,{success:Bxe,error:$6,payload:/*#__PURE__*/ nS(J6)})){};const j5=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minLength:/*#__PURE__*/ Q(hS),maxLength:/*#__PURE__*/ Q(hS),format:/*#__PURE__*/ Q(/*#__PURE__*/ eS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(U)}),M5=/*#__PURE__*/ W({type:/*#__PURE__*/ eS([`number`,`integer`]),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minimum:/*#__PURE__*/ Q(fS),maximum:/*#__PURE__*/ Q(fS),default:/*#__PURE__*/ Q(fS)}),N5=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`boolean`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),default:/*#__PURE__*/ Q(Gx)}),P5=/*#__PURE__*/ W({const:U,title:U}),F5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Q(U)}),/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),oneOf:/*#__PURE__*/ G(P5),default:/*#__PURE__*/ Q(U)})]),I5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(hS),maxItems:/*#__PURE__*/ Q(hS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(hS),maxItems:/*#__PURE__*/ Q(hS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(P5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))})]),L5=/*#__PURE__*/ W({type:/*#__PURE__*/ zx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Q(U)}),Vxe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Q(U),type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ Yx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([L5,F5,I5]),j5,M5,N5])),required:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),Hxe=/*#__PURE__*/ K([/* @__PURE__ */ W({...J6.fields,mode:/*#__PURE__*/ Q(/*#__PURE__*/ zx(`form`)),message:U,requestedSchema:Vxe}),/* @__PURE__ */ W({...J6.fields,mode:/*#__PURE__*/ zx(`url`),message:U,elicitationId:U,url:U})]),Uxe=/*#__PURE__*/ W({...X6.fields,action:/*#__PURE__*/ eS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ Q(/*#__PURE__*/ Yx(U,/*#__PURE__*/ K([U,fS,Gx,/*#__PURE__*/ G(U)])))});var R5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Uxe,error:$6,payload:Hxe})){},Wxe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};const z5=/*#__PURE__*/ W({...L8.fields,serverInfo:f5});var Gxe=class extends (/*#__PURE__*/ J(`initialize`,{success:z5,error:$6,payload:{...R8.payloadSchema.fields,capabilities:Ixe,clientInfo:f5}})){};const B5=/*#__PURE__*/ W({...Q6.fields,resources:/*#__PURE__*/ G(m5)}),V5=/*#__PURE__*/ W({...Q6.fields,resourceTemplates:/*#__PURE__*/ G(h5)}),H5=/*#__PURE__*/ W({...Q6.fields,prompts:/*#__PURE__*/ G(g5)}),U5=/*#__PURE__*/ W({...Z8.fields,messages:/*#__PURE__*/ G(Lxe)}),W5=/*#__PURE__*/ W({...Q6.fields,tools:/*#__PURE__*/ G(S5)});var Kxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:B5,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},qxe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:V5,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},Jxe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:H5,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},Yxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:U5,error:$6,payload:{...J6.fields,name:U,arguments:/*#__PURE__*/ Q(/*#__PURE__*/ Yx(U,U))}})){},Xxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:W5,error:$6,payload:/*#__PURE__*/ nS(Z6)})){},Zxe=class extends (/*#__PURE__*/ xN(i8,Gxe,K8,a8,Yxe,Jxe,Kxe,qxe,$8,o8,s8,Rxe,Xxe)){},G5=class extends (/*#__PURE__*/ xN(l8,y8,u8,d8)){},Qxe=class extends (/*#__PURE__*/ xN(i8,O5,A5,R5)){},$xe=class extends (/*#__PURE__*/ xN(l8,y8,f8,p8,m8,h8,g8,Wxe)){};const K5=/*#__PURE__*/ (/* @__PURE__ */ Zxe.omit(`ping`).middleware(s6).add(i8)).merge(G5),q5=/*#__PURE__*/ K5.omit(`ping`),eSe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||rn(e.properties)&&Object.values(e.properties).every(rn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Gt);return t&&n},J5=(e,t)=>new i6({operation:e,protocolVersion:c5,reason:t}),Y5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(J5(t,`Client did not advertise the ${n} capability`)),tSe=e=>e.stopReason===`toolUse`||(`type`in e.content?e.content.type===`tool_use`||e.content.type===`tool_result`:e.content.some(e=>e.type===`tool_use`||e.type===`tool_result`)),nSe=(e,t)=>{let n=e.clientCapabilities.elicitation;return n===void 0?!1:t===`form`?n.form!==void 0||n.url===void 0:n.url!==void 0},X5=/*#__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:hh(e.data),annotations:e.annotations,_meta:e._meta})),jO({type:`resource`},e=>{let t=e.resource;return`text`in t?b5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):b5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:hh(t.blob)},annotations:e.annotations,_meta:e._meta})}),zO)}),rSe=e=>e===void 0||iSe(e)?e:void 0,iSe=e=>rn(e),aSe=/*#__PURE__*/ D6({protocolVersion:c5,runtime:/*#__PURE__*/ z6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:K5,clientNotificationRpcs:G5,serverRequestRpcs:Qxe,serverNotificationRpcs:$xe,handlerRpcs:q5,makeHandlers:(e,t)=>q5.of({initialize:(e,{client:n})=>t.initialize(c5,{protocolVersion:c5,clientCapabilities:w3.make(e.capabilities),clientInfo:C3.make(e.clientInfo),requestMetadata:e._meta},n.id).pipe(V(e=>z5.make({protocolVersion:c5,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(sp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(d6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(d6.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(d6.RootsChanged(),n.id,r),"resources/list":()=>o6.use(t=>e.resources.list(h6(t))).pipe(V(e=>B5.make({resources:e.map(e=>m5.make(e))}))),"resources/templates/list":()=>o6.use(t=>e.resources.listTemplates(h6(t))).pipe(V(e=>V5.make({resourceTemplates:e.map(e=>h5.make(e))}))),"resources/read":H(function*({uri:t}){let n=yield*o6,r=yield*e.resources.read(t,g6(n)).pipe(mp(S6.fromFeature));return Y8.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:hh(e.blob)}),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(sp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(sp({})),"prompts/list":()=>o6.use(t=>e.prompts.list(h6(t))).pipe(V(e=>H5.make({prompts:e.map(e=>g5.make(e))}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*o6,i=yield*e.prompts.get(n,t??{},g6(r)).pipe(mp(S6.fromFeature));if(i._tag===`InputRequired`)return yield*S6.fromFeature(new u6({protocolVersion:c5,feature:`prompt input requirements`}));let a=i.value,o=yield*Uf(a.messages,e=>X5(e.content).pipe(V(t=>({role:e.role,content:t})),mp(S6.fromTool)));return U5.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*o6,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},g6(n)).pipe(mp(S6.fromFeature));return G8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*o6,n=yield*e.tools.list(h6(t));return W5.make({tools:n.map(e=>S5.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:eSe(e.outputSchema)?e.outputSchema:void 0,icons:e.icons,annotations:e.annotations===void 0?void 0:v8.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*o6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},g6(n)).pipe(B(e=>v6(c5,e)),up([`InvalidToolInput`,`ToolExecutionError`],e=>F(Y3.make({content:[V3.make({type:`text`,text:e.message})],isError:!0}))),mp(S6.fromTool)),i=yield*Uf(y6(r),X5).pipe(mp(S6.fromTool)),a=rSe(r.structuredContent);return C5.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*Y5(e,`roots/list`,`roots`);let r=yield*w6(n6.payloadSchema,A5.payloadSchema,n).pipe(mp(()=>J5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(mp(C6(`roots/list`)));return new t6({roots:i})}),createMessage:H(function*(n){if(yield*Y5(e,`sampling/createMessage`,`sampling`),x6(n)&&e.clientCapabilities.sampling?.tools==null)return yield*J5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`);if((n.includeContext===`thisServer`||n.includeContext===`allServers`)&&e.clientCapabilities.sampling?.context==null)return yield*J5(`sampling/createMessage`,`Client did not advertise the sampling.context capability`);let r=yield*w6(e6.payloadSchema,O5.payloadSchema,n).pipe(mp(()=>J5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(mp(C6(`sampling/createMessage`)));return tSe(i)&&e.clientCapabilities.sampling?.tools==null?yield*J5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`):yield*w6(O5.successSchema,e6.successSchema,i).pipe(mp(()=>J5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*Y5(e,`elicitation/create`,`elicitation`);let r=n.mode===`url`?`url`:`form`;if(!nSe(e,r))return yield*J5(`elicitation/create`,`Client did not advertise the elicitation.${r} capability`);let i=yield*w6(r6.payloadSchema,R5.payloadSchema,n).pipe(mp(()=>J5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(mp(C6(`elicitation/create`)));return yield*w6(R5.successSchema,r6.successSchema,a).pipe(mp(()=>J5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>e._tag===`ElicitationComplete`?F({tag:`notifications/elicitation/complete`,payload:{elicitationId:e.elicitationId}}):T6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Dx(l8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),Z5=`2026-07-28`,$=U6,Q5=/*#__PURE__*/ $(q),$5=/*#__PURE__*/ K([U,hS]),e7=$5,t7=K6,n7=q6,r7=f5,oSe=/*#__PURE__*/ Xx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Yx(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__*/ Yx(U,q))}),[q]),sSe=/*#__PURE__*/ Xx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Yx(U,q)),logging:/*#__PURE__*/ $(q),completions:/*#__PURE__*/ $(q),prompts:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Gx)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ $(Gx),listChanged:/*#__PURE__*/ $(Gx)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Gx)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ Yx(U,q))}),[q]),i7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ $(e7),"io.modelcontextprotocol/protocolVersion":U,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $(r7),"io.modelcontextprotocol/clientCapabilities":oSe,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(n7)}),[q]),a7=/*#__PURE__*/ W({_meta:i7}),o7=/*#__PURE__*/ W({_meta:/*#__PURE__*/ $(/* @__PURE__ */ Xx(/*#__PURE__*/ W({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $($5)}),[q]))}),s7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":r7}),[q]),c7={_meta:s7,resultType:/*#__PURE__*/ zx(`complete`)},l7=/*#__PURE__*/ W({code:hS,message:U,data:/*#__PURE__*/ $(QS)}),cSe=p5,u7=/*#__PURE__*/ W({...m5.fields,size:/*#__PURE__*/ $(hS),annotations:/*#__PURE__*/ $(cSe)}),d7=h5,lSe=k8,f7=_5,p7=v5,m7=y5,h7=/*#__PURE__*/ K([f7,p7,m7,/* @__PURE__ */ W({...u7.fields,type:/*#__PURE__*/ zx(`resource_link`)}),b5]),g7=g5,uSe=/*#__PURE__*/ W({role:t7,content:h7}),dSe=/*#__PURE__*/ Xx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ zx(`object`)}),[q]),fSe=/*#__PURE__*/ Xx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U)}),[q]),pSe=v8,_7=/*#__PURE__*/ W({...S5.fields,inputSchema:dSe,outputSchema:/*#__PURE__*/ $(fSe),annotations:/*#__PURE__*/ $(pSe)}),v7=/*#__PURE__*/ K([f7,p7,m7,w5,/* @__PURE__ */ W({type:/*#__PURE__*/ zx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(h7),structuredContent:/*#__PURE__*/ $(QS),isError:/*#__PURE__*/ $(Gx),_meta:Q5})]),y7=/*#__PURE__*/ W({role:t7,content:/*#__PURE__*/ K([v7,/*#__PURE__*/ G(v7)]),_meta:Q5}),mSe=/*#__PURE__*/ Xx(/*#__PURE__*/ W({name:/*#__PURE__*/ $(U)}),[q]),b7=/*#__PURE__*/ fS.check(/*#__PURE__*/ mS({minimum:0,maximum:1})),hSe=/*#__PURE__*/ W({...n8.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ G(mSe)),costPriority:/*#__PURE__*/ $(b7),speedPriority:/*#__PURE__*/ $(b7),intelligencePriority:/*#__PURE__*/ $(b7)}),gSe=/*#__PURE__*/ W({method:/*#__PURE__*/ zx(`sampling/createMessage`),params:/*#__PURE__*/ W({messages:/*#__PURE__*/ G(y7),modelPreferences:/*#__PURE__*/ $(hSe),systemPrompt:/*#__PURE__*/ $(U),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ eS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(fS),maxTokens:hS,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(/*#__PURE__*/ G(_7)),toolChoice:/*#__PURE__*/ $(D5)})}),_Se=/*#__PURE__*/ W({...y7.fields,model:U,stopReason:/*#__PURE__*/ $(U)}),vSe=k5,ySe=/*#__PURE__*/ W({method:/*#__PURE__*/ zx(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ W({_meta:Q5}))}),bSe=/*#__PURE__*/ W({roots:/*#__PURE__*/ G(vSe)}),xSe=/*#__PURE__*/ W({method:/*#__PURE__*/ zx(`elicitation/create`),params:/* @__PURE__ */ K([/* @__PURE__ */ W({mode:/*#__PURE__*/ $(/*#__PURE__*/ zx(`form`)),message:U,requestedSchema:/* @__PURE__ */ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ zx(`object`),properties:/*#__PURE__*/ Yx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([L5,F5,I5]),j5,M5,N5])),required:/*#__PURE__*/ $(/*#__PURE__*/ G(U))})}),/* @__PURE__ */ W({mode:/*#__PURE__*/ zx(`url`),message:U,url:U})])}),SSe=/*#__PURE__*/ W({action:/*#__PURE__*/ eS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ Yx(U,/*#__PURE__*/ K([U,fS,Gx,/*#__PURE__*/ G(U)])))}),CSe=/*#__PURE__*/ K([gSe,ySe,xSe]),wSe=/*#__PURE__*/ K([_Se,bSe,SSe]),x7=/*#__PURE__*/ Yx(U,CSe),TSe=/*#__PURE__*/ Yx(U,wSe),S7={_meta:s7,resultType:/*#__PURE__*/ zx(`input_required`)},C7=/*#__PURE__*/ K([/*#__PURE__*/ Xx(/*#__PURE__*/ W({...S7,inputRequests:x7,requestState:/*#__PURE__*/ $(U)}),[q]),/*#__PURE__*/ Xx(/*#__PURE__*/ W({...S7,inputRequests:/*#__PURE__*/ $(x7),requestState:U}),[q])]),w7={...a7.fields,inputResponses:/*#__PURE__*/ $(TSe),requestState:/*#__PURE__*/ $(U)},T7={...c7,ttlMs:/*#__PURE__*/ hS.check(/*#__PURE__*/ Ioe(0)),cacheScope:/*#__PURE__*/ eS([`public`,`private`])},E7={...a7.fields,cursor:/*#__PURE__*/ $(U)},D7={...c7,nextCursor:/*#__PURE__*/ $(U)},O7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...T7,supportedVersions:/*#__PURE__*/ G(U),capabilities:sSe,instructions:/*#__PURE__*/ $(U)}),[q]);var ESe=class extends (/*#__PURE__*/ J(`server/discover`,{success:O7,error:l7,payload:a7})){};const k7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...D7,...T7,resources:/*#__PURE__*/ G(u7)}),[q]);var DSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:k7,error:l7,payload:E7})){};const A7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...D7,...T7,resourceTemplates:/*#__PURE__*/ G(d7)}),[q]);var OSe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:A7,error:l7,payload:E7})){};const j7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...T7,contents:/*#__PURE__*/ G(lSe)}),[q]);var kSe=class extends (/*#__PURE__*/ J(`resources/read`,{success:/*#__PURE__*/ K([j7,C7]),error:l7,payload:{...w7,uri:U}})){};const M7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...D7,...T7,prompts:/*#__PURE__*/ G(g7)}),[q]);var ASe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:M7,error:l7,payload:E7})){};const N7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...c7,description:/*#__PURE__*/ $(U),messages:/*#__PURE__*/ G(uSe)}),[q]);var jSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:/*#__PURE__*/ K([N7,C7]),error:l7,payload:{...w7,name:U,arguments:/*#__PURE__*/ $(/*#__PURE__*/ Yx(U,U))}})){};const P7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...D7,...T7,tools:/*#__PURE__*/ G(_7)}),[q]);var MSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:P7,error:l7,payload:E7})){};const F7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...c7,content:/*#__PURE__*/ G(h7),structuredContent:/*#__PURE__*/ $(QS),isError:/*#__PURE__*/ $(Gx)}),[q]);var NSe=class extends (/*#__PURE__*/ J(`tools/call`,{success:/*#__PURE__*/ K([F7,C7]),error:l7,payload:{...w7,name:U,arguments:/*#__PURE__*/ $(q)}})){};const PSe=U8,FSe=W8,I7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({...c7,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U).check(/*#__PURE__*/ vS(100)),total:/*#__PURE__*/ $(hS),hasMore:/*#__PURE__*/ $(Gx)})}),[q]);var ISe=class extends (/*#__PURE__*/ J(`completion/complete`,{success:I7,error:l7,payload:{...a7.fields,ref:/*#__PURE__*/ K([PSe,FSe]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ $(/*#__PURE__*/ W({arguments:/*#__PURE__*/ $(/*#__PURE__*/ Yx(U,U))}))}})){};const L7=/*#__PURE__*/ W({toolsListChanged:/*#__PURE__*/ $(Gx),promptsListChanged:/*#__PURE__*/ $(Gx),resourcesListChanged:/*#__PURE__*/ $(Gx),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ G(U))}),R7=/*#__PURE__*/ Xx(/*#__PURE__*/ W({_meta:/* @__PURE__ */ Xx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":r7,"io.modelcontextprotocol/subscriptionId":$5}),[q]),resultType:/*#__PURE__*/ zx(`complete`)}),[q]);var LSe=class extends (/*#__PURE__*/ J(`subscriptions/listen`,{success:R7,error:l7,payload:{...a7.fields,notifications:L7}})){},z7=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...o7.fields,requestId:$5,reason:/*#__PURE__*/ $(U)}})){},RSe=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...o7.fields,progressToken:e7,progress:fS,total:/*#__PURE__*/ $(fS),message:/*#__PURE__*/ $(U)}})){},zSe=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...o7.fields,level:n7,logger:/*#__PURE__*/ $(U),data:QS}})){},B7=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...o7.fields,uri:U}})){},V7=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ nS(o7)})){},H7=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ nS(o7)})){},U7=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ nS(o7)})){},W7=class extends (/*#__PURE__*/ J(`notifications/subscriptions/acknowledged`,{payload:{...o7.fields,notifications:L7}})){},G7=class extends (/*#__PURE__*/ xN(ESe,ISe,jSe,ASe,DSe,OSe,kSe,LSe,NSe,MSe)){},K7=class extends (/*#__PURE__*/ xN(z7)){},BSe=class extends (/*#__PURE__*/ G7.merge(K7)){},VSe=class extends (/*#__PURE__*/ xN()){},HSe=class extends (/*#__PURE__*/ xN(z7,RSe,zSe,B7,V7,H7,U7,W7)){};const USe=/*#__PURE__*/ Yx(U,q),WSe=/*#__PURE__*/ Dx(i7),GSe=/*#__PURE__*/ Dx(z7.payloadSchema),KSe=/*#__PURE__*/ Ex(QS),q7=/*#__PURE__*/ jx(r7),J7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},qSe=(e,t)=>{if(en(t))return e===void 0;if(e===void 0)return!1;let n=m6(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))},JSe=/*#__PURE__*/ H(function*(e){let t=yield*WSe(e);return{protocolVersion:Z5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),Y7=(e,t)=>{let n=e._meta;return{...rn(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},X7=(e,t)=>J7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),Z7=/*#__PURE__*/ Dx(/*#__PURE__*/ K([F7,C7])),Q7=/*#__PURE__*/ H(function*(e,t){let n=yield*q7(t);return e._tag===`Complete`?yield*Z7({...J7(e.value),_meta:Y7(e.value,n),resultType:`complete`}):yield*Z7(X7(e,n))}),YSe=(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??{};x6(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},$7=e=>J7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:hh(e.blob)}}),e9=/*#__PURE__*/ kO().pipe(/*#__PURE__*/ jO({type:/*#__PURE__*/ PO(`text`,`resource_link`)},e=>e),/*#__PURE__*/ jO({type:/*#__PURE__*/ PO(`image`,`audio`)},e=>J7({type:e.type,mimeType:e.mimeType,data:hh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ jO({type:`resource`},e=>J7({type:`resource`,resource:$7(e.resource),annotations:e.annotations,_meta:e._meta})),zO),XSe=e=>u7.make(e),ZSe=e=>d7.make(e),QSe=e=>w6(Sbe,g7,e),$Se=e=>w6(J3,_7,e),t9={ttlMs:0,cacheScope:`private`},n9=/*#__PURE__*/ H(function*(e,t){let n=yield*q7(t);return{...J7(e),_meta:Y7(e,n),resultType:`complete`}}),eCe=/*#__PURE__*/ kO().pipe(/*#__PURE__*/ MO(`ResourceNotFound`,e=>new S6({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ MO(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,S6.fromTool),/*#__PURE__*/ RO(S6.fromFeature)),r9=e=>{let t=eCe(e);return l7.make({code:t.code,message:t.message,...KSe(t.data)?{data:t.data}:{}})},i9=/*#__PURE__*/ H(function*(e,t){let n=yield*jp(_M);return ji(n)&&TM(n.value,(t,n)=>F(Gse(n,e))),yield*t}),tCe=e=>GSe(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),a9=e=>new i6({operation:e,protocolVersion:Z5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),o9=/* @__PURE__ */ D6({protocolVersion:Z5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:JSe},clientRpcs:BSe,clientNotificationRpcs:K7,serverRequestRpcs:VSe,serverNotificationRpcs:HSe,handlerRpcs:/* @__PURE__ */ G7.merge(K7),makeHandlers:(e,t,n)=>{let r=Dx(USe),i=Dx(O7),a=Dx(k7),o=Dx(A7),s=Dx(j7),c=Dx(M7),l=Dx(N7),u=Dx(K([N7,C7])),d=Dx(I7),f=Dx(P7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:fte(n.serverInfo.extensions,e=>rn(e)),g=V(n.registrationPresence,e=>{let t={completions:{},logging:{}};return h!==void 0&&(t.extensions=h),e.tools&&(t.tools={listChanged:m}),e.resources&&(t.resources={listChanged:m,subscribe:m}),e.prompts&&(t.prompts={listChanged:m}),{supportedVersions:n.supportedVersions,capabilities:t,serverInfo:n.serverInfo}}),_=a6.useSync(_6),v=H(function*(e){let t=yield*a6,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(hp);return _6(a6.of({...t,inputResponses:n,requestState:e.requestState}))}),y=H(function*(e,t){let n=YSe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*i9(400,new S6({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 S6({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*qd(yield*Pp),o=n.getListChangeRevision?.()??0,s=yield*Wd(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*Pd();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?H7:void 0,PromptsChanged:()=>c.promptsListChanged===!0?U7:void 0,ResourcesChanged:()=>c.resourcesListChanged===!0?V7:void 0,ResourceUpdated:e=>u.has(e.uri)?B7: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(Cre(a),rp(Jf(()=>n.markSubscriptionCancelled?.(t.id,r)??L)),rp(zd(f,void 0)),tm),yield*p(Z5,t.id,{tag:W7._tag,payload:W7.payloadSchema.make({_meta:l,notifications:c})});let m=Yp(dw(d).pipe(B(e=>p(Z5,t.id,e))));yield*sie(m,Fd(f)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??L;let h=yield*q7(n.serverInfo);return R7.make({_meta:{...l,"io.modelcontextprotocol/serverInfo":h},resultType:`complete`})},mp(r9)),"server/discover":H(function*(e){let t=yield*g,r=yield*n9({...t9,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},mp(r9)),"resources/list":H(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*n9({...t9,resources:i.map(XSe)},n.serverInfo);return yield*a(o)},mp(r9)),"resources/templates/list":H(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*n9({...t9,resourceTemplates:i.map(ZSe)},n.serverInfo);return yield*o(a)},mp(r9)),"resources/read":H(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map($7),o=yield*n9({...t9,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},mp(r9)),"prompts/list":H(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*i9(404,new S6({code:E3,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*Uf(i,QSe),o=yield*n9({...t9,prompts:a},n.serverInfo);return yield*c(o)},mp(r9)),"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*q7(n.serverInfo);return yield*u(X7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:e9(e.content)})),s=yield*n9({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},mp(r9)),"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*n9({completion:J7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},mp(r9)),"tools/list":H(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*Uf(i,$Se),o=yield*n9({...t9,tools:a},n.serverInfo);return yield*f(o)},mp(r9)),"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*jp(_M);if(i!==void 0&&ji(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!rn(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!qSe(a.value.headers[e],n))return yield*i9(400,new S6({code:k3,message:`${e} does not match argument '${r}'`}))}if(rn(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:rn(n)&&Object.hasOwn(n,i)?n[i]:void 0,path:r===``?i:`${r}.${i}`})}}let o=yield*e.tools.call({name:t.name,arguments:t.arguments??{}},r).pipe(up([`ToolExecutionError`,`InvalidToolInput`],e=>F(l6.Complete(Y3.make({content:[V3.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*Q7(o,n.serverInfo);let s=o.value,c=s.content.map(e9);return yield*Q7(l6.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},mp(r9)),"notifications/cancelled":H(function*(e){return yield*L})}},toReverseClient:()=>({listRoots:()=>z(a9(`roots/list`)),createMessage:()=>z(a9(`sampling/createMessage`)),elicit:()=>z(a9(`elicitation/create`))}),projectNotification:e=>E6(e)?F(void 0):T6({supportsProgressMessage:!0},e),normalizeCancellation:tCe}),nCe=aSe,rCe=Fxe,s9=/*#__PURE__*/ new WeakMap,c9=/*#__PURE__*/ ha(`effect/ai/McpServer/RequestNotificationQueue`,{defaultValue:()=>void 0}),l9=e=>e._tag===`Progress`||e._tag===`LoggingMessage`,iCe=/*#__PURE__*/ Fbe.omit(`notifications/elicitation/complete`),u9=/*#__PURE__*/ Ex(Z3),aCe=e=>{switch(e.tag){case`notifications/cancelled`:return f6.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return f6.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 f6.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return f6.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return f6.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return f6.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return f6.PromptsChanged({metadata:e.payload?._meta});default:return}},d9=(e,t)=>{let n=Np(e,a6,t.requestContext),r=t.requestContext.requestMetadata,i=N(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return u9(i)&&(n=Np(n,Vd,p6[i].effect)),t.serverClient===void 0?n:Np(n,o6,t.serverClient)};var f9=class e extends (/*#__PURE__*/ P()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ R(function*(){let t=yield*Hbe,n=Ma(),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*bo).makeDispatcher(),d=yield*lN(iCe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>Pd().pipe(B(t=>tp(n=>{let r=e.message;if(r._tag!==`Request`)return L;let i=aCe(r);if(i===void 0)return L;let a={notification:i,delivered:t,requestContext:oa(n.context,a6),requestHeaders:oa(n.context,_M)?.headers},f=Jf(()=>d.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Od})),p=la(n.context,c9);if(p!==void 0&&a.requestContext!==void 0&&l9(i))return $C(p,a),rp(Fd(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?rp(Fd(t),f):f})))}),f=e.of({notifications:d.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>c()?L:Pd().pipe(B(n=>QC(o,{notification:f6.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(rp(Jf(()=>s.consumers>0?Fd(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=oa(e.annotations,c6);yield*t.tools.register({descriptor:new J3({...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)=>d9(e.handle(t.arguments),n).pipe(nie({InternalError:t=>z(new Bbe({name:e.tool.name,message:t.message})),InvalidParams:t=>z(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?Rbe:zbe)({name:e.tool.name,message:t.message}))}),V(e=>on(e,`InputRequired`)?l6.InputRequired(e):l6.Complete(e)))}),yield*d.client[`notifications/tools/list_changed`]({})}),callTool:e=>R(function*(){let n=yield*o6,r=yield*t.tools.call(e,g6(n)).pipe(mp(e=>new N3({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new N3({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=oa(e.annotations,c6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>d9(e.handle,t)}),yield*d.client[`notifications/resources/list_changed`]({})}),addResourceTemplate:({annotations:e,completions:n,handle:r,routerPath:a,template:o})=>R(function*(){let s=i.findIndex(({template:e})=>e.uriTemplate===o.uriTemplate);s===-1?i.push({template:o,annotations:e}):i[s]={template:o,annotations:e};let c=pCe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=oa(e,c6);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)=>d9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>d9(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*o6;return yield*t.resources.read(e,g6(n)).pipe(up(`ResourceNotFound`,e=>z(new N3({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=oa(e.annotations,c6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>d9(e.handle(t),n).pipe(V(e=>on(e,`InputRequired`)?l6.InputRequired(e):l6.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>d9(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*o6,i=yield*t.prompts.get(n,e??{},g6(r)).pipe(up(`PromptNotFound`,()=>new N3({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new N3({message:`Client input is not supported by this MCP protocol`})}),completion:H(function*(e){let n=yield*o6,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},g6(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return s9.set(f,{core:t,notifications:o,notificationDelivery:s}),f});static layer=/*#__PURE__*/ lf(e)(e.make)};const p9=`mcp-session-id`,m9=/*#__PURE__*/ new WeakMap,h9=/*#__PURE__*/ new WeakMap,g9=e=>`${typeof e}:${e}`;var _9=class extends ko{};const v9=/*#__PURE__*/ H(function*(e,t,n,r){let i=yield*vN,a=yield*f9,o=yield*Vd,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)=>Jf(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(r.tag);return o===void 0?$f(`MCP protocol ${e} does not define server notification ${r.tag}`):a.payloadCodecs(o).encode(r.payload).pipe(hp,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=g9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},_=(e,t,n,r)=>Jf(()=>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}=s9.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*dN.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=g9(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(zp(()=>I(()=>p(t,e))))}return r._tag===`Interrupt`?(p(g9(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(Np(dN,a)),write:r}}),idleTimeToLive:1e4}),C=s6.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=oa(e.context,_M);return t&&TM(t,()=>F(pj({status:r[p9]===void 0?400:404}))),$f(/* @__PURE__ */ Error(`Mcp-Session-Id does not exist`))}let l=s?.initializePayload??i,u=c.get(n.id),d=s?.protocol??u?.protocol??t.protocolForInternalTag(a._tag);if(!mCe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return $f(`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=a6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return Np(Np(Np(e,o6,o6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:rn(i)&&rn(i._meta)?i._meta:void 0,getClient:nE(ee,new _9({clientId:n.id,profile:f})).pipe(V(({client:e})=>e))})),a6,p),Vd,t.effectLogLevel(n.id,r,o))}),te=vN.of({...i,send:(e,t)=>{if(t._tag===`Exit`){let r=l.get(e),a=g9(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--,m9.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 P3({message:`Internal error`})}]}})}return i.send(e,t)},run:e=>(v=e,i.run((n,r)=>{let i=nC(),a=r,o=s?oa(i.context,_M):void 0;switch(o!==void 0&&a._tag!==`Eof`&&TM(o,(e,t)=>F(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?pj({headers:_g(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{if(o!==void 0&&a.isNotification!==!0){let e=h9.get(o)??{expected:0};e.expected++,h9.set(o,e)}let r=s?ca(nC().context,_M).headers:fg(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(g9(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*Kd(ca(i.context,Hd),I(()=>d(n))));let h=u.binding,_=u.protocol;if(c.set(n,{protocol:_,profile:u.profile??m?.profile,sessionHeaders:s&&r[p9]!==void 0?fg({[p9]:r[p9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*f(n,a.id,new j3({message:`JSON-RPC batches are not supported`}));o!==void 0&&h!==void 0&&TM(o,(e,i)=>F(t.resolveRequest(n,r)===void 0?pj({status:404}):xj(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&&TM(o,()=>F(pj({status:r[p9]===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=g9(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:eN(a.id),client:new YM(n),headers:r}):L;return yield*u.requestContext===void 0?c:Np(c,a6,u.requestContext)}).pipe(yp)}if(!y||b)return a.isNotification?void 0:yield*f(n,a.id,new M3({message:`Method not found: ${a.tag}`}));let x=yield*ap(_.payloadCodecs(y).decode(a.payload));if(xa(x))return yield*a.isNotification?L:f(n,a.id,new N3({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=l.get(n)??/* @__PURE__ */ new Map;e.set(g9(a.id),{requestId:eN(a.id),prepared:u,cancelled:!1,httpPost:o===void 0?void 0:h9.get(o)}),l.set(n,e)}let ee=e(n,v);return yield*u.requestContext===void 0?ee:Np(ee,a6,u.requestContext)}).pipe(lp(e=>a.isNotification?L:f(n,a.id,on(e,`ProtocolError`)?S6.fromFeature(e):new N3({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`?g9(a.requestId):void 0,r=s?t.resolveRequest(n,ca(nC().context,_M).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 _9({clientId:o,profile:f})).pipe(B(({write:e})=>e(a)),Fp)}}}))});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 Hf(t,{discard:!0})})),r===void 0&&(yield*Ip(I(()=>{b.consumers++}),()=>I(()=>{b.consumers--})));let ne=/* @__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;E6(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=l9(i),p=f&&l!==void 0?[l.clientId]:a===void 0?s?c.keys():t.deliveryClientIds():[a],h=[],g=!1;for(let e of p){if(a!==void 0&&e!==a)continue;if(!d.has(e)){t.disconnect(e);continue}if(!te.supportsNotifications)continue;let r=f&&l!==void 0?t.selectProtocol(l.protocolVersion):c.get(e)?.protocol;if(!r)continue;let s=ne.get(e),p=e===(a??l?.clientId);g||=p;let m=p?n:Nd();ne.set(e,m);let _=R(function*(){s!==void 0&&(yield*Fd(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||!u9(n)||Z3.literals.indexOf(i.level)<Z3.literals.indexOf(n))return}else if(!t.canDeliver(e,(l?.clientId===e?u:void 0)??c.get(e)?.sessionHeaders??dg,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(yp,Rp(I(()=>{Bd(m,Od),ne.get(e)===m&&ne.delete(e)})));h.push(_)}g||(yield*zd(n,void 0)),yield*Hf(h,{concurrency:`unbounded`,discard:!0}).pipe(tm({startImmediately:!0}))})),yp,Yp,tm),yield*jle(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(Np(vN,te),Np(s6,C),Op(S))},Fp),oCe=(e,t)=>ff(R(function*(){let n=yield*B6;yield*tm(v9(e,n,t))})).pipe(bf(f9.layer)),sCe=e=>{let t=H6(e.protocols);return oCe(e,`http`).pipe(yf(lCe(e)),yf(t),yf(ble()))},cCe=e=>ff(R(function*(){let t=yield*B6,n=t.protocols.find(e=>e.runtime._tag===`Stateful`);if(n!==void 0)return yield*new yd(`McpServer.layerHttpRequestScoped does not support the sessionful MCP protocol ${n.protocolVersion}`);let r=yield*f9,{core:i,notificationDelivery:a}=s9.get(r),o=yield*t.installHandlers({core:i,subscribeServerNotifications:$f(`Subscriptions are disabled for request-scoped MCP servers`),getListChangeRevision:()=>a.listChangeRevision,defaultLogLevel:yield*Vd,serverInfo:e});yield*Ip(I(()=>{a.requestEndpoints++}),()=>I(()=>{a.requestEndpoints--})),yield*y9(e,R(function*(){let{httpEffect:n,protocol:i}=yield*yN().pipe(Np(iN,b9)),a=yield*YC();return yield*v9(e,t,`http`,{notifications:a,handlers:o}).pipe(Np(vN,i),Np(f9,r),tm({startImmediately:!0})),yield*Np(n,c9,a)}))})).pipe(bf(f9.layer),yf(H6(e.protocols))),lCe=e=>lf(vN)(R(function*(){let{httpEffect:t,protocol:n}=yield*yN().pipe(Np(iN,b9));return yield*y9(e,t),n})),y9=/*#__PURE__*/ H(function*(e,t){let n=yield*B6,r=yield*DM,i=e.allowSessionTermination===!0&&n.protocols.some(e=>e.runtime._tag===`Stateful`),a=F(pj({status:403})),o=t=>n=>S9(n,e.allowedOrigins)?t(n):a,s=F(pj({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(!S9(r,e.allowedOrigins))return F(pj({status:403}));if(C9(r.headers[`content-type`])[0]!==`application/json`)return F(pj({status:415}));let i=C9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?F(pj({status:406})):R(function*(){let e=yield*ap(B(r.text,Ox(Uoe))),i=n.admitHttp(r.headers,e);if(i._tag===`Rejected`)return i.response;let a=e=>{let t=e.body._tag===`Uint8Array`&&e.body.body.subarray(0,-1).includes(10);return i.isSubscription||e.body._tag===`Stream`||t?fCe(e,i.isSubscription):e};return i.acknowledge?yield*dp(V(t,a),()=>F(pj({status:202}))):yield*B(t,e=>e.body._tag!==`Uint8Array`||e.body.body.length>0?F(a(e)):h9.get(r)?.expected===0?F(bj(TE,{contentType:`text/event-stream`})):$f(/* @__PURE__ */ Error(`MCP request ended without writing its response`)))})})}),b9=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ dCe();return iN.of({contentType:e.contentType,includesFraming:!0,codecFor:e.codecFor,makeUnsafe:()=>{let t=e.makeUnsafe();return{decode:t.decode,encode:e=>{let n=t.encode(e);return typeof n==`string`?`${n}\n`:n}}}})})(),uCe=/*#__PURE__*/ Ex(/*#__PURE__*/ oS(`Cause`,{data:/*#__PURE__*/ Eoe([/*#__PURE__*/ oS(`Fail`,{error:/*#__PURE__*/ Soe(F3)})])})),x9=e=>Array.isArray(e)?e.map(x9):!rn(e)||!N(e,`error`)?e:uCe(e.error)?{...e,error:e.error.data[0].error}:e;function dCe(e){let t=aN(e);return iN.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(rn(t)){let e=m9.get(t);e!==void 0&&(m9.delete(t),n.add(e))}let r=e.encode(t);if(typeof r!=`string`||n.size===0&&!r.includes(`"_tag":"Cause"`))return r;let i=JSON.parse(r);if(n.size>0){let e=e=>!(rn(e)&&!N(e,`method`)&&(typeof e.id==`string`||typeof e.id==`number`)&&n.delete(e.id));if(Array.isArray(i)){let t=i.filter(e);if(t.length===0)return;i=t}else if(!e(i))return}return JSON.stringify(x9(i))}}}})}const fCe=(e,t)=>{let n=new TextEncoder,r=new TextDecoder,i=e=>n.encode(r.decode(e).trimEnd().split(`
|
|
535
|
-
`).map(e=>`data: ${e}\n\n`).join(``)),a={status:e.status,statusText:e.statusText,headers:_g(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 bj(r,a);let o=bE(`15 seconds`).pipe(VE(1),ME(()=>n.encode(`: keepalive
|
|
536
|
-
|
|
537
|
-
`)));return bj(LE(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?hj(i(e.body.body),a):xj(e,`content-type`,`text/event-stream`)},S9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},C9=e=>e===void 0?[]:e.split(`,`).flatMap(e=>{let[t,...n]=e.split(`;`),r=n.map(e=>e.trim().toLowerCase()).find(e=>e.startsWith(`q=`));if(r!==void 0){let e=Number(r.slice(2));if(!Number.isFinite(e)||e<=0||e>1)return[]}return[t.trim().toLowerCase()]}),pCe=()=>{let e=oj({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},mCe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,w9=o9,hCe=[o9,nCe,rCe],gCe=Ex(QI),_Ce=Ex(G(QI)),T9=e=>eL(LI(e)),E9=e=>{let t=LI(e),n=eL(t);if(n!==void 0)return{kind:n,many:!1};if(!Dv(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(T9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},vCe=e=>{let t=e.context?.isOptional===!0,n=LI(e);if(t&&kv(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!Eie(e)),r=e===void 0||t.length>0?void 0:T9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=E9(n);return r===void 0||t&&r.many?void 0:r},D9=e=>{let t=LI(e.ast),n=E9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!Ov(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=vCe(t);return n===void 0?[]:[{name:String(e),...n}]});if(r.length===0)return{fields:r,rest:e};let i=new Set(r.map(({name:e})=>e)),a=t.propertySignatures.filter(({name:e})=>!i.has(e)),{identifier:o,...s}=t.annotations??{};return{fields:r,rest:a.length===0&&t.indexSignatures.length===0?void 0:Px(new ry(a,t.indexSignatures,s))}},yCe=e=>[...Cv(e)?e.typeParameters:[],...Dv(e)?[...e.elements,...e.rest]:[],...Ov(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...kv(e)?e.types:[],...Av(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],bCe=e=>{let t=/* @__PURE__ */ new Set,n=[e];for(let e=n.pop();e!==void 0;e=n.pop())if(!t.has(e)){if(t.add(e),$I(e))return!0;n.push(...yCe(e))}return!1},xCe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>bCe(e)),SCe=(e,t)=>e.fields.flatMap(({name:e,kind:n,many:r})=>{let i=e===void 0?t:N(t,e)?t[e]:void 0;return(r?_Ce(i)?i:[]:gCe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),CCe=Ex(K3),O9=(e,t)=>{let n=JS(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=Gt(n.schema.$ref)?Hb(n.schema.$ref)??[]:[],a=r===`$defs`&&i!==void 0?n.definitions[i]:n.schema;return a===void 0||Object.keys(n.definitions).length===0?a:{...a,$defs:n.definitions}},wCe=e=>{let t=e.map(([e])=>e).filter(e=>!CCe(O9(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])=>xCe(e,t)).map(([{name:e}])=>e);if(n.length>0)throw Error(`MCP media must be the success or an array of it, or a top-level field of a struct success, one, optional or a required array: ${n.join(`, `)}`)},TCe=e=>new Y3({isError:!0,content:[{type:`text`,text:e}]}),k9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],ECe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),DCe=(e,t)=>V(Dx(K3)(O9(YS(e.input),!0)),n=>new J3({name:e.name,description:e.description,inputSchema:n,outputSchema:t,annotations:{...e.mcp.title===void 0?{}:{title:e.mcp.title},...lbe(e)},_meta:e.mcp._meta===void 0?void 0:{...e.mcp._meta}})),OCe=H(function*(e,t){let n=yield*f9,r=yield*YI(e),i=yield*Ep(),a=e=>dm(e).pipe(rp(cO(e)),sp(TCe(`Tool execution failed due to an internal server error.`))),o=e=>md(e)?a(e):Zf(e);for(let[e,a]of r){let r=D9(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*Dx(q3)(O9(c,!1)).pipe(hp),u=yield*DCe(e,l).pipe(hp),d=Dx(YS(e.input),XI),f=e=>{let t=Ax(YS(e));return e=>hp(t(e))},p=f(e.success),m=f(K(BI(e))),h=t===void 0||e.caller===EI?a:e=>kB(ife(t,a(e))),g=new Set(s?.fields.map(({name:e})=>e)),_=(e,t)=>{if(s===void 0)return new Y3({isError:!1,structuredContent:e,content:k9(e)});let n=SCe(s,t).map(ECe);if(c===void 0)return new Y3({isError:!1,content:n});let r=nn(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!g.has(e))):e;return new Y3({isError:!1,structuredContent:r,content:[...k9(r),...n]})};yield*n.addTool({tool:u,annotations:na(),handle:t=>fie({tool:e.name,parameters:t??{}}).pipe(rp(()=>d(t??{})),mp(({message:t})=>new N3({message:new ube({toolName:e.name,description:t}).message})),B(e=>h(e).pipe(Tp({onFailure:e=>V(m(e),e=>new Y3({isError:!0,content:k9(e)})),onSuccess:e=>V(p(e),t=>_(t,e))}))),dp(o),Mp(e=>pa(i,e)))})}}),kCe=(e,t,n=cf,r)=>{II(`MCP tool`,e.flatMap(e=>e.actions));let i=e.flatMap(e=>e.actions.map(e=>[e,D9(e.success)]));wCe(i);let a=new Set(i.map(([{name:e}])=>e)),o=R(function*(){let t=(yield*f9).tools.flatMap(({tool:e})=>a.has(e.name)?[e.name]:[]);if(t.length>0)return yield*$f(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature`));yield*OCe(e,r)});return ff(o).pipe(yf(n),yf(t),jre,JI(e))},ACe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),jCe=e=>{let t=new Set(e.filter(({caller:e})=>e===EI).flatMap(({name:e})=>[e,`=?base64?${hh(e)}?=`]));return e=>{if(t.size===0||e[`mcp-protocol-version`]!==w9.protocolVersion)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(ACe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}},MCe=e=>Cp(e.json,{onFailure:()=>!0,onSuccess:t=>!N(t,`method`)||t.method===e.headers[`mcp-method`]});function NCe(e,{actions:t,features:n,path:r=`/mcp`,authentication:i,requestScoped:a,allowSubscriptions:o=n!==void 0,...s}){let c=qI(GI(e),t),l=c.flatMap(e=>e.actions);DI(l,i);let u=kCe(c,a===!0?cCe({...s,path:r,protocols:[w9]}):sCe({...s,path:r,protocols:hCe,allowSessionTermination:!0,allowSubscriptions:o}),n,i);if(i===void 0)return u;let d=jCe(l),f=IM(V(aL(i),e=>t=>B(_M,n=>n.method!==`POST`||d(n.headers)?e.http(t,!1):B(MCe(n),n=>e.http(t,n)))));return u.pipe(yf(f.layer))}var PCe=`0.25.0`;const FCe=(e,t)=>Kf(()=>RW({key:e,data:t})),ICe=(e,t)=>Kf(()=>zW({key:e,data:t})),LCe=async(e,t)=>(await Promise.all([KG(e.authCookies.sessionToken.name,t,e.secret),KG(e.authCookies.dontRememberToken.name,`true`,e.secret)])).map(e=>e.split(`;`)[0]).join(`; `),RCe=(e,t)=>sm(`OwnerAccount.providerSession`)(function*(n){let r=new Date((yield*Sf)+6e4),i=yield*Ip(H4(()=>e.internalAdapter.createSession(n,!0,{expiresAt:r},!0)),t=>Gf(()=>e.internalAdapter.deleteSession(t.token))),a=yield*H4(()=>LCe(e,i.token));return new Headers({origin:t,cookie:a})}),zCe=tH(W({id:U}));var A9=class e extends P()(`clankerauth/OwnerAccount`){static layer=lf(e,R(function*(){let{sql:e}=yield*aH,{auth:t,context:n}=yield*i3,{baseURL:r}=yield*X4,i=yield*Pw(1),a=RCe(n,r),o=sm(`OwnerAccount.find`)(function*(){let t=yield*e`SELECT id FROM user LIMIT 1`;if(t.length)return(yield*zCe(t[0])).id});return{find:o,create:sm(`OwnerAccount.create`)(function*(e){if(yield*o())return yield*z(tV.of());let{headers:n}=yield*H4(()=>t.api.signUpEmail({body:{name:`Owner`,email:e.email.trim(),password:e.password},returnHeaders:!0}),{refused:B4,conflict:tV.of});return n.getSetCookie()},e=>i.withPermit(e)),caller:(e,t,n)=>({userId:e,email:t,writable:n,providerHeaders:a(e)})}}))},j9=class extends P()(`clankerauth/ResponseCookies`){};const BCe=V(A9,e=>({setupStatus:()=>e.find().pipe(V(e=>({required:!e}))),setupOwner:sm(`Administration.setup`)(function*(t){let n=yield*e.create(t);return yield*(yield*j9).add(n),{created:!0}})}));var M9=class extends Po(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},N9=class extends qS()(`ProviderUnavailable`,{operation:U},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},P9=class extends Po(`InsufficientScope`){},VCe=class extends qS()(`ConfigurationError`,{message:U}){};const F9=oo(1),I9=(e,t)=>Dp(n=>vse(e).execute(t).pipe(Np(RN,{...oa(n,RN),redirect:`error`}),mp(e=>new N9({operation:`http.request`,cause:e})))),HCe=W({keys:G(W({kty:U,crv:Ix(U),x:Ix(U),kid:Ix(U),alg:Ix(U),use:Ix(U),key_ops:Ix(G(U))}))}),UCe=W({sub:xS,client_id:xS,scope:U,iat:fS,exp:fS}),WCe=W({list:U}),GCe=Pde.pipe(Jx({exp:fS})),L9=e=>new M9({cause:e}),R9=ao(5),z9=sm(`Verifier.make`)(function*(e){let t=yield*UA,n=yield*ep({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new VCe({message:`Invalid issuer URL`})}),r=sm(`Verifier.jwks`)(function*(){let e=yield*I9(t,qoe(n.jwks));return e.status===200?hI({keys:(yield*PA(HCe)(e).pipe(mp(e=>new N9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t)}):yield*new N9({operation:`jwks.fetch`,cause:{status:e.status}})},Fp),i=yield*Up(r(),e=>kd(e)?`1 minute`:R9),a=sm(`Verifier.signingKey`)(function*(e){let t=yield*i;return yield*Kf({try:()=>t({alg:`EdDSA`,kid:e}),catch:L9})}),o=sm(`Verifier.signed`)(function*(t,n){let r=yield*ep({try:()=>bI(t),catch:L9});if(r.alg!==`EdDSA`||r.kid===void 0)return yield*L9();let i=yield*a(r.kid),o=yield*Sf,{payload:s}=yield*Kf({try:()=>oI(t,i,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(o)}),catch:L9});return s}),s=sm(`Verifier.jwt`)(function*(e){let t=yield*o(e,`at+jwt`);if(t.cnf!==void 0)return yield*L9();let n=yield*Dx(UCe)(t).pipe(mp(L9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),c=sm(`Verifier.keyList`)(function*(){let r=OA(n.keyList).pipe(MA({resource:e.resource})),i=yield*I9(t,r);if(i.status!==200)return yield*new N9({operation:`key-list.fetch`,cause:{status:i.status}});let{list:a}=yield*PA(WCe)(i).pipe(mp(e=>new N9({operation:`key-list.decode`,cause:e}))),s=e=>new N9({operation:`key-list.verify`,cause:e}),c=yield*o(a,SI).pipe(up(`Unauthorized`,e=>z(s(e)))),l=yield*Dx(GCe)(c).pipe(mp(s));return{readAt:yield*Sf,expiresAt:l.exp*1e3,entries:new Map(l.keys.map(e=>[e.id,e.sealed]))}},Fp),l=yield*HO(!1),u=yield*Up(c().pipe(bp({duration:`3 seconds`,orElse:()=>z(new N9({operation:`key-list.timeout`}))}),gp(({operation:e})=>B(GO(l,!0),t=>t?L:um(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:e}))),ip(()=>B(GO(l,!1),e=>e?fm(`clankerauth key list reads have recovered`):L))),R9),d=yield*HO(void 0),f=R(function*(){let e=yield*ap(u);Sa(e)&&(yield*WO(d,e.success));let t=yield*UO(d);return t!==void 0&&t.expiresAt>(yield*Sf)?t:yield*xa(e)?e.failure:new N9({operation:`key-list.expired`})}),p=sm(`Verifier.apiKey`)(function*(t){let n=n=>Kf({try:()=>Lde(t,e.resource,n.entries),catch:L9}),r=yield*Sf,i=yield*UO(d),a=i!==void 0&&r-i.readAt<uo(F9)&&i.expiresAt>r?i:yield*f,o=(yield*n(a))??(yield*B(f,e=>e===a?F(void 0):n(e)));return o===void 0||o.expiresAt!==null&&o.expiresAt<=(yield*Sf)?yield*L9():{subject:o.ownerId,scopes:o.scopes,actor:{kind:`key`,keyId:o.keyId},expiresAt:o.expiresAt??void 0}});return{verifyToken:sm(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?z(L9()):p(t):s(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new P9({scope:r,actor:n.actor})})}}),KCe=sm(`AdministrationResource.make`)(function*(){let{auth:e}=yield*i3,{baseURL:t}=yield*X4,n=`${t}/api/auth`,r=lV(t);return{protectedResource:{resource:r,authorizationServers:[n],scopesSupported:[uV.read,uV.write,...Q4],scopesRequired:[uV.read,uV.write]},verifier:yield*z9({issuer:n,resource:r,apiKeys:!1}).pipe(Op(zN.pipe(yf(of(LN,(t,n)=>{let r=new Request(t,n);return r.headers.set(F4,`127.0.0.1`),e.handler(r)})))))}});nL(`whoami`,{description:`The verified subject, issuer and scopes behind this request's credential.`,readOnly:!0,caller:class extends P()(`@clankerauth/CurrentPrincipal`){},success:W({subject:xS,issuer:xS,scopes:G(U)})});const B9=(e,t)=>{let n=`Requires ${e}.`;return t.kind===`client`?new MI({message:n,scopes:[e]}):new MI({message:n})},qCe=(e,t)=>t===void 0||e.scopes.includes(t)?void 0:B9(t,e.actor),V9=e=>e instanceof M9?new AI({message:e.message}):e instanceof P9?B9(e.scope,e.actor):e,H9=(e,t)=>mp(e.verifyToken(ag(t)),V9);sm(`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*z9({issuer:r.issuer,resource:i,requiredScopes:[n],apiKeys:r.apiKeys}),c=e=>bp(e,{duration:`5 seconds`,orElse:()=>z(new N9({operation:`verify.timeout`}))}),l={verifyToken:e=>c(s.verifyToken(e))},u=sm(`Resource.principal`)(function*(e,t){let n=MB(e);if(Ai(n))return yield*new AI({message:`A bearer token is required.`});let r=yield*H9(l,n.value),i=qCe(r,t);return i===void 0?r:yield*i}),d=sm(`Resource.admit`)(function*(t,n){let r=yield*ap(u(t,n));if(Sa(r))return{ok:!0,principal:r.success};let i=qse(zB(r.failure,{authentication:e,protectedResource:o,authorization:t}));return{ok:!1,refusal:{status:i.status,headers:Object.fromEntries(i.headers),body:yield*Gf(()=>i.text())}}});return{resource:i,issuer:r.issuer,protectedResource:o,verifier:l,admit:d,watch:(e,t)=>Yp(R(function*(){let n=yield*u(e,t),r=yield*Sf,i=Math.max(0,(n.expiresAt??1/0)-r);return n.actor.kind===`key`?yield*xp(Math.min(i,uo(F9))):(yield*xp(i),yield*V9(new M9))}))}});const JCe=e=>JB(e,V(i3,e=>()=>R(function*(){let t=yield*_M,n=new Headers(t.headers),r=yield*H4(()=>e.auth.api.getSession({headers:n}),{unavailable:V4});return r?{providerHeaders:F(n),userId:r.user.id,email:r.user.email,writable:!0}:yield*new AI({message:`Owner session required`})}))),YCe=tH(W({id:U,email:U})),XCe=e=>JB(cV,R(function*(){let{sql:t}=yield*aH,n=yield*A9,r=()=>new AI({message:`Owner authorization required`});return i=>R(function*(){let a=yield*H9(e.verifier,i).pipe(up(`ProviderUnavailable`,()=>z(new XB({message:`Request could not be completed`}))));if(a.actor.kind!==`client`)return yield*r();let o=a.scopes.includes(uV.write);if(!o&&!a.scopes.includes(uV.read))return yield*new MI({message:`Insufficient scope`,scopes:[uV.read]});let s=yield*t`SELECT u.id, u.email FROM user u
|
|
538
|
-
JOIN oauthClient c ON c.clientId = ${a.actor.clientId}
|
|
539
|
-
WHERE u.id = ${a.subject} AND c.disabled IS NOT 1`;if(!s[0])return yield*r();let c=yield*YCe(s[0]);return n.caller(c.id,c.email,o)})}),{protectedResource:e.protectedResource}),ZCe=e=>e.readOnly?L:B(aV,({writable:e})=>e?L:z(new MI({message:`This action requires the ${uV.write} scope`,scopes:[uV.write]}))),QCe=IM()(e=>R(function*(){let t=[],n=yield*Np(e,j9,{add:e=>I(()=>t.push(...e))});return t.length?Tj(n,Ph(t)):n}));function $Ce(e){return mf(R(function*(){let{context:t}=yield*i3,n=yield*d3,r=yield*u3,i=yield*BCe,a=yield*o3,o=iL(WV,{listClients:n.list,createClient:n.create,updateClient:n.update,deleteClient:n.delete,revokeClient:n.revoke,blockClient:n.block,rotateClientSecret:n.rotate,setClientAccess:r.setAccess,getResource:r.get,putResource:r.put,deleteResource:r.delete,listApiKeys:a.list,createApiKey:a.create,updateApiKey:a.update,deleteApiKey:a.delete},{authorize:ZCe}),s=iL(HV,{setupStatus:i.setupStatus,setupOwner:i.setupOwner,keyList:({resource:e})=>a.keyList(e)}),c=yield*KCe(),l=oV(t.authCookies.sessionToken.name),u=KV(l),d=gf(gB(u,o).pipe(yf(JCe(l))),AM(`GET`,`/openapi.json`,vj(qR(u.api))),gB(u,s).pipe(yf(QCe.layer))),f=gf(NCe(o,{name:`clankerauth-admin`,version:PCe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${uV.read} or ${uV.write}; every other action changes authorization policy and needs ${uV.write}. Create and rotate actions return secrets once.`,authentication:cV}),gB(qV,o)).pipe(yf(XCe(c)));return gf(d,f)}))}const U9=`clankerauth_forward`,W9=(e,t)=>vj({error:t},{status:e}),ewe=e=>mf(R(function*(){let t=yield*X4,{auth:n,context:r}=yield*i3,i=yield*r3,a=n=>{if(!URL.canParse(n))return;let r=new URL(n);return!r.username&&!r.password&&K4(r,t.allowInsecureHttp)&&G4(r.hostname,e)?r:void 0},o=ag(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=>H4(()=>n.api.getSession({headers:new Headers({cookie:e})}),{unavailable:V4}),f=R(function*(){let e=yield*_M,{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 W9(400,`invalid_forwarded_request`);let p=new URL(e.url,t.baseURL).searchParams.get(`resource`),m=p&&(yield*i.application(p));if(!m)return W9(403,`unknown_resource`);let h=e.cookies[U9],g=h?yield*tie(ICe(o,h)):Oi(),_=ji(g)?yield*d(`${l}=${g.value}`):null;if(!_)return r[`sec-fetch-mode`]===`navigate`?mj(u(`/forward-auth/continue`,f)):W9(401,`unauthenticated`);let v=Math.floor((yield*Sf)/1e3),{token:y}=yield*H4(()=>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 pj({status:204,headers:{authorization:`Bearer ${y}`}})}),p=R(function*(){let e=yield*_M,n=new URL(e.url,t.baseURL).searchParams.get(`rd`),r=n?a(n):void 0;if(!r)return W9(400,`invalid_return_url`);let i=e.cookies[l];if(!(i&&(yield*d(e.headers.cookie??``)))||!i)return mj(u(`/login`,u(`/forward-auth/continue`,r)));let s=yield*FCe(o,i);return yield*mj(r).pipe(wj(U9,s,c))}),m=R(function*(){let e=yield*_M,r=new URL(e.url,t.baseURL).searchParams.get(`rd`),i=r&&a(r)||s,{headers:o}=yield*H4(()=>n.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}),{refused:B4,unavailable:V4});return yield*Tj(mj(i),Ph(o.getSetCookie())).pipe(wj(U9,``,{...c,maxAge:0}))});return gf(AM(`GET`,`/forward-auth`,lp(f,W4)),AM(`GET`,`/forward-auth/continue`,lp(p,W4)),AM(`GET`,`/forward-auth/logout`,lp(m,W4)))})),twe=/* @__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`]),nwe=/* @__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`]),rwe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),iwe=new Set(cbe),awe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css|woff2)$/,G9=(e,t=200)=>vj(e,{status:t}),K9=G9({error:`Not found`},404),q9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],owe=new Set(q9.map(e=>e.toLowerCase())),swe=(e=pt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>mf(R(function*(){let t=yield*X4,{auth:n}=yield*i3,{sql:r}=yield*aH,i=yield*r3,a=[.../* @__PURE__ */ new Set([t.baseURL,...t.mcpAllowedOrigins])],o=R(function*(){let e=yield*_M,r=new URL(e.url,t.baseURL),a=r.pathname.replace(/^\/api\/auth/,``);if(!twe.has(a)&&a!==`/.well-known/oauth-authorization-server/api/auth`)return K9;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 G9({error:`invalid_target`,error_description:Z4},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*H4(()=>n.handler(new Request(r,{method:e.method,headers:e.headers,body:o})));return Xse(s)}).pipe(lp(W4)),s=kM(n=>R(function*(){let r=yield*Mj;yield*n.add(`*`,`/*`,R(function*(){let n=yield*_M;if(n.method!==`GET`&&n.method!==`HEAD`)return K9;let i=new URL(n.url,t.baseURL).pathname,a=iwe.has(i)?`index.html`:awe.test(i)?i.slice(1):void 0;return a?yield*r.fileResponse(dt(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:a.endsWith(`.woff2`)?`font/woff2`:`text/html; charset=utf-8`}).pipe(lp(()=>F(K9))):K9}))})),c=IM(e=>Rye({baseURL:t.baseURL,trustProxy:t.trustProxy})(R(function*(){let n=yield*_M,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=nwe.has(i),u;if(o&&s!==void 0&&!c)u=G9({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=>owe.has(e))?pj({status:204}):G9({error:`MCP preflight rejected`},403)}else u=l&&n.method===`OPTIONS`?pj({status:204}):yield*e;l&&(u=u.pipe(Cj({"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`}),Sj(`access-control-allow-credentials`))),o&&(u=u.pipe(xj(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),Sj(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(Cj({"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(Cj({"access-control-allow-methods":`POST`,"access-control-allow-headers":q9.join(`, `)})))));let d=n.method!==`GET`||u.status!==200?`no-store`:r.startsWith(`/assets/`)?`public, max-age=31536000, immutable`:rwe.has(i)?`public, max-age=300`:`no-store`;return u=u.pipe(Cj({"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(xj(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),l=IM(e=>qp(e));return gf($Ce(a),t.cookieDomain===void 0?cf:ewe(t.cookieDomain),AM(`GET`,`/healthz`,r`SELECT 1`.pipe(sp(G9({status:`ok`})),lp(W4))),AM(`*`,`/api/auth/*`,o),AM(`*`,`/.well-known/*`,o),s).pipe(yf(l.layer),yf(c),yf(Aue))})),cwe=sm(`Http.nodeHandler`)(function*(e){let t=yield*ale(swe(e));return yield*Oue(t,{scope:yield*Pp})}),lwe=(e,t)=>{let n=mf(V(X4,({database:e})=>aH.layer(e)));return gf(A9.layer,d3.layer,o3.layer).pipe(bf(u3.layer),bf(i3.layer),bf(r3.layer),bf(n),bf(_f(e,t)))},J9=`credentials.json`,Y9=W({email:U,password:U,secret:U,clientId:Lx(U),clientSecret:Lx(U)}),X9=Dx(wS(Y9)),uwe=Nx(Y9),Z9=(e,t)=>B(rD,n=>n.writeFileString(ut(e,J9),`${JSON.stringify(uwe(t),null,2)}\n`,{mode:384})),dwe=sm(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:at(24).toString(`base64url`),secret:at(32).toString(`hex`)};if(!t)return n;let r=yield*rD,i=ut(e,J9);return(yield*r.exists(i))?yield*X9(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=sm(`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*UA,a=yield*i.execute(OA(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(MA(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:Jh(a.cookies)}});yield*s.text;let c=Gh(a.cookies,s.cookies);return{cookie:Jh(c),cookies:Object.entries(Yh(c)).map(([e,t])=>({name:e,value:t}))}}),fwe=gf(FN,zN,of(RN,{redirect:`manual`})),pwe=H(function*(e){let t=yield*rD,n=pt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(ut(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*sp(t.makeDirectory(dt(r),{recursive:!0,mode:448}),dt(r)),a=yield*Pye(e.port??0,`127.0.0.1`),{port:o}=a,s=e.cookieDomain===void 0?`http://127.0.0.1:${o}`:`http://clankerauth.${e.cookieDomain}:${o}`,c=yield*dwe(i,r!==void 0),l=yield*Y4({baseURL:s,secret:rg(c.secret),database:ut(i,`issuer.sqlite`),host:`127.0.0.1`,port:o,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),u=yield*Ore(lwe(of(X4,l),P4.layerWith(e.cimdTransport))),d=la(u,A9),f=yield*qd(yield*Pp),p=yield*cwe(n).pipe(Op(u),Np(Hd,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=la(u,d3),g=la(u,u3),_=la(u,o3),v=e=>qp(Fp(R(function*(){let t=yield*d.find();return t===void 0?yield*$f(/* @__PURE__ */ Error(`Owner setup failed`)):yield*e(t).pipe(Np(aV,d.caller(t,m.email,!0)))}))).pipe(mp(Q9));(yield*d.find())||(yield*d.create(m).pipe(mp(Q9))),yield*v(()=>Uf(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:sm(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(s,x,m,e.appOrigin),n=yield*UA,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 mwe(e){let t=Ud(),n=e=>im(e.pipe(Np(Hd,t),Op(fwe)),{onFiberStart:rC(t)}),r=am(Hp(Yd(t,Od)));try{let t=await n(pwe(e));return{...t.details,apiKey:e=>n(t.apiKey(e)),ownerSession:e=>n(t.ownerSession(e)),ownerToken:e=>n(t.ownerToken(e)),close:()=>im(r)}}catch(e){throw await im(r),e}}export{JV as n,mwe as t};
|