@gjermundgaraba/clankerauth-dev 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +31 -31
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{t as e}from"./esm-CdWTLqG7.mjs";import{A as t,C as n,D as r,E as i,F as a,I as o,L as s,M as c,N as l,O as u,P as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as ee,n as te,o as E,p as ne,r as re,s as ie,t as ae,u as oe,v as D,w as se,x as ce,y as le}from"./schemas-CYxWglEB.mjs";import{C as ue,D as de,E as fe,S as pe,T as me,a as he,b as ge,c as _e,d as ve,f as ye,g as be,h as xe,l as eee,m as Se,n as Ce,o as we,r as Te,s as Ee,t as De,u as Oe,v as tee,w as ke,x as nee,y as Ae}from"./random-CJ6fASpe.mjs";import{a as je,c as Me,l as Ne,o as Pe,r as Fe,s as Ie}from"./schema-check-BzXTKlLa.mjs";import{i as Le,n as ree,r as Re}from"./factory-QgsYt4OE.mjs";import{c as ze,r as Be,s as Ve}from"./sqlite-introspector-DSCAP82F-uK1vwYwN.mjs";import{c as He,i as Ue,n as We,o as Ge,r as Ke,s as iee,t as aee}from"./dist-DmipO4_i.mjs";import{t as qe}from"./compiled-query-kXoVMG6q.mjs";import{n as oee}from"./access-OpW0SRxm.mjs";import*as Je from"node:crypto";import{randomBytes as Ye,randomUUID as see,scrypt as cee}from"node:crypto";import*as Xe from"node:path";import Ze,{dirname as lee,join as Qe,resolve as $e}from"node:path";import*as et from"node:url";import{fileURLToPath as tt}from"node:url";import*as nt from"node:child_process";import{Duplex as rt,PassThrough as it,Readable as at,pipeline as ot}from"node:stream";import{IncomingMessage as st,createServer as ct}from"node:http";import{isIP as lt}from"node:net";import*as ut from"node:fs";import dt,{mkdirSync as ft}from"node:fs";import*as pt from"node:os";import mt from"node:os";import{request as uee}from"node:https";import*as dee from"node:stream/promises";import{pipeline as fee}from"node:stream/promises";import*as ht from"node:zlib";import*as gt from"node:readline";import{DatabaseSync as _t}from"node:sqlite";import vt from"node:fs/promises";import{lookup as yt}from"node:dns/promises";const bt=(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}}},xt={pipe(){return bt(this,arguments)}},St=/*#__PURE__*/ function(){function e(){}return e.prototype=xt,e}(),O=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)}}}},k=e=>e,Ct=e=>()=>e,wt=/*#__PURE__*/ Ct(!0),Tt=/*#__PURE__*/ Ct(!1),Et=/*#__PURE__*/ Ct(void 0),Dt=Et;function Ot(e,...t){return bt(e,t)}function kt(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 At(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 jt(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 Mt=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},Nt=/*#__PURE__*/ new WeakSet,Pt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Ft=0;const pee=()=>{Ft++};function It(e){return typeof e==`string`}function Lt(e){return typeof e==`number`}function Rt(e){return typeof e==`boolean`}function mee(e){return typeof e==`bigint`}function zt(e){return typeof e==`symbol`}function Bt(e){return It(e)||Lt(e)||zt(e)}function Vt(e){return typeof e==`function`}function Ht(e){return e===void 0}function Ut(e){return e!==void 0}function Wt(e){return e!==null}function Gt(e){return e==null}function hee(e){return e!=null}function Kt(e){return!1}function qt(e){return!0}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yt(e){return Jt(e)}function Xt(e){return typeof e==`object`&&!!e||Vt(e)}const A=/*#__PURE__*/ O(2,(e,t)=>Xt(e)&&t in e),Zt=/*#__PURE__*/ O(2,(e,t)=>A(e,`_tag`)&&e._tag===t);function Qt(e){return e instanceof Error}function $t(e){return A(e,Symbol.iterator)||It(e)}const en=`~effect/Hash`,tn=e=>{switch(typeof e){case`number`:return cn(e);case`bigint`:return ln(e.toString(10));case`string`:return ln(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?ln(`Invalid Date`):ln(e.toISOString());if(e instanceof RegExp)return ln(e.toString());{if(Nt.has(e))return nn(e);let t=_n.get(e);if(t!==void 0)return t;if(vn.has(e))return pee(),ln(`[Circular]`);vn.add(e);let n=Ft,r;try{r=`~effect/Hash`in e?e[en]():typeof e==`function`?nn(e):e instanceof DataView?pn(Pt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?pn(e):e instanceof Map?mn(e):e instanceof Set?gee(e):dn(e)}finally{vn.delete(e)}return n===Ft&&_n.set(e,r),r}}return on(rn(ln(String(e))))},nn=e=>(gn.has(e)||gn.set(e,on(Math.random()*4294967296|0)),gn.get(e)),rn=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),an=/*#__PURE__*/ O(2,(e,t)=>rn(Math.imul(e,2654435761)+Math.imul(t,2246822507))),on=e=>e&3221225471|e>>>1&1073741824,sn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),cn=e=>{let t=e|0;return t===e?on(t):(sn.setFloat64(0,e===e?e:NaN),on(an(sn.getInt32(0),sn.getInt32(4))))},ln=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return on(t)},un=(e,t)=>{let n=12289;for(let r of t)n^=an(tn(r),tn(e[r]));return on(n)},dn=e=>un(e,Mt(e)),fn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return on(r)},pn=e=>{let t=6151;for(let n of e)t=an(t,tn(n));return on(t)},mn=/*#__PURE__*/ fn(/*#__PURE__*/ ln(`Map`),([e,t])=>an(tn(e),tn(t))),hn=/*#__PURE__*/ ln(`Set`),gee=/*#__PURE__*/ fn(hn,e=>an(hn,tn(e))),gn=/*#__PURE__*/ new WeakMap,_n=/*#__PURE__*/ new WeakMap,vn=/*#__PURE__*/ new WeakSet,yn=`~effect/Equal`;function bn(){return arguments.length===1?e=>xn(e,arguments[0]):xn(arguments[0],arguments[1])}function xn(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`||Nt.has(e)||Nt.has(t)?!1:Sn(e,t):!1}function Sn(e,t){let n=wn.length;for(let r=n;r-->0;)if(wn[r]===e&&Tn[r]===t)return!0;if(n)return Cn(e,t);let r=En.get(e);r||En.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Cn(e,t)),i}function Cn(e,t){wn.push(e),Tn.push(t);try{return Dn(e,t)}finally{wn.pop(),Tn.pop()}}const wn=[],Tn=[],En=/*#__PURE__*/ new WeakMap;function Dn(e,t){if(tn(e)!==tn(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=Mn(e);if(n!==Mn(t)||typeof e==`function`&&!n)return!1;if(n)return e[yn](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:On(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?kn(Pt(e),Pt(t)):kn(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:An(e,t,vee,jn):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:An(e,t,tn,xn):_ee(e,t)}function On(e,t){for(let n=0;n<e.length;n++)if(!xn(e[n],t[n]))return!1;return!0}function kn(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 _ee(e,t){let n=Mt(e),r=Mt(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!xn(e[i],t[i]))return!1;return!0}function An(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 vee=e=>tn(e[0]),jn=(e,t)=>xn(e[0],t[0])&&xn(e[1],t[1]),Mn=e=>A(e,yn),Nn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),yee=e=>A(e,Nn);function Pn(e){return yee(e)?Fn(e):e}function Fn(e){return e[Nn](globalThis[`~effect/Fiber/currentFiber`]?.context??Rn)}const In=`~effect/Fiber/currentFiber`,Ln=/*#__PURE__*/ new Map,Rn={"~effect/Context":{},base:Ln,depth:0,mapUnsafe:Ln,pipe(){return bt(this,arguments)}};function zn(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 Bn;r.add(e);let l;if(Nn in e)l=c(Fn(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=
|
|
3
|
-
`)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}const
|
|
1
|
+
import{t as e}from"./esm-CdWTLqG7.mjs";import{A as t,C as n,D as r,E as i,F as a,I as o,L as s,M as c,N as l,O as u,P as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as ee,n as te,o as E,p as ne,r as re,s as ie,t as ae,u as oe,v as D,w as se,x as ce,y as le}from"./schemas-CYxWglEB.mjs";import{C as ue,D as de,E as fe,S as pe,T as me,a as he,b as ge,c as _e,d as ve,f as ye,g as be,h as xe,l as eee,m as Se,n as Ce,o as we,r as Te,s as Ee,t as De,u as Oe,v as tee,w as ke,x as nee,y as Ae}from"./random-CJ6fASpe.mjs";import{a as je,c as Me,l as Ne,o as Pe,r as Fe,s as Ie}from"./schema-check-BzXTKlLa.mjs";import{i as Le,n as ree,r as Re}from"./factory-QgsYt4OE.mjs";import{c as ze,r as Be,s as Ve}from"./sqlite-introspector-DSCAP82F-uK1vwYwN.mjs";import{c as He,i as Ue,n as We,o as Ge,r as Ke,s as iee,t as aee}from"./dist-DmipO4_i.mjs";import{t as qe}from"./compiled-query-kXoVMG6q.mjs";import{n as oee}from"./access-OpW0SRxm.mjs";import*as Je from"node:crypto";import{randomBytes as Ye,randomUUID as see,scrypt as cee}from"node:crypto";import*as Xe from"node:path";import Ze,{dirname as lee,join as Qe,resolve as $e}from"node:path";import*as et from"node:url";import{fileURLToPath as tt}from"node:url";import*as nt from"node:child_process";import{Duplex as rt,PassThrough as it,Readable as at,pipeline as ot}from"node:stream";import{IncomingMessage as st,createServer as ct}from"node:http";import{isIP as lt}from"node:net";import*as ut from"node:fs";import dt,{mkdirSync as ft}from"node:fs";import*as pt from"node:os";import mt from"node:os";import{request as uee}from"node:https";import*as dee from"node:stream/promises";import{pipeline as fee}from"node:stream/promises";import*as ht from"node:zlib";import*as gt from"node:readline";import{DatabaseSync as _t}from"node:sqlite";import vt from"node:fs/promises";import{lookup as yt}from"node:dns/promises";const bt=(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}}},xt={pipe(){return bt(this,arguments)}},St=/*#__PURE__*/ function(){function e(){}return e.prototype=xt,e}(),O=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)}}}},k=e=>e,Ct=e=>()=>e,wt=/*#__PURE__*/ Ct(!0),Tt=/*#__PURE__*/ Ct(!1),Et=/*#__PURE__*/ Ct(void 0),Dt=Et;function Ot(e,...t){return bt(e,t)}function kt(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 At(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 jt(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 Mt=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},Nt=/*#__PURE__*/ new WeakSet,Pt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Ft=0;const pee=()=>{Ft++};function It(e){return typeof e==`string`}function Lt(e){return typeof e==`number`}function Rt(e){return typeof e==`boolean`}function mee(e){return typeof e==`bigint`}function zt(e){return typeof e==`symbol`}function Bt(e){return It(e)||Lt(e)||zt(e)}function Vt(e){return typeof e==`function`}function Ht(e){return e===void 0}function Ut(e){return e!==void 0}function Wt(e){return e!==null}function Gt(e){return e==null}function hee(e){return e!=null}function Kt(e){return!1}function qt(e){return!0}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yt(e){return Jt(e)}function Xt(e){return typeof e==`object`&&!!e||Vt(e)}const A=/*#__PURE__*/ O(2,(e,t)=>Xt(e)&&t in e),Zt=/*#__PURE__*/ O(2,(e,t)=>A(e,`_tag`)&&e._tag===t);function Qt(e){return e instanceof Error}function $t(e){return A(e,Symbol.iterator)||It(e)}const en=`~effect/Hash`,tn=e=>{switch(typeof e){case`number`:return cn(e);case`bigint`:return ln(e.toString(10));case`string`:return ln(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?ln(`Invalid Date`):ln(e.toISOString());if(e instanceof RegExp)return ln(e.toString());{if(Nt.has(e))return nn(e);let t=_n.get(e);if(t!==void 0)return t;if(vn.has(e))return pee(),ln(`[Circular]`);vn.add(e);let n=Ft,r;try{r=`~effect/Hash`in e?e[en]():typeof e==`function`?nn(e):e instanceof DataView?pn(Pt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?pn(e):e instanceof Map?mn(e):e instanceof Set?gee(e):dn(e)}finally{vn.delete(e)}return n===Ft&&_n.set(e,r),r}}return on(rn(ln(String(e))))},nn=e=>(gn.has(e)||gn.set(e,on(Math.random()*4294967296|0)),gn.get(e)),rn=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),an=/*#__PURE__*/ O(2,(e,t)=>rn(Math.imul(e,2654435761)+Math.imul(t,2246822507))),on=e=>e&3221225471|e>>>1&1073741824,sn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),cn=e=>{let t=e|0;return t===e?on(t):(sn.setFloat64(0,e===e?e:NaN),on(an(sn.getInt32(0),sn.getInt32(4))))},ln=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return on(t)},un=(e,t)=>{let n=12289;for(let r of t)n^=an(tn(r),tn(e[r]));return on(n)},dn=e=>un(e,Mt(e)),fn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return on(r)},pn=e=>{let t=6151;for(let n of e)t=an(t,tn(n));return on(t)},mn=/*#__PURE__*/ fn(/*#__PURE__*/ ln(`Map`),([e,t])=>an(tn(e),tn(t))),hn=/*#__PURE__*/ ln(`Set`),gee=/*#__PURE__*/ fn(hn,e=>an(hn,tn(e))),gn=/*#__PURE__*/ new WeakMap,_n=/*#__PURE__*/ new WeakMap,vn=/*#__PURE__*/ new WeakSet,yn=`~effect/Equal`;function bn(){return arguments.length===1?e=>xn(e,arguments[0]):xn(arguments[0],arguments[1])}function xn(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`||Nt.has(e)||Nt.has(t)?!1:_ee(e,t):!1}function _ee(e,t){let n=Cn.length;for(let r=n;r-->0;)if(Cn[r]===e&&wn[r]===t)return!0;if(n)return Sn(e,t);let r=Tn.get(e);r||Tn.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Sn(e,t)),i}function Sn(e,t){Cn.push(e),wn.push(t);try{return En(e,t)}finally{Cn.pop(),wn.pop()}}const Cn=[],wn=[],Tn=/*#__PURE__*/ new WeakMap;function En(e,t){if(tn(e)!==tn(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=An(e);if(n!==An(t)||typeof e==`function`&&!n)return!1;if(n)return e[yn](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Dn(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?On(Pt(e),Pt(t)):On(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:kn(e,t,yee,bee):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:kn(e,t,tn,xn):vee(e,t)}function Dn(e,t){for(let n=0;n<e.length;n++)if(!xn(e[n],t[n]))return!1;return!0}function On(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 vee(e,t){let n=Mt(e),r=Mt(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!xn(e[i],t[i]))return!1;return!0}function kn(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 yee=e=>tn(e[0]),bee=(e,t)=>xn(e[0],t[0])&&xn(e[1],t[1]),An=e=>A(e,yn),jn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),Mn=e=>A(e,jn);function Nn(e){return Mn(e)?Pn(e):e}function Pn(e){return e[jn](globalThis[`~effect/Fiber/currentFiber`]?.context??Ln)}const Fn=`~effect/Fiber/currentFiber`,In=/*#__PURE__*/ new Map,Ln={"~effect/Context":{},base:In,depth:0,mapUnsafe:In,pipe(){return bt(this,arguments)}};function Rn(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 zn;r.add(e);let l;if(jn in e)l=c(Pn(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=Hn(e);else if(!t?.ignoreToString&&A(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Un(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=>`${Bn(t)}:${c(Wn(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Bn(t)}: ${c(Wn(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 zn=`[Circular]`;function Bn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Vn(e){return e.map(e=>`[${Bn(e)}]`).join(``)}function Hn(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Un(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Wn(e,t){try{return e[t]}catch{return`[property access threw]`}}function Gn(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=A(r,jn)?Nn(r):Nn(t);if(typeof i==`bigint`)return Rn(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!A(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),!Kn(a)||qn(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:Nn(n)}});return n.push(o),o},t?.space)??`null`}function Kn(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function qn(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 Jn=/*#__PURE__*/ Symbol.for(`nodejs.util.inspect.custom`),Yn=e=>{try{return e=Nn(e),A(e,`toJSON`)&&Vt(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(Yn):e}catch{return`[toJSON threw]`}},Xn=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Gn(e,{space:t}):Rn(e,{space:t})}catch{return String(e)}},Zn={toJSON(){return Yn(this)},[Jn](){return this.toJSON()},toString(){return Rn(this.toJSON())}};var Qn=class{[Jn](){return this.toJSON()}toString(){return Rn(this.toJSON())}};const $n=/*#__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=>{$n&&(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{}}};return er()!==0&&t[e](()=>(/* @__PURE__ */ Error()).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`,xee={_A:k,_E:k,_R:k},cr=`${or}/identifier`,lr=`${or}/args`,ur=`${or}/evaluate`,dr=`${or}/successCont`,fr=`${or}/failureCont`,pr=`${or}/ensureCont`,mr=/*#__PURE__*/ Symbol.for(`effect/Effect/Yield`),hr={pipe(){return bt(this,arguments)},toJSON(){return{...this}},toString(){return Rn(this.toJSON(),{ignoreToString:!0,space:2})},[Jn](){return this.toJSON()}},See={[or]:xee,...hr,[Symbol.iterator](){return new nr(this)},toJSON(){return{_id:`Effect`,op:this[cr],...lr in this?{args:this[lr]}:void 0}}},gr=e=>A(e,or),_r=e=>A(e,sr),vr=`~effect/Cause`,yr=`~effect/Cause/Reason`,br=e=>A(e,vr),Cee=e=>A(e,yr);var xr=class{constructor(e){this[vr]=vr,this.reasons=e}pipe(){return bt(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${Rn(this.reasons)})`}[Jn](){return this.toJSON()}[yn](e){return br(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>bn(t,e.reasons[n]))}[en](){return pn(this.reasons)}};const Sr=/*#__PURE__*/ new WeakMap;var Cr=class{[yr];annotations;_tag;constructor(e,t,n){if(this[yr]=yr,this._tag=e,t!==wr&&typeof n==`object`&&n&&t.size>0){let e=Sr.get(n);e&&(t=new Map([...e,...t])),Sr.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 bt(this,arguments)}toString(){return Rn(this)}[Jn](){return this.toString()}};const wr=/*#__PURE__*/ new Map;var Tr=class extends Cr{constructor(e,t=wr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${Rn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[yn](e){return Pr(e)&&bn(this.error,e.error)&&bn(this.annotations,e.annotations)}[en](){return an(ln(this._tag))(an(tn(this.error))(tn(this.annotations)))}};const Er=e=>new xr(e),Dr=(e,t)=>{let n=/* @__PURE__ */ new Map,r=[];for(let i of e.concat(t)){let e=tn(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>bn(e,i)))continue;else t.push(i);r.push(i)}return r},Or=/*#__PURE__*/ O(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new xr(Dr(e.reasons,t.reasons));return bn(e,n)?e:n}),kr=/*#__PURE__*/ new xr([]),Ar=e=>new xr([new Tr(e)]);var jr=class extends Cr{constructor(e,t=wr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${Rn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[yn](e){return Fr(e)&&bn(this.defect,e.defect)&&bn(this.annotations,e.annotations)}[en](){return an(ln(this._tag))(an(tn(this.defect))(tn(this.annotations)))}};const Mr=e=>new xr([new jr(e)]),Nr=/*#__PURE__*/ O(e=>br(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new xr(e.reasons.map(e=>e.annotate(t,n)))),Pr=e=>e._tag===`Fail`,Fr=e=>e._tag===`Die`,Ir=e=>e._tag===`Interrupt`;function Lr(e){return Kr(`Effect.evaluate: Not implemented`)}const Rr=e=>({...See,[cr]:e.op,[ur]:e[ur]??Lr,[dr]:e[dr],[fr]:e[fr],[pr]:e[pr]}),zr=e=>{let t=Rr(e),n=function(e){this[lr]=e};return n.prototype=t,function(e){return new n(e)}},Br=e=>{let t={[sr]:sr,_tag:e.op,get[e.prop](){return this[lr]},...Rr(e),toString(){return`${e.op}(${Rn(this[lr])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[lr]}},[yn](e){return _r(e)&&e._tag===this._tag&&bn(this[lr],e[lr])},[en](){return an(ln(e.op),tn(this[lr]))}},n=function(e){this[lr]=e};return n.prototype=t,function(e){return new n(e)}},Vr=/*#__PURE__*/ Br({op:`Success`,prop:`value`,[ur](e){let t=e.getCont(dr);return t?t[dr](this[lr],e,this):e.yieldWith(this)}}),Hr={key:`effect/Cause/StackTrace`},Ur={key:`effect/Cause/InterruptorStackTrace`},Wr=/*#__PURE__*/ Br({op:`Failure`,prop:`cause`,[ur](e){let t=this[lr],n=!1;e.cache.stackFrame&&(t=Nr(t,{mapUnsafe:/* @__PURE__ */ new Map([[Hr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(fr),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=cr in r,r=e.getCont(fr);a&&(t=Er(t.reasons.filter(e=>e._tag!==`Fail`))),t=Or(t,i),n=!0}return r?r[fr](t,e,n?void 0:this):e.yieldWith(n?Wr(t):this)}}),Gr=e=>Wr(Ar(e)),Kr=e=>Wr(Mr(e)),qr=/*#__PURE__*/ zr({op:`WithFiber`,[ur](e){return this[lr](e)}}),Jr=/*#__PURE__*/ function(){class e extends globalThis.Error{}let t=/*#__PURE__*/ Rr({op:`YieldableError`,[ur](){return Gr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Yr=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Symbol.for(`effect/Data/Error/plainArgs`);return class extends Jr{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}}}}(),Xr=e=>{class t extends Yr{_tag=e}return t.prototype.name=e,t},Zr=`~effect/Cause/NoSuchElementError`,Qr=e=>A(e,Zr);var $r=class extends (/*#__PURE__*/ Xr(`NoSuchElementError`)){[Zr]=Zr;constructor(e){super({message:e})}};const ei=`~effect/Cause/Done`,ti=e=>A(e,ei),ni={[ei]:ei,_tag:`Done`,value:void 0},ri=e=>e===void 0?ni:{[ei]:ei,_tag:`Done`,value:e},ii=/*#__PURE__*/ Gr(ni),ai=e=>e===void 0?ii:Gr(ri(e)),oi=e=>Rr({op:e.label,[ur]:e.evaluate}),si=e=>(t,n)=>t===n||e(t,n),ci=(e,t)=>e===t,li=()=>ci;function wee(e){return si((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 Tee(e){return si((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 ui=`~effect/Option`,di={[ui]:{_A:e=>e},...hr,[Symbol.iterator](){return new nr(this)}},Eee=/*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(di),{_tag:`Some`,_op:`Some`,[yn](e){return fi(e)&&mi(e)&&bn(this.value,e.value)},[en](){return an(tn(this._tag))(tn(this.value))},toString(){return`some(${Rn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:Yn(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Dee=/*#__PURE__*/ tn(`None`),Oee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(di),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[yn](e){return fi(e)&&pi(e)},[en](){return Dee},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),fi=e=>A(e,ui),pi=e=>e._tag===`None`,mi=e=>e._tag===`Some`,kee=/*#__PURE__*/ Object.create(Oee),hi=function(e){this.value=e};hi.prototype=Eee;const Aee=e=>new hi(e),gi=`~effect/Result`,_i={[gi]:{
|
|
4
4
|
/* v8 ignore next 2 */
|
|
5
|
-
_A:e=>e,_E:e=>e},...
|
|
5
|
+
_A:e=>e,_E:e=>e},...hr,[Symbol.iterator](){return new nr(this)}},jee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(_i),{_tag:`Success`,_op:`Success`,[yn](e){return vi(e)&&bi(e)&&bn(this.success,e.success)},[en](){return an(tn(this._tag))(tn(this.success))},toString(){return`success(${Rn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:Yn(this.success)}}}),Mee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(_i),{_tag:`Failure`,_op:`Failure`,[yn](e){return vi(e)&&yi(e)&&bn(this.failure,e.failure)},[en](){return an(tn(this._tag))(tn(this.failure))},toString(){return`failure(${Rn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:Yn(this.failure)}}}),vi=e=>A(e,gi),yi=e=>e._tag===`Failure`,bi=e=>e._tag===`Success`,xi=function(e){this.failure=e};xi.prototype=Mee;const Nee=e=>new xi(e),Si=function(e){this.success=e};Si.prototype=jee;const Pee=e=>new Si(e);function Ci(e){return(t,n)=>t===n?0:e(t,n)}const Fee=/*#__PURE__*/ Ci((e,t)=>e<t?-1:1),wi=/*#__PURE__*/ Ci((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),Iee=/*#__PURE__*/ O(2,(e,t)=>Ci((n,r)=>e(t(n),t(r)))),Lee=e=>O(2,(t,n)=>e(t,n)===-1),Ti=e=>O(2,(t,n)=>e(t,n)===1),Ree=e=>O(2,(t,n)=>e(t,n)!==1),Ei=e=>O(2,(t,n)=>e(t,n)!==-1),Di=()=>kee,Oi=Aee,zee=fi,ki=pi,Ai=mi,ji=/*#__PURE__*/ O(2,(e,{onNone:t,onSome:n})=>ki(e)?t():n(e.value)),Mi=/*#__PURE__*/ O(2,(e,t)=>ki(e)?t():e.value),Ni=e=>e==null?Di():Oi(e),Pi=e=>e===void 0?Di():Oi(e),Fi=/*#__PURE__*/ Mi(Et),Ii=e=>(...t)=>{try{return Oi(e(...t))}catch{return Di()}},Li=/*#__PURE__*/ O(2,(e,t)=>ki(e)?Di():Oi(t(e.value))),Ri=/*#__PURE__*/ O(2,(e,t)=>ki(e)?Di():t(e.value)),Bee=e=>ki(e)?[]:[e.value],Vee=/*#__PURE__*/ O(2,(e,t)=>ki(e)?Di():t(e.value)?Oi(e.value):Di()),zi=`~effect/Context/Service`,j=function(){function e(){}let t=e;Object.setPrototypeOf(t,Bi);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Hi]=Hi,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Vi.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Bi={[zi]:zi,.../*#__PURE__*/ oi({label:`Service`,evaluate(e){return Vr(la(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return na(this,e)},use(e){return qr(t=>e(la(t.context,this)))},useSync(e){return qr(t=>Vr(e(la(t.context,this))))}},Vi=/*#__PURE__*/ new Set,Hi=`~effect/Context/Reference`,Ui=`~effect/Context`,Wi=(e,t,n,r)=>{let i=Object.create(Hee);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Gi=(e,t)=>{t&&(Gi(e,t.parent),e.set(t.key,t.value))},Ki=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Gi(t,e.overlay),e._flat=t},qi=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),Xi(n)},Ji=/*#__PURE__*/ Symbol(),Yi=(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)?Ji:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=8&&(n.base=Ki(n),n.overlay=void 0,n.depth=0),r)},Xi=e=>Wi(void 0,e,void 0,0),Hee={get mapUnsafe(){return Ki(this)},...hr,[Ui]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[yn](e){if(!Zi(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)||!bn(r,n.get(e)))return!1;return!0},[en](){return cn(this.mapUnsafe.size)}},Uee=(e,t)=>e.cacheRoot===t.cacheRoot,Zi=e=>A(e,Ui),Qi=e=>A(e,zi),$i=e=>!!e[Hi],ea=()=>ta,ta=/*#__PURE__*/ Xi(/*#__PURE__*/ new Map),na=(e,t)=>Xi(/* @__PURE__ */ new Map([[e.key,t]])),ra=/*#__PURE__*/ O(3,(e,t,n)=>ia(e,t.key,n)),ia=(e,t,n)=>{let r=e,i=Vi.has(t)?void 0:r.cacheRoot;if(r.depth>=8){let e=new Map(r.mapUnsafe);return e.set(t,n),Wi(i,e,void 0,0)}return Wi(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},aa=/*#__PURE__*/ O(3,(e,t,n)=>{let r=Yi(e,t.key);return r===Ji?$i(t)?da(t):n():r}),oa=/*#__PURE__*/ O(2,(e,t)=>sa(e,t.key)),sa=(e,t)=>{let n=Yi(e,t);return n===Ji?void 0:n},ca=/*#__PURE__*/ O(2,(e,t)=>{let n=Yi(e,t.key);if(n===Ji){if($i(t))return da(t);throw fa(t)}return n}),la=ca,ua=`~effect/Context/defaultValue`,da=e=>ua in e?e[ua]:e[ua]=e.defaultValue(),fa=e=>{let t=/* @__PURE__ */ Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
|
|
6
6
|
`);e.splice(1,3),t.stack=e.join(`
|
|
7
|
-
`)}return t},ha=/*#__PURE__*/ O(2,(e,t)=>{let n=Zi(e,t.key);return n===Xi?ta(t)?ki(pa(t)):Oi():ki(n)}),ga=/*#__PURE__*/ O(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:Yi(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),_a=(...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 Qi(t)},va=(...e)=>t=>Yi(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),ya=j,ba=e=>e.length>0,xa=e=>e>0?Math.floor(e):0,Sa=Nee,Ca=Mee,wa=e=>{if(Vt(e))try{return Sa(e())}catch(e){return Ca(e)}try{return Sa(e.try())}catch(t){return Ca(e.catch(t))}},Ta=yi,Ea=bi,Da=xi,Oa=/*#__PURE__*/ O(2,(e,t)=>Ea(e)?Ca(t(e.failure)):e),ka=/*#__PURE__*/ O(2,(e,t)=>Da(e)?Sa(t(e.success)):e),Aa=/*#__PURE__*/ O(2,(e,{onFailure:t,onSuccess:n})=>Ea(e)?t(e.failure):n(e.success)),ja=/*#__PURE__*/ (/* @__PURE__ */ O(2,(e,t)=>Ea(e)?t(e.failure):e.success))(Et),Ma=Cee,Na=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},Pa=()=>({}),Fa=e=>Object.keys(e).length===0,Ia=/*#__PURE__*/ O(2,(e,t)=>Object.hasOwn(e,t)),La=/*#__PURE__*/ O(2,(e,t)=>{let n={...e};for(let r of za(e))ar(n,r,t(e[r],r));return n}),Ra=/*#__PURE__*/ O(2,(e,t)=>{let n=Pa();for(let r of za(e))t(e[r],r)&&ar(n,r,e[r]);return n}),za=e=>Object.keys(e),Hee=/*#__PURE__*/ O(3,(e,t,n)=>({...e,[t]:n})),Uee=e=>O(2,(t,n)=>{for(let r of za(t))if(!Ia(n,r)||!e(t[r],n[r]))return!1;return!0}),Wee=e=>{let t=Uee(e);return(e,n)=>t(e,n)&&t(n,e)},Ba=globalThis.Array,Va=e=>Ba.isArray(e)?e:Ba.from(e),Ha=e=>Ba.isArray(e)?e:[e],Ua=/*#__PURE__*/ O(2,(e,t)=>[...e,t]);Ba.isArray;const Wa=ba,Ga=ba;function Gee(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const Kee=e=>e[e.length-1],qee=(e,t)=>Math.min(xa(e),t),Jee=/*#__PURE__*/ O(2,(e,t)=>{let n=Va(e);return n.slice(0,qee(t,n.length))}),Yee=e=>Ba.from(e).reverse(),Xee=(e,t)=>{let n=tn(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(bn(e,t))return!1;return r.push(t),!0},Ka=()=>[],qa=e=>[e],Ja=/*#__PURE__*/ O(2,(e,t)=>e.map(t)),Zee=wee,Qee=e=>{let t=Va(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)Xee(n,e)&&r.push(e);return r},Ya=`~effect/Duration`,Xa=/*#__PURE__*/ BigInt(0),Za=/*#__PURE__*/ BigInt(1),$ee=/*#__PURE__*/ BigInt(2),ete=/*#__PURE__*/ BigInt(10),Qa=/*#__PURE__*/ BigInt(24),$a=/*#__PURE__*/ BigInt(60),eo=/*#__PURE__*/ BigInt(1e3),to=/*#__PURE__*/ BigInt(1e6),no=e=>BigInt(e<0?Math.ceil(e-.5):Math.floor(e+.5)),ro=e=>no(e*1e6),io=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=ete**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t,s=o/a+(o%a*$ee>=a?Za:Xa);return r?-s:s},tte=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,ao=e=>{switch(typeof e){case`number`:return _o(e);case`bigint`:return go(e);case`string`:{if(e===`Infinity`)return mo;if(e===`-Infinity`)return ho;let t=tte.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return go(io(r,Za));if(i===`micro`||i===`micros`)return go(io(r,eo));let a=Number(r);switch(i){case`milli`:case`millis`:return _o(a);case`second`:case`seconds`:return vo(a);case`minute`:case`minutes`:return yo(a);case`hour`:case`hours`:return ste(a);case`day`:case`days`:return cte(a);case`week`:case`weeks`:return lte(a)}break}case`object`:{if(e===null)break;if(Ya in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Lt)?oo(e):Number.isNaN(e[0])||Number.isNaN(e[1])?po:e[0]===-1/0||e[1]===-1/0?ho:e[0]===1/0||e[1]===1/0?mo:co(no(e[0]*1e9+e[1]));let t=e,n=0;return t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds?co(n):co(no(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0)))}}return oo(e)},oo=e=>{throw Error(`Invalid Input: ${e}`)},so={_tag:`Millis`,millis:0},nte={_tag:`Infinity`},rte={_tag:`NegativeInfinity`},ite={[Ya]:Ya,[en](){switch(this.value._tag){case`Millis`:{let e=this.value.millis*1e6;return Number.isFinite(e)?tn(no(e)):cn(this.value.millis)}case`Nanos`:return tn(this.value.nanos);default:return dn(this.value)}},[yn](e){return lo(e)&&wo(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`}}},[Yn](){return this.toJSON()},pipe(){return bt(this,arguments)}},co=e=>{let t=Object.create(ite);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?so:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:ro(e)}:e>0?nte:rte:e===Xa?so:{_tag:`Nanos`,nanos:e},t},lo=e=>A(e,Ya),uo=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,fo=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Xa;case`Infinity`:case`NegativeInfinity`:return!1}},ate=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Xa;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},ote=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return mo;case`Millis`:return e.value.millis<0?co(-e.value.millis):e;case`Nanos`:return e.value.nanos<Xa?co(-e.value.nanos):e}},po=/*#__PURE__*/ co(0),mo=/*#__PURE__*/ co(1/0),ho=/*#__PURE__*/ co(-1/0),go=e=>co(e),_o=e=>co(e),vo=e=>co(e*1e3),yo=e=>co(e*6e4),ste=e=>co(e*36e5),cte=e=>co(e*864e5),lte=e=>co(e*6048e5),bo=e=>So(ao(e),{onMillis:k,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),ute=e=>So(ao(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),xo=e=>{let t=ao(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return ro(t.value.millis)}},So=/*#__PURE__*/ O(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)()}}),dte=/*#__PURE__*/ O(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(xo(e),t.value.nanos):n.onNanos(e.value.nanos,xo(t))),Co=(e,t)=>dte(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),wo=/*#__PURE__*/ O(2,(e,t)=>Co(e,t)),To=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=xo(e),n=t<Xa,r=n?-t:t,i=r/to,a=i/eo,o=a/$a,s=o/$a,c=s/Qa,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Qa),minutes:l*Number(o%$a),seconds:l*Number(a%$a),millis:l*Number(i%eo),nanos:l*Number(r%to)}},Eo=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(fo(e))return`0`;if(ate(e))return`-`+Eo(ote(e));let t=To(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(` `)},Do=/*#__PURE__*/ ya(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new Mo}),Oo=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},ko=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},Ao=e=>{try{return ko(e)}catch{return Oo(e)}};var jo=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}},Mo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Oo:Ao)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new No(this.setImmediate)}},No=class{tasks=/*#__PURE__*/ new jo;running=void 0;setImmediate;constructor(e=Ao){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 Po=/*#__PURE__*/ ya(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Fo=/*#__PURE__*/ ya(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Io=class extends St{constructor(e){super(),e&&or(this,e)}},Lo=e=>class extends Io{_tag=e},Ro=()=>new Proxy({},{get(e,t,n){return t===`$is`?Zt:t===`$match`?zo:e=>({...e,_tag:t})}});function zo(){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 Bo=Xr,Vo=Zr,Ho=`~effect/encoding/EncodingError`;var Uo=class extends (/*#__PURE__*/ Vo(`EncodingError`)){[Ho]=Ho};const Wo=e=>{switch(e){case 16:return qo();case 32:return Jo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Ko();return t}}},M=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Go=()=>Math.random()*4294967296>>>0,Ko=()=>{let e=Go();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15])},qo=()=>{let e=Go(),t=Go();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15],M[t>>>28],M[t>>>24&15],M[t>>>20&15],M[t>>>16&15],M[t>>>12&15],M[t>>>8&15],M[t>>>4&15],M[t&15])},Jo=()=>{let e=Go(),t=Go(),n=Go(),r=Go();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15],M[t>>>28],M[t>>>24&15],M[t>>>20&15],M[t>>>16&15],M[t>>>12&15],M[t>>>8&15],M[t>>>4&15],M[t&15],M[n>>>28],M[n>>>24&15],M[n>>>20&15],M[n>>>16&15],M[n>>>12&15],M[n>>>8&15],M[n>>>4&15],M[n&15],M[r>>>28],M[r>>>24&15],M[r>>>20&15],M[r>>>16&15],M[r>>>12&15],M[r>>>8&15],M[r>>>4&15],M[r&15])},Yo=`effect/Tracer/ParentSpan`;var Xo=class extends (/*#__PURE__*/ j()(Yo,{fiberCached:!0})){};const Zo=e=>e,Qo=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??na()}),$o=/*#__PURE__*/ ya(`effect/Tracer/DisablePropagation`,{defaultValue:Tt}),es=/*#__PURE__*/ ya(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),ts=/*#__PURE__*/ ya(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),ns=`effect/Tracer`,rs=/*#__PURE__*/ ya(ns,{fiberCached:!0,defaultValue:()=>is}),is=/*#__PURE__*/ Zo({span:e=>new as(e)});var as=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=Li(this.parent)?.traceId??Wo(32)}get spanId(){return this._spanId??=Wo(16)}get attributes(){return this._attributes??=/* @__PURE__ */ new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}};const os=/*#__PURE__*/ ya(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),ss=/*#__PURE__*/ ya(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Et}),cs=/*#__PURE__*/ ya(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:wt}),ls=/*#__PURE__*/ ya(`effect/References/TracerTimingEnabled`,{defaultValue:wt}),us=/*#__PURE__*/ ya(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),ds=/*#__PURE__*/ ya(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),fs=/*#__PURE__*/ ya(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),ps=/*#__PURE__*/ ya(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),ms=/*#__PURE__*/ ya(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),hs=/*#__PURE__*/ ya(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),gs=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=tr();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};nr(3);let n=/* @__PURE__ */ Error();return nr(t),{...e,captureStackTrace:vs(()=>n.stack)}},_s=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}},
|
|
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?
|
|
7
|
+
`)}return t},pa=/*#__PURE__*/ O(2,(e,t)=>{let n=Yi(e,t.key);return n===Ji?$i(t)?Oi(da(t)):Di():Oi(n)}),ma=/*#__PURE__*/ O(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:qi(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),ha=(...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 Xi(t)},ga=(...e)=>t=>qi(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),_a=j,va=e=>e.length>0,ya=e=>e>0?Math.floor(e):0,ba=Pee,xa=Nee,Sa=e=>{if(Vt(e))try{return ba(e())}catch(e){return xa(e)}try{return ba(e.try())}catch(t){return xa(e.catch(t))}},Ca=vi,wa=yi,Ta=bi,Ea=/*#__PURE__*/ O(2,(e,t)=>wa(e)?xa(t(e.failure)):e),Da=/*#__PURE__*/ O(2,(e,t)=>Ta(e)?ba(t(e.success)):e),Oa=/*#__PURE__*/ O(2,(e,{onFailure:t,onSuccess:n})=>wa(e)?t(e.failure):n(e.success)),ka=/*#__PURE__*/ (/* @__PURE__ */ O(2,(e,t)=>wa(e)?t(e.failure):e.success))(Et),Aa=wee,ja=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},Ma=()=>({}),Na=e=>Object.keys(e).length===0,Pa=/*#__PURE__*/ O(2,(e,t)=>Object.hasOwn(e,t)),Fa=/*#__PURE__*/ O(2,(e,t)=>{let n={...e};for(let r of La(e))ir(n,r,t(e[r],r));return n}),Ia=/*#__PURE__*/ O(2,(e,t)=>{let n=Ma();for(let r of La(e))t(e[r],r)&&ir(n,r,e[r]);return n}),La=e=>Object.keys(e),Ra=/*#__PURE__*/ O(3,(e,t,n)=>({...e,[t]:n})),za=e=>O(2,(t,n)=>{for(let r of La(t))if(!Pa(n,r)||!e(t[r],n[r]))return!1;return!0}),Wee=e=>{let t=za(e);return(e,n)=>t(e,n)&&t(n,e)},Ba=globalThis.Array,Va=e=>Ba.isArray(e)?e:Ba.from(e),Ha=e=>Ba.isArray(e)?e:[e],Ua=/*#__PURE__*/ O(2,(e,t)=>[...e,t]);Ba.isArray;const Wa=va,Ga=va;function Gee(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const Kee=e=>e[e.length-1],qee=(e,t)=>Math.min(ya(e),t),Jee=/*#__PURE__*/ O(2,(e,t)=>{let n=Va(e);return n.slice(0,qee(t,n.length))}),Yee=e=>Ba.from(e).reverse(),Xee=(e,t)=>{let n=tn(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(bn(e,t))return!1;return r.push(t),!0},Ka=()=>[],qa=e=>[e],Ja=/*#__PURE__*/ O(2,(e,t)=>e.map(t)),Zee=Tee,Qee=e=>{let t=Va(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)Xee(n,e)&&r.push(e);return r},Ya=`~effect/Duration`,Xa=/*#__PURE__*/ BigInt(0),Za=/*#__PURE__*/ BigInt(1),$ee=/*#__PURE__*/ BigInt(2),ete=/*#__PURE__*/ BigInt(10),Qa=/*#__PURE__*/ BigInt(24),$a=/*#__PURE__*/ BigInt(60),eo=/*#__PURE__*/ BigInt(1e3),to=/*#__PURE__*/ BigInt(1e6),no=e=>BigInt(e<0?Math.ceil(e-.5):Math.floor(e+.5)),ro=e=>no(e*1e6),io=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=ete**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t,s=o/a+(o%a*$ee>=a?Za:Xa);return r?-s:s},tte=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,ao=e=>{switch(typeof e){case`number`:return _o(e);case`bigint`:return go(e);case`string`:{if(e===`Infinity`)return mo;if(e===`-Infinity`)return ho;let t=tte.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return go(io(r,Za));if(i===`micro`||i===`micros`)return go(io(r,eo));let a=Number(r);switch(i){case`milli`:case`millis`:return _o(a);case`second`:case`seconds`:return vo(a);case`minute`:case`minutes`:return yo(a);case`hour`:case`hours`:return ste(a);case`day`:case`days`:return cte(a);case`week`:case`weeks`:return lte(a)}break}case`object`:{if(e===null)break;if(Ya in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Lt)?oo(e):Number.isNaN(e[0])||Number.isNaN(e[1])?po:e[0]===-1/0||e[1]===-1/0?ho:e[0]===1/0||e[1]===1/0?mo:co(no(e[0]*1e9+e[1]));let t=e,n=0;return t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds?co(n):co(no(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0)))}}return oo(e)},oo=e=>{throw Error(`Invalid Input: ${e}`)},so={_tag:`Millis`,millis:0},nte={_tag:`Infinity`},rte={_tag:`NegativeInfinity`},ite={[Ya]:Ya,[en](){switch(this.value._tag){case`Millis`:{let e=this.value.millis*1e6;return Number.isFinite(e)?tn(no(e)):cn(this.value.millis)}case`Nanos`:return tn(this.value.nanos);default:return dn(this.value)}},[yn](e){return lo(e)&&Co(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[Jn](){return this.toJSON()},pipe(){return bt(this,arguments)}},co=e=>{let t=Object.create(ite);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?so:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:ro(e)}:e>0?nte:rte:e===Xa?so:{_tag:`Nanos`,nanos:e},t},lo=e=>A(e,Ya),uo=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,fo=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Xa;case`Infinity`:case`NegativeInfinity`:return!1}},ate=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Xa;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},ote=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return mo;case`Millis`:return e.value.millis<0?co(-e.value.millis):e;case`Nanos`:return e.value.nanos<Xa?co(-e.value.nanos):e}},po=/*#__PURE__*/ co(0),mo=/*#__PURE__*/ co(1/0),ho=/*#__PURE__*/ co(-1/0),go=e=>co(e),_o=e=>co(e),vo=e=>co(e*1e3),yo=e=>co(e*6e4),ste=e=>co(e*36e5),cte=e=>co(e*864e5),lte=e=>co(e*6048e5),bo=e=>So(ao(e),{onMillis:k,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),ute=e=>So(ao(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),xo=e=>{let t=ao(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return ro(t.value.millis)}},So=/*#__PURE__*/ O(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)()}}),dte=/*#__PURE__*/ O(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(xo(e),t.value.nanos):n.onNanos(e.value.nanos,xo(t))),fte=(e,t)=>dte(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Co=/*#__PURE__*/ O(2,(e,t)=>fte(e,t)),wo=e=>{if(e.value._tag===`Infinity`)return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};if(e.value._tag===`NegativeInfinity`)return{days:-1/0,hours:-1/0,minutes:-1/0,seconds:-1/0,millis:-1/0,nanos:-1/0};let t=xo(e),n=t<Xa,r=n?-t:t,i=r/to,a=i/eo,o=a/$a,s=o/$a,c=s/Qa,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Qa),minutes:l*Number(o%$a),seconds:l*Number(a%$a),millis:l*Number(i%eo),nanos:l*Number(r%to)}},To=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(fo(e))return`0`;if(ate(e))return`-`+To(ote(e));let t=wo(e),n=[];return t.days!==0&&n.push(`${t.days}d`),t.hours!==0&&n.push(`${t.hours}h`),t.minutes!==0&&n.push(`${t.minutes}m`),t.seconds!==0&&n.push(`${t.seconds}s`),t.millis!==0&&n.push(`${t.millis}ms`),t.nanos!==0&&n.push(`${t.nanos}ns`),n.join(` `)},Eo=/*#__PURE__*/ _a(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new jo}),Do=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Oo=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ko=e=>{try{return Oo(e)}catch{return Do(e)}};var Ao=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},jo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Do:ko)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Mo(this.setImmediate)}},Mo=class{tasks=/*#__PURE__*/ new Ao;running=void 0;setImmediate;constructor(e=ko){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}};const No=/*#__PURE__*/ _a(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Po=/*#__PURE__*/ _a(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Fo=class extends St{constructor(e){super(),e&&ar(this,e)}},Io=e=>class extends Fo{_tag=e},Lo=()=>new Proxy({},{get(e,t,n){return t===`$is`?Zt:t===`$match`?Ro:e=>({...e,_tag:t})}});function Ro(){if(arguments.length===1){let e=arguments[0];return function(t){return e[t._tag](t)}}let e=arguments[0];return arguments[1][e._tag](e)}const zo=Yr,Bo=Xr,Vo=`~effect/encoding/EncodingError`;var Ho=class extends (/*#__PURE__*/ Bo(`EncodingError`)){[Vo]=Vo};const Uo=e=>{switch(e){case 16:return Ko();case 32:return qo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Go();return t}}},M=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Wo=()=>Math.random()*4294967296>>>0,Go=()=>{let e=Wo();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15])},Ko=()=>{let e=Wo(),t=Wo();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15],M[t>>>28],M[t>>>24&15],M[t>>>20&15],M[t>>>16&15],M[t>>>12&15],M[t>>>8&15],M[t>>>4&15],M[t&15])},qo=()=>{let e=Wo(),t=Wo(),n=Wo(),r=Wo();return String.fromCharCode(M[e>>>28],M[e>>>24&15],M[e>>>20&15],M[e>>>16&15],M[e>>>12&15],M[e>>>8&15],M[e>>>4&15],M[e&15],M[t>>>28],M[t>>>24&15],M[t>>>20&15],M[t>>>16&15],M[t>>>12&15],M[t>>>8&15],M[t>>>4&15],M[t&15],M[n>>>28],M[n>>>24&15],M[n>>>20&15],M[n>>>16&15],M[n>>>12&15],M[n>>>8&15],M[n>>>4&15],M[n&15],M[r>>>28],M[r>>>24&15],M[r>>>20&15],M[r>>>16&15],M[r>>>12&15],M[r>>>8&15],M[r>>>4&15],M[r&15])},Jo=`effect/Tracer/ParentSpan`;var Yo=class extends (/*#__PURE__*/ j()(Jo,{fiberCached:!0})){};const Xo=e=>e,Zo=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??ea()}),Qo=/*#__PURE__*/ _a(`effect/Tracer/DisablePropagation`,{defaultValue:Tt}),$o=/*#__PURE__*/ _a(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),es=/*#__PURE__*/ _a(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),ts=`effect/Tracer`,ns=/*#__PURE__*/ _a(ts,{fiberCached:!0,defaultValue:()=>rs}),rs=/*#__PURE__*/ Xo({span:e=>new is(e)});var is=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??=Fi(this.parent)?.traceId??Uo(32)}get spanId(){return this._spanId??=Uo(16)}get attributes(){return this._attributes??=/* @__PURE__ */ new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}};const as=/*#__PURE__*/ _a(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),os=/*#__PURE__*/ _a(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Et}),ss=/*#__PURE__*/ _a(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:wt}),cs=/*#__PURE__*/ _a(`effect/References/TracerTimingEnabled`,{defaultValue:wt}),ls=/*#__PURE__*/ _a(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),us=/*#__PURE__*/ _a(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),ds=/*#__PURE__*/ _a(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),fs=/*#__PURE__*/ _a(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),ps=/*#__PURE__*/ _a(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),ms=/*#__PURE__*/ _a(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),hs=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:_s(()=>n.stack)}},gs=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}},_s=/*#__PURE__*/ gs(3);var vs=class extends Cr{constructor(e,t=wr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[yn](e){return Ir(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[en](){return an(ln(`${this._tag}:${this.fiberId}`))(nn(this.annotations))}};const ys=e=>new vs(e),bs=e=>new xr([new vs(e)]),xs=e=>{let t=e.reasons.find(Pr);return t?ba(t):xa(e)},Ss=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return ba(n.error)}return xa(e)},Cs=e=>e.reasons.some(Fr),ws=e=>{let t=e.reasons.find(Fr);return t?ba(t.defect):xa(e)},Ts=e=>e.reasons.some(Ir),Es=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=/* @__PURE__ */ new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?ba(t):xa(e)},Ds=e=>{let t=Es(e);return wa(t)?Os:t.success},Os=/*#__PURE__*/ new Set,ks=e=>Xi(e.annotations),As=/*#__PURE__*/ O(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>Pr(e)?(n=!0,new Tr(t(e.error),e.annotations)):e);return n?Er(r):e}),js=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},Ms=(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){if(i._tag===`Interrupt`){r.push(i);continue}n.push(Ns(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=Rs(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(Ns(i,r[0].annotations,t))}}finally{i!==0&&tr(i)}return n},Ns=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Ps(e),{cause:e.cause?Ns(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=Is(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?Ls(e,t):e}n?.includeCauseInStack&&(i.stack=Vs(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else{i=new globalThis.Error(e?r===`string`?e:Gn(e):`Unknown error: ${e}`);let n=`${i.name}: ${i.message}`;i.stack=t?Ls(n,t):n}return i},Ps=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 Gn(e)},Fs=/\((.*)\)/g,Is=(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?Ls(a.join(`
|
|
10
10
|
`),n):a.join(`
|
|
11
|
-
`)},
|
|
12
|
-
`)},
|
|
13
|
-
`)},
|
|
14
|
-
`),
|
|
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${Us(e.cause,`${t} `)}\n${t}}`),r},Ws=`~effect/Fiber`,Gs={_A:k,_E:k},Ks={id:0},qs=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Js=()=>qs===void 0?void 0:new qs(`effect/Fiber`),Ys=()=>globalThis[In];var Xs=class{constructor(e,t=!0){this.setContext(e),this.id=++Ks.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[Ws](){return Gs}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return da(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Dt):(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=xs(e);this.cache.stackFrame&&(n=Pr(n,ia(Ur,this.cache.stackFrame))),t&&(n=Pr(n,t)),this._interruptedCause=this._interruptedCause?kr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(uc(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=Js();return}let n=ec.interruptChildren&&ec.interruptChildren(this);if(n!==void 0)return this.evaluate(Xc(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[In];globalThis[In]=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=uc(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Xc(gc,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[dr](this),i===hr){let e=this._yielded;if(cr 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(!A(i,dr))return qr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=qr(e)}}finally{this._running=n,globalThis[In]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Qs;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&$s-1))return Hr(e);let t=this.getCont(fr);return t?t[fr](e,this):this.yieldWith(Hr(e))}yieldWith(e){return this._yielded=e,hr}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return bt(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Vee(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Zs(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 Zs=e=>{let t=la(e,ns);return{scheduler:da(e,Do),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:da(e,cs),span:la(e,Yo),logLevel:da(e,ps),minimumLogLevel:da(e,ms),stackFrame:da(e,ss),runtimeMetrics:la(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:da(e,Po),preventYield:da(e,Fo)}},Qs={[fr](e,t){return uc(t._interruptedCause)},[pr](e,t){return uc(t._interruptedCause)}},$s=32,ec={interruptChildren:void 0},tc=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(Wr.key,e.cache.stackFrame),Qi(t)},nc=e=>{if(e._children!==void 0&&e._children.size!==0)return cc(e._children)},rc=e=>{let t=e;return t._exit?lc(t._exit):kc(n=>t._exit?n(lc(t._exit)):fc(e.addObserver(e=>n(lc(e)))))},ic=e=>kc(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();continue}i=e.value.addObserver(e=>{r.push(e),a()});return}t(lc(r))}return a(),fc(()=>i?.())}),ac=e=>{let t=e;return t._exit?t._exit:kc(n=>t._exit?n(t._exit):fc(e.addObserver(n)))},oc=e=>Jr(t=>sc(e,t.id)),sc=/*#__PURE__*/ O(e=>A(e[0],Ws),(e,t,n)=>Jr(r=>{let i=tc(r);return i=i&&n?ga(i,n):i??n,e.interruptUnsafe(t,i),Jc(rc(e))})),cc=e=>Jr(t=>{let n=tc(t),r=Ka();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Jc(ic(r))}),lc=Hr,uc=Gr,dc=Kr,fc=/*#__PURE__*/ Br({op:`Sync`,[dr](e){let t=this[ur](),n=e.getCont(fr);return n?n[fr](t,e):e.yieldWith(Hr(t))}}),pc=/*#__PURE__*/ Br({op:`Suspend`,[dr](e){return this[ur]()}}),mc=/*#__PURE__*/ O(e=>e.length>=2||Ai(e[0]),(e,t)=>ji(e)?dc(t?t():new ei(`Effect.fromOption: Option.none`)):lc(e.value)),hc=/*#__PURE__*/ Aa({onFailure:dc,onSuccess:lc}),gc=/*#__PURE__*/ (/* @__PURE__ */ Br({op:`Yield`,[dr](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(nl)},this[ur]??0),e.yieldWith(()=>{t=!0})}}))(0),_c=e=>lc(ki(e)),vc=/*#__PURE__*/ lc(/*#__PURE__*/ Oi()),yc=e=>pc(()=>uc(e())),bc=e=>qr(e),xc=e=>pc(()=>dc(e())),Sc=/*#__PURE__*/ lc(void 0),Cc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new ad(e,`An error occurred in Effect.try`):e.catch;return pc(()=>{try{return lc(t())}catch(e){return dc(n(e))}})},wc=e=>Dc(function(t,n){e(n).then(e=>t(lc(e)),e=>t(bc(e)))},e.length!==0),Tc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new ad(e,`An error occurred in Effect.tryPromise`):e.catch;return Dc(function(e,r){let i=e=>pc(()=>{try{return dc(ir(()=>n(e)))}catch(e){return bc(e)}});try{t(r).then(t=>e(lc(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},Ec=e=>Jr(t=>e(t.id)),Dc=/*#__PURE__*/ function(){let e=/*#__PURE__*/ zr({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(Oc(()=>(t=!0,r?.abort(),i??nl))),hr):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Oc=/*#__PURE__*/ Br({op:`AsyncFinalizer`,[mr](e){e.interruptible&&(e.interruptible=!1,e._stack.push(nu))},[pr](e,t){return Es(e)?Xc(kl(Gr(e),this[ur]()),()=>uc(e)):uc(e)}}),kc=e=>Dc(e,e.length>=2),Ac=/*#__PURE__*/ kc(Dt),jc=(...e)=>{if(e.length===1){let t=e[0];return pc(()=>Lc(t()))}let[t,n]=e;return pc(()=>Lc(n.call(t.self)))},Mc=(e,...t)=>{let n=t.length===0?function(){return pc(()=>Lc(e.apply(this,arguments)))}:function(){let n=pc(()=>Lc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Nc(e.length,n)},Nc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Pc=/*#__PURE__*/ _s(2),fte=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=tr(),i;return r!==0&&(nr(2),i=new globalThis.Error,nr(r)),e?(r,...a)=>Fc(t,r,i,a,e,n):Fc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Fc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Pc(()=>n.stack):Et;return Nc(o.length,function(...t){let n=pc(()=>{let e=o.apply(this,arguments);return _r(e)?e:Lc(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!_r(n))return n;let l=tr(),u;return l!==0&&(nr(2),u=new globalThis.Error,nr(l)),al(i?Ru(e,a,e=>zu(n,e)):n,ss,t=>({name:e,stack:u?Pc(()=>u.stack):Et,parent:{name:s,stack:c,parent:t}}))})},pte=(e,...t)=>Nc(e.length,t.length===0?function(){return Ic(()=>e.apply(this,arguments))}:function(){let n=Ic(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),Ic=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return lc(r.value);let i=r.value;if(i&&i._tag===`Success`){n=i.value;continue}if(i&&i._tag===`Failure`)return r.value;{let n=!0;return pc(()=>n?(n=!1,Xc(r.value,e=>Lc(t,e))):pc(()=>Lc(e())))}}}catch(e){return bc(e)}},Lc=/*#__PURE__*/ function(){let e=/*#__PURE__*/ zr({op:`Iterator`,[fr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return lc(r.value);if(!Zc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[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)}}(),Rc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,Vc,lc(t))),zc=function(e){return e._stack.push(this),this[ur]},mte=/*#__PURE__*/ zr({op:`OnSuccess`,[dr]:zc}),Bc=function(e,t,n){this[ur]=e,this[fr]=t,this.payload=n};Bc.prototype=mte;const Vc=function(){return this.payload},Hc=function(e,t){return t.succeedWith(this.payload)},Uc=/*#__PURE__*/ (()=>{let e=`~effect/Effect/stackProbe`;return{[e]:function(){return(/* @__PURE__ */ Error()).stack}}[e]()?.includes(`[as `+e+`]`)===!0})(),hte=function(e,t){let n=this.payload;return t.succeedWith(Uc?n(e):ir(()=>n(e)))},Wc=function(e){let t=this.payload;return t(e)},gte=function(e){let t=this.payload;return new Bc(t(e),Hc,e)},_te=function(e){return new Bc(this.payload,Hc,e)},Gc=e=>Qc(e,ki),Kc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,_r(t)?Vc:Wc,t)),qc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,_r(t)?_te:gte,t)),Jc=e=>new Bc(e,Vc,nl),vte=(e,t)=>Jr(n=>{let r=/* @__PURE__ */ new Set;return Gl(n,()=>r.size===0?void 0:cc(r)),kc(i=>{let a=Va(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(uc(Dr(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=hu(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),yte=(e,t)=>Jr(n=>{let r=/* @__PURE__ */ new Set;return Gl(n,()=>r.size===0?void 0:cc(r)),kc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=hu(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})})}})}),bte=/*#__PURE__*/ O(e=>_r(e[1]),(e,t,n)=>vte([e,t],n)),Yc=/*#__PURE__*/ O(e=>_r(e[1]),(e,t,n)=>yte([e,t],n)),Xc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,Wc,t)),xte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):_l(e,t)),Zc=e=>e[cr]!==void 0,Ste=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e._tag===`Success`?t(e.value):e:Xc(e,t)),Cte=e=>Xc(e,k),Qc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,hte,t)),wte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?Ate(e,t):Qc(e,t)),Tte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?jte(e,t):hl(e,t)),Ete=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?Mte(e,t):Xte(e,t)),Dte=/*#__PURE__*/ O(2,(e,t)=>{if(Zc(e)){if(e._tag===`Success`)return e;let n=Cs(e.cause);return Ea(n)?e:t(n.success)}return pl(e,t)}),$c=e=>Gr(xs(e)),el=e=>e._tag===`Success`,Ote=e=>e._tag===`Failure`,kte=e=>e._tag===`Failure`?Sa(e.cause):Ca(e),tl=e=>e._tag===`Failure`&&Es(e.cause),nl=/*#__PURE__*/ Hr(void 0),Ate=/*#__PURE__*/ O(2,(e,t)=>e._tag===`Success`?Hr(t(e.value)):e),jte=/*#__PURE__*/ O(2,(e,t)=>{if(e._tag===`Success`)return e;let n=Cs(e.cause);return Ea(n)?e:Kr(t(n.success))}),Mte=/*#__PURE__*/ O(2,(e,t)=>{if(e._tag===`Success`)return Hr(t.onSuccess(e.value));let n=Cs(e.cause);return Ea(n)?e:Kr(t.onFailure(n.success))}),Nte=/*#__PURE__*/ O(2,(e,t)=>el(e)?t:e),rl=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?nl:Gr(Dr(t))},Pte=e=>e,Fte=e=>Jr(t=>lc(ha(t.context,e))),il=/*#__PURE__*/ O(2,(e,t)=>Jr(n=>{let r=n.context,i=t(r);return r===i?e:(n.setContext(i),Gl(n,()=>{n.setContext(r)}),e)})),al=/*#__PURE__*/ O(3,(e,t,n)=>il(e,e=>{let r=ua(e,t),i=n(r);return r===i?e:aa(e,t,i)})),Ite=()=>Lte,Lte=/*#__PURE__*/ Jr(e=>lc(e.context)),ol=e=>Jr(t=>e(t.context)),Rte=/*#__PURE__*/ O(2,(e,t)=>il(e,Ct(t))),sl=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e:il(e,ga(t))),cl=function(){return arguments.length===1?O(2,(e,t)=>ll(e,arguments[0],t)):O(3,(e,t,n)=>ll(e,t,n)).apply(this,arguments)},ll=(e,t,n)=>il(e,aa(t,n)),zte=/*#__PURE__*/ O(2,(e,t)=>Xc(t,t=>t?Gc(e):vc)),Bte=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>lu({while:wt,body:Ct(t?.disableYield?e:Xc(e,e=>gc)),step:Dt})),ul=/*#__PURE__*/ O(2,(e,t)=>new dl(e,t.length===1?t:e=>t(e))),Vte=/*#__PURE__*/ zr({op:`OnFailure`,[dr]:zc}),dl=function(e,t){this[ur]=e,this[pr]=t};dl.prototype=Vte;const Hte=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>t(e)?n(e):uc(e))),fl=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>{let r=t(e);return Ea(r)?uc(r.failure):n(r.success,e)})),pl=/*#__PURE__*/ O(2,(e,t)=>fl(e,Cs,e=>t(e))),Ute=/*#__PURE__*/ O(2,(e,t)=>fl(e,Ts,t)),Wte=/*#__PURE__*/ O(2,(e,t)=>ul(e,e=>Kc(t(e),uc(e)))),Gte=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>{let r=t(e);return Ea(r)?uc(e):Kc(n(r.success,e),uc(e))})),Kte=/*#__PURE__*/ O(2,(e,t)=>Gte(e,Cs,e=>t(e))),ml=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n,r)=>ul(e,e=>{let i=Cs(e);return Ea(i)?uc(i.failure):t(i.success)?n(i.success):r?r(i.success):uc(e)})),qte=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n,r)=>ul(e,e=>{let i=Cs(e);if(Ea(i))return uc(i.failure);let a=t(i.success);return Ea(a)?r?r(a.failure):uc(e):n(a.success)})),Jte=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>A(e,`_tag`)&&t.includes(e._tag):Zt(t);return ml(e,i,n,r)}),Yte=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n)=>{let r;return qte(e,e=>(r??=Object.keys(t),A(e,`_tag`)&&It(e._tag)&&r.includes(e._tag)?Sa(e):Ca(e)),e=>t[e._tag](e),n)}),hl=/*#__PURE__*/ O(2,(e,t)=>pl(e,e=>xc(()=>t(e)))),Xte=/*#__PURE__*/ O(2,(e,t)=>yl(e,{onFailure:e=>xc(()=>t.onFailure(e)),onSuccess:e=>fc(()=>t.onSuccess(e))})),Zte=e=>pl(e,bc),Qte=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>{if(!t?.log)return yl(e,{onFailure:e=>Sc,onSuccess:e=>Sc});let n=ld(t.log===!0?void 0:t.log);return _l(e,{onFailure(e){let r=Ss(e);return Ea(r)?uc(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Sc})}),$te=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>{if(!t?.log)return _l(e,{onFailure:e=>Sc,onSuccess:e=>Sc});let n=ld(t.log===!0?void 0:t.log);return _l(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>Sc})}),ene=e=>bl(e,{onFailure:Oi,onSuccess:ki}),gl=e=>ine(e,{onFailure:Ca,onSuccess:Sa}),_l=/*#__PURE__*/ O(2,(e,t)=>new vl(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),tne=/*#__PURE__*/ zr({op:`OnSuccessAndFailure`,[dr]:zc}),vl=function(e,t,n){this[ur]=e,this[fr]=t,this[pr]=n};vl.prototype=tne;const nne=function(e,t){let n=this.payload;return t.succeedWith(Uc?n.onSuccess(e):ir(()=>n.onSuccess(e)))},rne=/*#__PURE__*/ ((e,t)=>{let n=zr({op:e,[dr]:zc,[fr]:nne,[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(Fr);if(n===void 0)return uc(e);let r=this.payload;return t.succeedWith(Uc?r.onFailure(n.error):ir(()=>r.onFailure(n.error)))}),yl=/*#__PURE__*/ O(2,(e,t)=>_l(e,{onFailure:e=>{let n=e.reasons.find(Fr);return n?t.onFailure(n.error):uc(e)},onSuccess:t.onSuccess})),bl=/*#__PURE__*/ O(2,(e,t)=>new rne(e,t)),ine=/*#__PURE__*/ O(2,(e,t)=>{if(Zc(e)){if(e._tag===`Success`)return Hr(t.onSuccess(e.value));let n=Cs(e.cause);return Ea(n)?e:Hr(t.onFailure(n.success))}return bl(e,t)}),xl=e=>Zc(e)?Hr(e):ane(e),ane=/*#__PURE__*/ Br({op:`Exit`,[dr](e){return e._stack.push(this),this[ur]},[fr](e,t,n){return t.succeedWith(n??Hr(e))},[pr](e,t,n){return t.succeedWith(n??Gr(e))}}),one=/*#__PURE__*/ O(2,(e,t)=>Kc(Xu(t),e)),Sl=/*#__PURE__*/ O(2,(e,t)=>Xc(lne(e,t.duration),e=>ji(e)?t.orElse():lc(e.value))),sne=e=>new $u(`Operation timed out after '${Eo(e)}'`),cne=/*#__PURE__*/ O(2,(e,t)=>{let n=ao(t);return Sl(e,{duration:n,orElse:()=>dc(sne(n))})}),lne=/*#__PURE__*/ O(2,(e,t)=>Yc(Gc(e),Rc(Xu(t),Oi()))),Cl=`~effect/Scope`,wl=`~effect/Scope/Closeable`,Tl=/*#__PURE__*/ j(`effect/Scope`),El=(e,t)=>Jr(n=>(au(n),Dl(e,t)??Sc)),Dl=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&Nl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Ol(n.finalizer,t);let r=n.finalizers;return r.size===1?Ol(r.values().next().value,t):une(e,r,t)},Ol=(e,t)=>{try{return e(t)}catch(e){return qr(e)}},kl=(e,t)=>el(e)?t:ul(t,t=>uc(kr(e.cause,t))),une=/*#__PURE__*/ Mc(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Ys();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*xl(Ol(s,n))):i.push(hu(o,Ol(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*ic(i)),yield*rl(r)}),dne=(e,t)=>fc(()=>Al(e,t)),Al=(e,t)=>{let n=Fl(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Ml(e,n,e=>El(n,e)),n)},jl=(e,t)=>pc(()=>e.state._tag===`Closed`?t(e.state.exit):(Ml(e,{},t),Sc)),fne=(e,t)=>jl(e,Ct(t)),Ml=(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.set(t,n):(r.finalizers=/* @__PURE__ */ new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0,r.finalizers.set(t,n))}},Nl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=Il:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=Il))},Pl=e=>Fl(e,void 0),Fl=(e=`sequential`,t)=>({[wl]:wl,[Cl]:Cl,strategy:e,parent:t,state:Il}),Il={_tag:`Empty`},pne=e=>fc(()=>Pl(e)),Ll=Tl,Rl=/*#__PURE__*/ cl(Tl),zl=e=>Jr(t=>{let n=t.context,r=Pl();return t.setContext(aa(t.context,Tl,r)),Gl(t,e=>(t.setContext(n),Dl(r,e))),e}),Bl=/*#__PURE__*/ O(2,(e,t)=>Kl(Rl(e,t),e=>pc(()=>Dl(t,e)??Sc))),Vl=e=>pc(()=>{let t=Pl();return Kl(e(t),e=>pc(()=>Dl(t,e)??Sc))}),mne=(e,t,n)=>ol(r=>cu(i=>Xc(Ll,a=>qc(n?.interruptible?i(e):e,e=>jl(a,n=>sl(t(e,n),r)))))),Hl=e=>Xc(Ll,t=>ol(n=>jl(t,t=>sl(e(t),n)))),Ul=/*#__PURE__*/ function(){let e=/*#__PURE__*/ zr({op:`OnExit`,[dr](e){return e._stack.push(this),this.effect},[mr](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(nu),e.interruptible=!1)},[fr](e,t,n){n??=Hr(e);let r;try{r=this.onExit(n)}catch(e){r=qr(e)}return r?Xc(r,e=>n):n},[pr](e,t,n){n??=Gr(e);let r;try{r=this.onExit(n)}catch(e){r=qr(e)}return r?Xc(kl(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),Wl=(e,t,n)=>new Ul(e,t,n),Gl=(e,t)=>{e._stack.push(new Ul(void 0,t,void 0))},Kl=/*#__PURE__*/ O(2,Wl),ql=/*#__PURE__*/ O(2,(e,t)=>Kl(e,e=>t)),Jl=/*#__PURE__*/ O(3,(e,t,n)=>Kl(e,e=>{let r=t(e);return Ea(r)?Sc:n(r.success,e)})),Yl=/*#__PURE__*/ O(2,(e,t)=>Jl(e,kte,t)),hne=/*#__PURE__*/ O(3,(e,t,n)=>Kl(e,e=>{if(e._tag!==`Failure`)return Sc;let r=t(e.cause);return Ea(r)?Sc:n(r.success,e.cause)})),gne=/*#__PURE__*/ O(2,(e,t)=>hne(Ds,t)(e)),_ne=/*#__PURE__*/ O(2,(e,t)=>fc(()=>Xl(e,typeof t==`function`?e=>bo(ao(t(e))):Ct(bo(ao(t)))))),vne=/*#__PURE__*/ Ct(1/0),Xl=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Gl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,oc(t.fiber)}),ac(t.fiber));return[Jr(o=>{if(i!==void 0)return a(o,i);if(r!==void 0&&(n===1/0||o.getRef(Uu).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(Uu),c={fiber:void 0,awaiters:0};return i=c,c.fiber=hu(o,Wl(e,e=>{if(i!==c||(i=void 0,tl(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e}),!0,!0),c.fiber._exit??a(o,c)}),fc(()=>{r=void 0})]},Zl=/*#__PURE__*/ O(2,(e,t)=>Qc(_ne(e,t),e=>e[0])),Ql=e=>fc(()=>Xl(e,vne)[0]),$l=/*#__PURE__*/ Jr(e=>uc(xs(e.id))),eu=e=>Jr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(nu),e):e),tu=/*#__PURE__*/ Br({op:`SetInterruptible`,[mr](e){if(e.interruptible=this[ur],e._interruptedCause&&e.interruptible)return()=>uc(e._interruptedCause)}}),nu=/*#__PURE__*/ tu(!0),ru=/*#__PURE__*/ tu(!1),iu=e=>{if(e.interruptible=!0,e._stack.push(ru),e._interruptedCause)return uc(e._interruptedCause)},au=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(nu))},ou=e=>{let t=e;if(!t.interruptible)return iu(t)},su=e=>Jr(t=>t.interruptible?e:iu(t)??e),cu=e=>Jr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(nu),e(su)):e(k)),yne=(e,t)=>$t(e)?t?.mode===`result`?uu(e,gl,t):uu(e,k,t):t?.discard?t.mode===`result`?uu(Object.values(e),gl,t):uu(Object.values(e),k,t):pc(()=>{let n={};return Rc(uu(Object.entries(e),([e,r])=>Qc(t?.mode===`result`?gl(r):r,t=>{ar(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),lu=/*#__PURE__*/ Br({op:`While`,[fr](e,t){return this[ur].step(e),this[ur].while()?(t._stack.push(this),this[ur].body()):nl},[dr](e){return this[ur].while()?(e._stack.push(this),this[ur].body()):nl}}),uu=/*#__PURE__*/ O(e=>typeof e[1]==`function`,(e,t,n)=>pc(()=>{let r=du(n?.concurrency);if(r===1)return bne(e,t,n);let i=Va(e),a=i.length;if(a===0)return n?.discard?Sc:lc([]);let o=n?.discard?void 0:Array(a),s=xne({f:t,out:o},i,{concurrency:r});return s?Rc(s,o):lc(o)})),bne=(e,t,n)=>pc(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return Rc(lu({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),du=e=>e===`unbounded`?1/0:Math.max(1,e??1),fu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Xc(xl(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Sc),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!Zc(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},pu=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=qr(e);return f=t,c=!0,u&&u.size>0?Xc(eu(cc(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(Zc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=hu(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=Dr(e);f=Gr(f._tag===`Failure`?kr(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??Sc)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return kc(e=>{l=Ys(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):pc(()=>(f??=nl,Xc(u?cc(u):Sc,()=>f?._tag===`Failure`?f:Sc)))})}if(c=!0,f){if(u&&u.size>0){let e=tc(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(Sc);else return nl}};return h()}},mu=()=>e=>pu(e),xne=/*#__PURE__*/ pu({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)}}),Sne=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>Jr(n=>(Ine(),lc(hu(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),hu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Xs(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Js(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},gu=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n)=>Jr(r=>{let i=hu(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};Ml(t,e,()=>Ec(e=>e===i.id?Sc:oc(i))),i.addObserver(()=>Nl(t,e))}else i.interruptUnsafe(r.id,tc(r))}return lc(i)})),Cne=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>Xc(Ll,n=>gu(e,n,t))),_u=e=>(t,n)=>{let r=new Xs(n?.scheduler?aa(e,Do,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},wne=/*#__PURE__*/ O(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(Nl(t,e),Ml(t,e,()=>oc(e)),e.addObserver(()=>Nl(t,e)),e)),vu=/*#__PURE__*/ _u(/*#__PURE__*/ na()),yu=e=>{let t=_u(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},bu=e=>{let t=yu(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw Ms(e.cause);return e.value})},xu=/*#__PURE__*/ bu(/*#__PURE__*/ na()),Su=e=>{let t=_u(e);return e=>{if(Zc(e))return e;let n=new Mo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??qr(new Ene(r))}},Cu=/*#__PURE__*/ Su(/*#__PURE__*/ na()),wu=/*#__PURE__*/ (e=>{let t=Su(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw Ms(n.cause);return n.value}})(/*#__PURE__*/ na()),Tu=/*#__PURE__*/ lc(!0),Eu=/*#__PURE__*/ lc(!1);var Du=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Tu;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=[],Tu}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](nl)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](nl)}open=/*#__PURE__*/ Jr(e=>this._isOpen?Eu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ Jr(e=>this._isOpen?Eu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ kc(e=>this._isOpen?e(Sc):(this.waiters.push(e),fc(()=>{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__*/ fc(()=>this.closeUnsafe());whenOpen=e=>Xc(this.await,()=>e);isOpen(){return this._isOpen}};const Ou=e=>new Du(e??!1),ku=e=>fc(()=>Ou(e)),Au=/*#__PURE__*/ BigInt(0),ju={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:Au,endTime:Au,exit:nl},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},Mu=e=>Object.assign(Object.create(ju),e),Nu=e=>e?da(e.annotations,$o)?e._tag===`Span`?Nu(Li(e.parent)):Oi():ki(e):Oi(),Pu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&da(n.annotations,$o),i=n?.parent===void 0?n?.root?Oi():Nu(e.cache.span):ki(n.parent),a;if(r)a=Mu({name:t,parent:i,annotations:aa(n?.annotations??na(),$o,!0)});else{let r=e.cache.tracer??is,o=e.getRef(Uu),s=e.getRef(ls),c=e.getRef(us),l=e.getRef(ds),u=n?.level??e.getRef(es),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??na(),links:d,startTime:s?o.currentTimeNanosUnsafe():Au,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(Mi(i)&&i.value.sampled===!1?!1:!sd(e.getRef(ts),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},Fu=(e,t)=>eu(Jr(n=>{let r=ua(n.context,Tl),i=Pu(n,e,t??{}),a=n.getRef(Uu),o=n.getRef(ls);return Rc(jl(r,e=>Lu(i,e,a,o)),i)})),Iu=(e,t)=>(t=typeof t==`function`?t:Et,al(ss,n=>({name:e,stack:t,parent:n}))),Lu=(e,t,n,r)=>fc(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():Au,t)}),Ru=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return Jr(t=>{let i=Pu(t,e,n),a=t.getRef(Uu),o=t.getRef(ls);return Gl(t,e=>Lu(i,e,a,o)),r(i)})},zu=/*#__PURE__*/ cl(Xo),Bu=function(){let e=_r(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=k;return t._tag===`Span`&&(n=gs(n),r=Iu(t.name,n?.captureStackTrace)),e?zu(r(arguments[0]),t):e=>zu(r(e),t)},Vu=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=gs(arguments[2]);if(e){let e=arguments[0];return Ru(t,arguments[2],t=>Bu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Ru(t,r?r(...a):i,t=>Bu(e,t,n))},Hu=(...e)=>Jr(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 Sc}),Uu=/*#__PURE__*/ ya(`effect/Clock`,{defaultValue:()=>new Gu}),Wu=2**31-1;var Gu=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ fc(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Ju()}currentTimeNanos=/*#__PURE__*/ fc(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return qu()}monotonicTimeNanos=/*#__PURE__*/ fc(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(bo(e))}sleepMillis(e){return e<=0?gc:Number.isFinite(e)?kc(t=>{let n=e>Wu?this.sleepMillis(e-Wu):Sc,r=setTimeout(()=>t(n),Math.min(e,Wu));return fc(()=>clearTimeout(r))}):Ac}};const Ku=/*#__PURE__*/ BigInt(1e6),qu=/*#__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())*Ku;return e>t&&(t=e),t}}(),Ju=/*#__PURE__*/ function(){let e=/*#__PURE__*/ BigInt(1e9),t;return()=>{let n=qu(),r=BigInt(Date.now())*Ku;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}}(),Yu=e=>Jr(t=>e(t.getRef(Uu))),Xu=e=>Yu(t=>t.sleep(ao(e))),Zu=/*#__PURE__*/ Yu(e=>e.currentTimeMillis),Qu=`~effect/Cause/TimeoutError`;var $u=class extends (/*#__PURE__*/ Zr(`TimeoutError`)){[Qu]=Qu;constructor(e){super({message:e})}};const ed=`~effect/Cause/IllegalArgumentError`;var td=class extends (/*#__PURE__*/ Zr(`IllegalArgumentError`)){[ed]=ed;constructor(e){super({message:e})}};const nd=`~effect/Cause/ExceededCapacityError`;var Tne=class extends (/*#__PURE__*/ Zr(`ExceededCapacityError`)){[nd]=nd;constructor(e){super({message:e})}};const rd=`~effect/Cause/AsyncFiberError`;var Ene=class extends (/*#__PURE__*/ Zr(`AsyncFiberError`)){[rd]=rd;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const id=`~effect/Cause/UnknownError`;var ad=class extends (/*#__PURE__*/ Zr(`UnknownError`)){[id]=id;constructor(e,t){super({message:t,cause:e})}};const Dne=/*#__PURE__*/ ya(`effect/Console`,{defaultValue:()=>globalThis.console}),od=/*#__PURE__*/ Fee(Ti,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}}),sd=/*#__PURE__*/ Ei(od),One=/*#__PURE__*/ ya(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([Pne,Fne])}),kne=/*#__PURE__*/ ya(`effect/Logger/LogToStderr`,{defaultValue:Tt}),Ane={"~effect/Logger":{_Message:k,_Output:k},pipe(){return bt(this,arguments)}},cd=e=>{let t=Object.create(Ane);return t.log=e,t},jne=e=>e.replace(/[\s="]/g,`_`),Mne=(e,t)=>`${jne(e[0])}=${t-e[1]}ms`,ld=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];xr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Dr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Ar),Jr(r=>{let i=e??r.cache.logLevel;if(sd(r.cache.minimumLogLevel,i))return Sc;let a=r.getRef(Uu),o=r.getRef(One);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 Sc})},ud={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};ud.gray,ud.blue,ud.green,ud.yellow,ud.red,ud.bgBrightRed,ud.black;const Nne=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`)}`,Pne=/*#__PURE__*/ cd(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Vs(e));let o=t.getTime(),s=n.getRef(hs),c=``;for(let e of s)c+=` ${Mne(e,o)}`;let l=n.getRef(fs);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Dne);(n.getRef(kne)?u.error:u.log)(`[${Nne(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Fne=/*#__PURE__*/ cd(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Uu),a=t.getRef(fs),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))ar(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Vs(e)),o.event(Zn(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function Ine(){ec.interruptChildren??=nc}const Lne=/*#__PURE__*/ O(e=>_r(e[0]),(e,t)=>Yl(e,e=>Jr(n=>(dd(n,e,t?.defectsOnly),Sc)))),dd=(e,t,n)=>{let r=e.getRef(os);if(r.size===0||n&&!ws(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(Uu).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},Rne=xr,zne=See,fd=Fr,pd=Ir,md=Dr,hd=jr,gd=Nr,_d=e=>new Er(e),vd=e=>new Mr(e),yd=bs,bd=js,xd=kr,Sd=Ms,Cd=Ss,wd=Cs,Td=ws,Ed=Es,Dd=Os,Od=Vs,kd=$r,Ad=ni,jd=ii,Md=oi,Nd=td,Pd=Tne,Fd=ad,Id=Pr,Ld=As;var Rd=class extends (/*#__PURE__*/ j()(`effect/Cause/StackTrace`)){};const zd=vr,Bd=Hr,Vd=Gr,Hd=Kr,Ud=qr,Wd=$c,Gd=nl,Kd=el,qd=Ote,Jd=tl,Yd=rl,Xd=`~effect/Deferred`,Zd=e=>A(e,Xd),Qd={[Xd]:{_A:k,_E:k},pipe(){return bt(this,arguments)}},$d=function(){this.resumes=void 0,this.effect=void 0};$d.prototype=Qd;const ef=()=>new $d,tf=()=>fc(()=>ef()),nf=e=>kc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),fc(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),rf=/* @__PURE__ */ O(2,(e,t)=>fc(()=>uf(e,t))),af=/*#__PURE__*/ O(2,(e,t)=>rf(e,Gr(t))),of=/*#__PURE__*/ O(2,(e,t)=>af(e,xs(t))),sf=e=>fc(()=>cf(e)),cf=e=>e.effect!==void 0,lf=/*#__PURE__*/ O(2,(e,t)=>rf(e,Hr(t))),uf=(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},df=fs,ff=ps,pf=ls,mf=Tl,hf=pne,gf=Pl,_f=Rl,vf=jl,yf=fne,bf=dne,xf=Al,Sf=El,Cf=Dl,wf=Bl,Tf=`~effect/Layer/MemoMap`,Ef=(e,t)=>{let n={observers:0,deferred:ef(),scope:gf(),finalizer:r=>pc(()=>--n.observers>0?Sc:(e.map.delete(t),Sf(n.scope,r)))};return n},Df=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Ml(t,{},e.finalizer),!0),Of={"~effect/Layer":{_ROut:k,_E:k,_RIn:k},pipe(){return bt(this,arguments)}},kf=e=>{let t=Object.create(Of);return t.build=e,t},Af=e=>kf((t,n)=>{let r=xf(n);return Kl(e(t,r),e=>e._tag===`Failure`?Sf(r,e):Sc)}),jf=e=>{let t=Af((n,r)=>n.getOrElseMemoize(t,r,e));return t};var Mf=class{get[Tf](){return Tf}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(Df(n,t),n.deferred.effect??nf(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return pc(()=>{let r;return Wl(pc(()=>{let i=this.get(e,t);if(i)return i;let a=Ef(this,e);return Df(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&uf(r,e)})})}};const Nf=()=>new Mf,Pf=e=>new Mf(e);var Ff=class e extends (/*#__PURE__*/ j()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=ca(t,e);return n?Pf(n):Nf()}};const If=/*#__PURE__*/ O(3,(e,t,n)=>cl(Qc(pc(()=>e.build(t,n)),aa(Ff,t)),Ff,t)),Lf=e=>Jr(t=>If(e,Ff.forkOrCreate(t.context),ua(t.context,mf))),Rf=/*#__PURE__*/ O(2,(e,t)=>Jr(n=>If(e,Ff.forkOrCreate(n.context),t))),zf=function(){return arguments.length===1?e=>Bf(ia(arguments[0],e)):Bf(ia(arguments[0],arguments[1]))},Bf=e=>kf(Ct(lc(e))),Vf=/*#__PURE__*/ Bf(/*#__PURE__*/ na()),Hf=function(){return arguments.length===1?e=>Uf(arguments[0],e):Uf(arguments[0],arguments[1])},Uf=(e,t)=>Wf(Qc(t,t=>ia(e,t))),Wf=e=>jf((t,n)=>_f(e,n)),Gf=e=>Wf(Rc(e,na())),Kf=/*#__PURE__*/ j(`effect/Layer/unwrap`),qf=e=>Vne(Hf(Kf)(e),da(Kf)),Jf=(e,t,n)=>{let r=xf(n,`parallel`);return uu(e,e=>e.build(t,xf(r,`sequential`)),{concurrency:e.length}).pipe(Qc(e=>_a(...e)))},Yf=(...e)=>Af((t,n)=>Jf(e,t,n)),Bne=/*#__PURE__*/ O(2,(e,t)=>Yf(e,...Array.isArray(t)?t:[t])),Xf=(e,t,n)=>Af((r,i)=>Xc(Array.isArray(t)?Jf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(sl(t),Qc(e=>n(e,t))))),Zf=/*#__PURE__*/ O(2,(e,t)=>Xf(e,t,k)),Qf=/*#__PURE__*/ O(2,(e,t)=>Xf(e,t,(e,t)=>ga(t,e))),Vne=/*#__PURE__*/ O(2,(e,t)=>Af((n,r)=>Xc(e.build(n,r),e=>t(e).build(n,r)))),Hne=e=>kf((t,n)=>e.build(Nf(),n)),$f=Uu,ep=Zu,tp=`~effect/DateTime`,np=`~effect/DateTime/TimeZone`,rp={[tp]:tp,pipe(){return bt(this,arguments)},[Yn](){return this.toString()},toJSON(){return lp(this).toJSON()}},Une={...rp,_tag:`Utc`,[en](){return cn(this.epochMilliseconds)},[yn](e){return ap(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${lp(this).toJSON()})`}};({...rp});const ip={[np]:np,[Yn](){return this.toString()}};({...ip}),{...ip};const ap=e=>A(e,tp),Wne=e=>e._tag===`Utc`,op=e=>{let t=Object.create(Une);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},sp=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Nd(`Invalid date`);return op(t)},cp=e=>{if(ap(e))return e;if(e instanceof Date)return sp(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return sp(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return Yne(t,e),sp(t)}return typeof e==`string`&&!Gne(e)?sp(/* @__PURE__ */ new Date(e+`Z`)):sp(new Date(e))},Gne=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Kne=/*#__PURE__*/ Ri(cp),qne=e=>op(e.epochMilliseconds),lp=e=>new Date(e.epochMilliseconds),Jne=e=>e.epochMilliseconds,Yne=(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)},Xne=e=>lp(e).toISOString();globalThis.String;const Zne=e=>e.trim(),Qne=(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)},up=/*#__PURE__*/ O(2,(e,t)=>fl(e,$ne,e=>t(e))),dp=e=>e.reasons.some(fp),fp=e=>e._tag===`Fail`&&Ad(e.error),pp=e=>{let t,n=!1;for(let r of e.reasons)fp(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Ca(e):n?Ca(md(e.reasons.filter(e=>!fp(e)))):Sa(t)},$ne=e=>{let t=pp(e);return Ea(t)?t:Sa(t.success.value)},mp=e=>{let t=pp(e);return Ea(t)?Vd(t.failure):Bd(t.success.value)},ere=/*#__PURE__*/ O(2,(e,t)=>_l(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=pp(e);return Ea(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),tre=(e,t,n)=>Vl(r=>Xc(n?.local?If(t,Nf(),r):Rf(t,r),t=>sl(e,t))),nre=/*#__PURE__*/ O(e=>_r(e[0]),(e,t,n)=>$i(t)?sl(e,t):tre(e,Array.isArray(t)?Yf(...t):t,n)),hp=_r,gp=yne,_p=uu,vp=lu,yp=wc,bp=Tc,N=lc,xp=vc,rre=_c,Sp=pc,P=fc,F=Sc,Cp=kc,wp=Ac,I=jc,L=dc,Tp=uc,Ep=yc,Dp=bc,Op=Cc,ire=gc,kp=Jr,Ap=hc,are=mc,R=Xc,ore=Cte,jp=Kc,Mp=qc,Np=gl,sre=ene,Pp=xl,z=Qc,Fp=Rc,Ip=Jc,Lp=pl,Rp=Jte,cre=Yte,zp=ul,Bp=Ute,Vp=ml,lre=Hte,Hp=hl,Up=Zte,Wp=Kte,Gp=Wte,Kp=Qte,qp=$te,ure=Lne,dre=cne,Jp=Sl,fre=one,Yp=Xu,pre=bte,Xp=Yc,mre=zte,Zp=bl,Qp=xte,$p=_l,em=yl,tm=Ite,nm=ol,rm=nre,im=sl,am=Rte,om=Pte,sm=Fte,cm=il,lm=cl,um=Ll,dm=zl,fm=Vl,pm=mne,mm=Hl,hm=ql,gm=Yl,_m=Wl,vm=Kl,ym=Ql,bm=Zl,xm=$l,Sm=su,Cm=gne,wm=eu,Tm=cu,Em=Bte,Dm=Hu,Om=Fu,km=Ru,Am=Vu,jm=Bu,Mm=Sne,Nm=gu,Pm=Cne,Fm=vu,Im=_u,Lm=xu,Rm=bu,zm=wu,Bm=Cu,B=Mc,V=fte,Vm=Yu,Hm=/*#__PURE__*/ ld(`Fatal`),Um=/*#__PURE__*/ ld(`Warn`),Wm=/*#__PURE__*/ ld(`Error`),Gm=/*#__PURE__*/ ld(`Info`),Km=/*#__PURE__*/ ld(`Debug`),qm=/*#__PURE__*/ O(e=>hp(e[0]),(e,...t)=>al(e,df,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||ar(n,t[0],t[1]),n})),Jm=(e,t,n)=>(...r)=>Cp(i=>{try{e(...r,(e,n)=>{i(e?t?Sp(()=>L(t(e,r))):L(e):N(n))})}catch(e){i(n?L(n(e,r)):Dp(e))}}),Ym=wte,Xm=Tte,Zm=Ete,Qm=Ste,$m=Dte,eh=pte,th=`~effect/BigDecimal`,nh={[th]:th,[en](){let e=uh(this);return an(ln(String(e.value)),cn(e.scale))},[yn](e){return rh(e)&&mh(this,e)===0},toString(){return`BigDecimal(${gh(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Yn](){return this.toJSON()},pipe(){return bt(this,arguments)}},rh=e=>A(e,th),ih=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(nh);return n.value=e,n.scale=t,n},ah=(e,t)=>{let n=ih(e,t);return n.normalized=n,n},oh=/*#__PURE__*/ BigInt(0),sh=/*#__PURE__*/ BigInt(1),ch=/*#__PURE__*/ BigInt(10),lh=/*#__PURE__*/ ah(oh,0),uh=e=>{if(e.normalized===void 0){if(e.value===oh)e.normalized=lh;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=ah(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},dh=[sh],fh=(e,t)=>e===t?0:e<t?-1:1,ph=(e,t)=>{let n=`${e.value<oh?-e.value:e.value}`,r=`${t.value<oh?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==oh)return i<oh?-1:1;let a=Math.max(n.length,r.length);return Pee(n.padEnd(a,`0`),r.padEnd(a,`0`))},mh=(e,t)=>{if(e.scale===t.scale)return fh(e.value,t.value);let n=hh(e),r=hh(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?ph(t,e):ph(e,t);let o=dh[a]??=ch**BigInt(a);return i>0?fh(e.value,t.value*o):fh(e.value*o,t.value)},hh=e=>e.value===oh?0:e.value<oh?-1:1,gh=e=>{let t=uh(e);if(Math.abs(t.scale)>=16)return _h(t);let n=t.value<oh,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},_h=e=>{if(vh(e))return`0e+0`;let t=uh(e),n=`${t.value}`,r=t.value<oh?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},vh=e=>e.value===oh,yh=globalThis.BigInt,bh=e=>e>yh(2**53-1)||e<yh(-(2**53-1))?Oi():ki(Number(e)),xh=/*#__PURE__*/ BigInt(0),Sh=/*#__PURE__*/ BigInt(1),Ch=/*#__PURE__*/ BigInt(1e3),wh=/*#__PURE__*/ BigInt(1024),Th=[{symbol:`B`,factor:Sh,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Ch,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Ch**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Ch**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Ch**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Ch**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Ch**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Ch**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Ch**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Ch**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Ch**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],Eh=[Th[0],{symbol:`KiB`,factor:wh,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:wh**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:wh**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:wh**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:wh**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:wh**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:wh**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:wh**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],Dh=[...Th,.../*#__PURE__*/ Eh.slice(1)],Oh=/*#__PURE__*/ new Map(/*#__PURE__*/ Dh.flatMap(e=>e.names.map(t=>[t,e]))),kh=/*#__PURE__*/ new Map(/*#__PURE__*/ Dh.map(e=>[e.symbol,e])),Ah=e=>e,jh=/*#__PURE__*/ Ah(xh),Mh=e=>{throw Error(`Invalid ByteSize: ${e}`)},Nh=e=>!Number.isSafeInteger(e)||e<0?Mh(`expected a non-negative safe integer, received ${e}`):Ah(BigInt(e)),Ph=(e,t)=>{if(typeof e==`bigint`)return e<xh?Mh(`expected a non-negative quantity, received ${e}`):Ah(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?Mh(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):Ah(BigInt(n))},Fh=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return Mh(`unsupported syntax ${JSON.stringify(e)}`);let n=Oh.get(t[3]);if(n===void 0)return Mh(`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===xh?Ah(a/i):Mh(`${JSON.stringify(e)} does not represent an integral number of bytes`)},Ih=e=>{switch(typeof e){case`bigint`:return e<xh?Mh(`expected a non-negative bigint, received ${e}`):Ah(e);case`number`:return Nh(e);case`string`:return Fh(e)}return Mh(`unsupported input ${e}`)},Lh=/*#__PURE__*/ Ri(Ih),Rh=e=>typeof e==`bigint`?Ih(e):Nh(e),zh=/*#__PURE__*/ (e=>t=>Ph(t,kh.get(e)))(`MiB`),Bh=ap,Vh=Wne,Hh=sp,Uh=cp,Wh=Kne,Gh=qne,Kh=Jne,qh=Xne,Jh=e=>Zh(typeof e==`string`?Qh.encode(e):e),Yh=e=>{let t=eg(e),n=t.length;if(n%4!=0)return Ca(new Uo({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 Ca(new Uo({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=rg(t.charCodeAt(e))<<18|rg(t.charCodeAt(e+1))<<12|rg(t.charCodeAt(e+2))<<6|rg(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return Sa(r)}catch(e){return Ca(new Uo({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Xh=e=>ka(Yh(e),e=>$h.decode(e)),Zh=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=tg[e[r-2]>>2],n+=tg[(e[r-2]&3)<<4|e[r-1]>>4],n+=tg[(e[r-1]&15)<<2|e[r]>>6],n+=tg[e[r]&63];return r===t+1&&(n+=tg[e[r-2]>>2],n+=tg[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=tg[e[r-2]>>2],n+=tg[(e[r-2]&3)<<4|e[r-1]>>4],n+=tg[(e[r-1]&15)<<2],n+=`=`),n},Qh=/*#__PURE__*/ new TextEncoder,$h=/*#__PURE__*/ new TextDecoder,eg=e=>e.replace(/[\n\r]/g,``),tg=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,ng=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)ng[/*#__PURE__*/ tg.charCodeAt(e)]=e;ng[61]=0;const rg=e=>{if(e>=ng.length||ng[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return ng[e]},ig=`~effect/http/Cookies`,ag=e=>A(e,ig),og=`~effect/http/Cookies/Cookie`,sg=`~effect/http/Cookies/CookieError`;var cg=class extends Bo{},lg=class e extends (/*#__PURE__*/ Vo(`CookiesError`)){static fromReason(t,n){return new e({reason:new cg({_tag:t,cause:n})})}[sg]=sg;get message(){return this.reason._tag}};const ug={[ig]:ig,...Qn,toJSON(){return{_id:`effect/Cookies`,cookies:La(this.cookies,e=>e.toJSON())}},pipe(){return bt(this,arguments)}},dg=e=>{let t=Object.create(ug);return t.cookies=e,t},fg=e=>{let t={};for(let n of e)ar(t,n.name,n);return dg(t)},pg=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=mg(e.trim());t&&n.push(t)}return fg(n)};function mg(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(!vg.test(r))return;let i=t[0].slice(n+1),a=jg(i);if(t.length===1)return Object.assign(Object.create(xg),{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=vo(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(xg),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const hg=/*#__PURE__*/ fg([]),gg=e=>Fa(e.cookies),_g=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,vg=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,yg=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,bg=/^[\u0020-\u003a\u003c-\u007e]+$/,xg={[og]:og,...Qn,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function Sg(e,t,n){let r=encodeURIComponent(t),i=Cg(e,r,n);return i===void 0?Sa(Object.assign(Object.create(xg),{name:e,value:t,valueEncoded:r,options:n})):Ca(i)}function Cg(e,t,n){if(!vg.test(e))return lg.fromReason(`InvalidCookieName`);if(t&&!_g.test(t))return lg.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!yg.test(n.domain))return lg.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!bg.test(n.path))return lg.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!uo(ao(n.maxAge)))return lg.fromReason(`CookieInfinityMaxAge`)}const wg=/*#__PURE__*/ O(2,(e,t)=>dg({...e.cookies,...t.cookies})),Tg=/*#__PURE__*/ O(e=>ag(e[0]),(e,t,n,r)=>ka(Sg(t,n,r),n=>dg(Hee(e.cookies,t,n))));function Eg(e){let t=Cg(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=ute(ao(r.maxAge));n+=`; Max-Age=`+Math.trunc(e)}if(r.domain!==void 0&&(n+=`; Domain=`+r.domain),r.path!==void 0&&(n+=`; Path=`+r.path),r.priority!==void 0)switch(r.priority){case`low`:n+=`; Priority=Low`;break;case`medium`:n+=`; Priority=Medium`;break;case`high`:n+=`; Priority=High`}if(r.expires!==void 0&&(n+=`; Expires=`+r.expires.toUTCString()),r.httpOnly&&(n+=`; HttpOnly`),r.secure&&(n+=`; Secure`),r.partitioned&&(n+=`; Partitioned`),r.sameSite!==void 0)switch(r.sameSite){case`lax`:n+=`; SameSite=Lax`;break;case`strict`:n+=`; SameSite=Strict`;break;case`none`:n+=`; SameSite=None`}return n}const Dg=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),Og=e=>{let t={},n=Object.values(e.cookies);for(let e=0;e<n.length;e++){let r=n[e];ar(t,r.name,r.value)}return t},kg=e=>Object.values(e.cookies).map(Eg);function Ag(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();ar(t,o,n.indexOf(`%`)===-1?n:jg(n))}r=i+1}return t}const jg=e=>{try{return decodeURIComponent(e)}catch{return e}},Mg=/*#__PURE__*/ new WeakMap,Ng=e=>{if(Mg.has(e))return Mg.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},Pg=`~effect/Redacted`,Fg=e=>A(e,Pg),Ig=(e,t)=>{let n=Object.create(Lg);return t?.label&&(n.label=t.label),Mg.set(n,e),n},Lg={[Pg]:{_A:e=>e},label:void 0,...gr,toJSON(){return this.toString()},toString(){return`<redacted${It(this.label)?`:`+this.label:``}>`},[en](){return tn(Mg.get(this))},[yn](e){return Fg(e)&&bn(Mg.get(this),Mg.get(e))}},Rg=Ng,zg=e=>ci((t,n)=>e(Rg(t),Rg(n))),Bg=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),Vg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[Bg]:{value:Bg},[Nn]:{value(e){return Qg(this,da(e,e_))}},toJSON:{value(){return Pn(this)}},[yn]:{value(e){return Ug(this,e)}},[en]:{value(){return dn(this)}},toString:{value:Qn.toString},[Yn]:{value:Qn[Yn]}}),Hg=e=>Object.assign(Object.create(Vg),e),Ug=/*#__PURE__*/ Wee(/*#__PURE__*/ ui()),Wg=/*#__PURE__*/ Object.create(Vg),Gg=e=>{if(e===void 0)return Wg;if(Symbol.iterator in e){let t=Object.create(Vg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(Vg);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},Kg=e=>Object.setPrototypeOf(e,Vg),qg=/*#__PURE__*/ O(3,(e,t,n)=>{let r=Hg(e);return r[t.toLowerCase()]=n,r}),Jg=/*#__PURE__*/ O(2,(e,t)=>Hg({...e,...Gg(t)})),Yg=/*#__PURE__*/ O(2,(e,t)=>{let n=Hg(e);return Object.assign(n,t),n}),Xg=/*#__PURE__*/ O(2,(e,t)=>{let n=Hg(e);return delete n[t.toLowerCase()],n}),Zg=/*#__PURE__*/ O(2,(e,t)=>{let n=Hg(e);for(let e of t)delete n[e.toLowerCase()];return n}),Qg=/*#__PURE__*/ O(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=Ig(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=Ig(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),$g=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(typeof r==`string`){if(r.toLowerCase()===e.toLowerCase())return!0}else if(e.search(r)!==-1)return!0}return!1},e_=/*#__PURE__*/ ya(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`,`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]}),t_=`~effect/http/UrlParams`,n_=e=>A(e,t_),r_={...gr,[t_]:t_,[Symbol.iterator](){return this.params[Symbol.iterator]()},toJSON(){return{_id:`UrlParams`,params:Object.fromEntries(this.params)}},[yn](e){return s_(this,e)},[en](){return pn(this.params.flat())}},i_=e=>{let t=Object.create(r_);return t.params=e,t},a_=e=>{if(n_(e))return e;let t=o_(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 i_(n)},o_=e=>{let t=typeof e[Symbol.iterator]==`function`?Va(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,String(r[t])]);else if(typeof r==`object`&&r){let t=o_(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,String(r)]);return n},s_=/*#__PURE__*/ ci((e,t)=>c_(e.params,t.params)),c_=/*#__PURE__*/ Zee(/*#__PURE__*/ Ma([/*#__PURE__*/ ui(),/*#__PURE__*/ ui()])),l_=/*#__PURE__*/ i_([]),u_=/*#__PURE__*/ O(2,(e,t)=>{let n=a_(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 i_(n)}),d_=e=>new URLSearchParams(a_(e).params).toString(),f_=e=>{let t={};for(let[n,r]of e.params)if(!Object.hasOwn(t,n))ar(t,n,r);else{let e=t[n];typeof e==`string`?ar(t,n,[e,r]):e.push(r)}return t};function p_(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function m_(e){return t=>p_(t)?.[e]}const h_=`~structural`,g_=`~identifier`,__=`~sentinels`,v_=`~constructor`,y_=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],b_=/*#__PURE__*/ m_(`identifier`),x_=/*#__PURE__*/ m_(g_),S_=/*#__PURE__*/ m_(`description`),C_=/*#__PURE__*/ At(e=>{let t=p_(e)?.identifier;return typeof t==`string`?t:e.getExpected(C_)}),w_=/*#__PURE__*/ new Set([__,h_,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),T_=/*#__PURE__*/ Symbol(),E_=Bd,D_=/*#__PURE__*/ E_(T_),O_=/*#__PURE__*/ E_(T_),k_=e=>e===T_?Oi():ki(e),A_=e=>e._tag===`None`?D_:E_(e.value),j_=`~effect/SchemaIssue/Issue`;function M_(e){return A(e,j_)&&e[j_]===j_}function N_(e){return Object.hasOwn(e,`input`)}var P_=class{[j_]=j_;constructor(e,t){t?.reportInput===!0&&e!==T_&&(this.input=e)}};const F_=class extends P_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},I_=class extends P_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},L_=class extends P_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},R_=class extends P_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},z_=class extends P_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},B_=class extends P_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},V_=class extends P_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},H_=class extends P_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function U_(e,t,n,r,i){return new B_(e,[new L_([t],n)],r,i)}const W_=class extends P_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},G_=class extends P_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},K_=class extends P_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function q_(e,t,n){if(M_(e))return e;if(typeof e==`string`)return new H_({message:e},t,n);let r=typeof e.issue==`string`?new H_({message:e.issue},t,n):e.issue;return new L_(e.path,r)}function J_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new H_(void 0,t,n):q_(e,t,n)}function Y_(e,t,n,r){return Array.isArray(t)?Ga(t)?t.length===1?q_(t[0],n,r):new B_(e,Ja(t,e=>q_(e,n,r)),n,r):void 0:J_(t,n,r)}const X_=e=>{let t=sv(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return tv(C_(e.ast),e);case`InvalidValue`:{let t=ev(e);if(t!==void 0)return tv(t,e);let n=$_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=$_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=$_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Z_=e=>sv(e.issue)??sv(e);function Q_(e){return t=>({issues:nv(t,[],e?.leafHook??X_,e?.checkHook??Z_)})}function $_(e){return N_(e)?zn(e.input):void 0}function ev(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function tv(e,t){let n=$_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function nv(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 nv(e.issue,t,n,r);let a=ev(e.issue);return[{path:t,message:a===void 0?tv(rv(e.filter),e):tv(a,e.issue)}]}case`Encoding`:return nv(e.issue,t,n,r);case`Pointer`:return nv(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>nv(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:sv(e)??tv(C_(e.ast),e)}]:e.issues.flatMap(e=>nv(e,t,n,r));default:return[{path:t,message:n(e)}]}}function rv(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=>rv(e)).join(` & `)}}function iv(){return e=>ov(e,``)}const av=/*#__PURE__*/ iv();function ov(e,t){let n;switch(e._tag){case`Filter`:{let r=Z_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return ov(e.issue,t);let r=ev(e.issue);n=r===void 0?tv(rv(e.filter),e):tv(r,e.issue)}break}case`Encoding`:return ov(e.issue,t);case`Pointer`:return ov(e.issue,t+Hn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>ov(e,t)).join(`
|
|
16
|
-
`);n=sv(e)??tv(C_(e.ast),e);break;default:n=X_(e)}return t?`${n}\n at ${t}`:n}function sv(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return sv(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 cv(e){let t;for(let n of e.reasons){if(!fd(n)||!M_(n.error))return;t??=n.error}return t}function lv(e,t){let n=cv(e);if(n===void 0)throw Error(t,{cause:e});return n}const uv=(e,t,n)=>{switch(e._tag){case`Passthrough`:return N(t);case`Transform`:return N(zi(t,e.transform));case`TransformOptional`:return N(e.transform(t));case`TransformEffect`:return ji(t)?xp:Ym(e.transform(t.value,n),ki);case`TransformOptionalEffect`:return e.transform(t,n)}},dv=e=>Object.assign(Object.create(xt),e),fv=(e,t)=>Sv((n,r)=>Qm(uv(e,n,r),e=>uv(t,e,r))),pv=/*#__PURE__*/ O(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 yv(n=>t.transform(e.transform(n)));case`TransformOptional`:return xv(n=>t.transform(zi(n,e.transform)));case`TransformEffect`:return bv((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return fv(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return xv(n=>zi(e.transform(n),t.transform));case`TransformOptional`:return xv(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return fv(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return bv((n,r)=>Ym(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return fv(e,t);case`TransformEffect`:return bv((n,r)=>Qm(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return fv(e,t)}});function mv(e){return Sv((t,n)=>L(e(t,n)))}function hv(e){return mv((t,n)=>{let r={message:e(t)};return Mi(t)?new W_(r,t.value,n):new W_(r)})}const gv=/*#__PURE__*/ hv(()=>`Encoding is not supported`),_v=/*#__PURE__*/ dv({_tag:`Passthrough`});function vv(){return _v}function yv(e){return dv({_tag:`Transform`,transform:e})}function bv(e){return dv({_tag:`TransformEffect`,transform:e})}function xv(e){return dv({_tag:`TransformOptional`,transform:e})}function Sv(e){return dv({_tag:`TransformOptionalEffect`,transform:e})}function Cv(){return xv(()=>Oi())}function wv(e){return Sv(t=>{let n=zee(t,Ut);return Mi(n)?N(n):Ym(e,ki)})}function Tv(){return yv(globalThis.String)}function Ev(){return yv(globalThis.Number)}function Dv(){return yv(globalThis.BigInt)}function Ov(){return yv(Zne)}function kv(e){return bv((t,n)=>Op({try:()=>JSON.parse(t,e?.reviver),catch:()=>new H_({expected:`a valid JSON string`},t,n)}))}function Av(e){return bv((t,n)=>Op({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 H_({expected:`a JSON-serializable value`},t,n)}))}function jv(e){let t=e?.separator??`,`;return yv(e=>e===``?[]:e.split(t))}function Mv(){return yv(Jh)}function Nv(){return bv((e,t)=>Xm(Ap(Yh(e)),()=>new H_({expected:`a valid Base64 string`},e,t)))}const Pv=class extends St{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Pv(this.encode,this.decode)}},Fv=`~effect/SchemaTransformation/Transformation`,Iv=class extends St{[Fv]=Fv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Iv(this.encode,this.decode)}};function Lv(e){return A(e,Fv)&&e[Fv]===Fv}const Rv=e=>Lv(e)?e:new Iv(e.decode,e.encode);function zv(e){return new Iv(bv(e.decode),bv(e.encode))}function Bv(e){return new Iv(yv(e.decode),yv(e.encode))}function Vv(){return new Iv(Ov(),vv())}const Hv=/*#__PURE__*/ new Iv(/*#__PURE__*/ vv(),/*#__PURE__*/ vv());function Uv(){return Hv}const Wv=/*#__PURE__*/ new Iv(/*#__PURE__*/ Ev(),/*#__PURE__*/ Tv()),Gv=/*#__PURE__*/ new Iv(/*#__PURE__*/ Dv(),/*#__PURE__*/ Tv()),Kv=e=>Jt(e)&&typeof e.message==`string`,qv=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Zv(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},Jv=e=>{try{let t=Kn(e);return t===void 0?zn(e):JSON.parse(t)}catch{return zn(e)}},Yv=(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},Xv=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(Qt(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Yv(r,e,n);return t.delete(r),i}return Jv(r)};return n},Zv=e=>Kv(e)?qv(e):e,hre=e=>Bv({decode:Zv,encode:Xv(e)}),Qv=/*#__PURE__*/ new Iv(/*#__PURE__*/ Nv(),/*#__PURE__*/ Mv());function gre(e){return new Iv(kv(e??{}),Av(e))}function $v(e){return t=>t._tag===e}const ey=/*#__PURE__*/ $v(`Declaration`),_re=/*#__PURE__*/ $v(`Null`),vre=/*#__PURE__*/ $v(`Undefined`),ty=/*#__PURE__*/ $v(`Void`),yre=/*#__PURE__*/ $v(`Never`),ny=/*#__PURE__*/ $v(`Literal`),ry=/*#__PURE__*/ $v(`UniqueSymbol`),bre=/*#__PURE__*/ $v(`Enum`),iy=/*#__PURE__*/ $v(`Arrays`),ay=/*#__PURE__*/ $v(`Objects`),oy=/*#__PURE__*/ $v(`Union`),sy=/*#__PURE__*/ $v(`Suspend`),cy=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},ly={},uy=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}},dy=`~effect/Schema`;var fy=class{[dy]=dy;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 py=class extends fy{_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===T_?D_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Cb(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new py(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>`}},my=/*#__PURE__*/ new class extends fy{_tag=`Null`;getParser(){return Nb(this,null)}getExpected(){return`null`}},xre=class extends fy{_tag=`Undefined`;getParser(){return Nb(this,void 0)}toCodecJson(){return fb(this,[hy])}getExpected(){return`undefined`}},hy=/*#__PURE__*/ new cy(my,/*#__PURE__*/ new Iv(/*#__PURE__*/ yv(()=>void 0),/*#__PURE__*/ yv(()=>null))),gy=/*#__PURE__*/ new xre,Sre=/*#__PURE__*/ new class extends fy{_tag=`Void`;getParser(){let e=E_(void 0);return t=>t===T_?D_:e}toCodecJson(){return fb(this,[hy])}getExpected(){return`void`}},Cre=/*#__PURE__*/ new class extends fy{_tag=`Never`;getParser(){return Pb(this,Kt)}getExpected(){return`never`}},wre=/*#__PURE__*/ new class extends fy{_tag=`Any`;getParser(){return Pb(this,qt)}getExpected(){return`any`}},_y=/*#__PURE__*/ new class extends fy{_tag=`Unknown`;getParser(){return Pb(this,qt)}getExpected(){return`unknown`}};function vy(e){return typeof e==`number`?`parts[${e}]`:e}function yy(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${vy(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=vy(t);r=!e.checks&&e.parts.every((e,t)=>yy(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=vy(t);r=!e.checks&&e.types.every((e,t)=>yy(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const Tre=class extends fy{_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(!yy(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 Ty(!1,this.parts.map(Rb),[]),n=e(Eb(Sy,t,Ere(this)));return(e,t)=>{if(e===T_)return D_;let r=n(e,t);return r._tag===`Success`?O_:Zm(r,{onSuccess:()=>e,onFailure:n=>new B_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return Fb(this,e,t)===void 0?void 0:e}};function Ere(e){return new Iv(bv((t,n)=>{let r=Fb(e,t,n);return r?N(r):L(new H_({expected:`a string matching template literal parts`},t,n))}),yv(e=>e.join(``)))}const by=class extends fy{_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 ${zn(e)}`);this.literal=e}getParser(){return Nb(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?xy(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:xy(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function xy(e){let t=globalThis.String(e.literal);return fb(e,[new cy(new by(t),new Iv(yv(()=>e.literal),yv(()=>t)))])}const Sy=/*#__PURE__*/ new class extends fy{_tag=`String`;getParser(){return Pb(this,It)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Hb(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Dre=class extends fy{_tag=`Number`;getParser(){return Pb(this,Lt)}matchKey(e,t){return this._match(Zre,e,t)}matchPart(e,t){return this._match(zb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Hb(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Cy(this.checks,`effect/schema/isFinite`)||Cy(this.checks,`effect/schema/isInt`))?this:fb(this,[zre])}toCodecStringTree(){return this.toCodecJson()===this?fb(this,[$re]):fb(this,[eie])}getExpected(){return`number`}};function Cy(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Cy(e.checks,t))}const wy=/*#__PURE__*/ new Dre,Ore=/*#__PURE__*/ new class extends fy{_tag=`Boolean`;getParser(){return Pb(this,Rt)}getExpected(){return`boolean`}},kre=/*#__PURE__*/ new class extends fy{_tag=`BigInt`;getParser(){return Pb(this,mee)}matchPart(e,t){if(!Vb.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Hb(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return fb(this,[nie])}getExpected(){return`bigint`}},Ty=class extends fy{_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(Db(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(Db(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 z_(n,t[o],i),a=new L_([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return L(new B_(n,[a],t,i))}return e.issues?L(new B_(n,e.issues,t,i)):E_(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:du(t.concurrency),f=d===1?jre(i,e,0,u):Mre(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Zc(f))return Qm(f,()=>c(i));let p=!0;return Sp(()=>p?(p=!1,R(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===T_)return D_;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):L(new V_(n,e,a))}catch(e){return Dp(e)}}}_rebuild(e,t,n){let r=Cb(this.elements,e),i=Cb(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Ty(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 Are(e,t,n,r){if(n._tag===`Failure`)return Dy(e,e.ast,r,n);let i=n===O_?t:n[ur];if(i!==T_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Db(t.ast))return;let n=new L_([r],new R_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Hd(new B_(e.ast,[n],e.input,e.options))}}const Ey={onItem(e,t,n){let r=n<e.len?t:T_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Are},jre=/*#__PURE__*/ fu()(Ey),Mre=/*#__PURE__*/ mu()(Ey),Dy=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=cv(r.cause);if(i===void 0)return Vd(bd(r.cause,r=>new B_(t,[new L_([n],r)],e.input,e.options)));let a=new L_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Hd(new B_(t,[a],e.input,e.options))},Oy=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function ky(e,t,n=ly){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(Ab(t)))}const Ay=class{name;type;constructor(e,t){this.name=e,this.type=t}};function jy(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(jy);default:return!1}}function My(e){let t=mb(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(My);default:return!1}}function Nre(e){return jy(e)&&My(e)}const Ny=class{parameter;type;constructor(e,t){if(!Nre(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Db(t)&&!Mb(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Py=class extends fy{_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 Pb(n,hee);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 Dy(t,n,i,s)??Gd;let c=s===O_?o:s[ur];if(a!==T_&&c!==T_){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Gd;ar(t.out,a,c)}return Gd},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Zc(t))return R(Pp(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Dy(e,n,r,a)??Gd;let o=a===O_?r:a[ur],s=e.input[r],l=i.parserValue(s,e.options);return Zc(l)?t(e,r,o,s,l):R(Pp(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Zc(a)?t(e,n,n,i,a):R(Pp(a),r=>t(e,n,n,i,r))},u=i?mu()({onItem:(e,[t,n])=>n.is.parameter===Sy?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return eh(function*(t,d){if(t===T_)return T_;if(typeof t!=`object`||!t||Array.isArray(t))return yield*L(new V_(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:du(d.concurrency),v=i&&g?n.indexSignatures.map(e=>ky(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 z_(n,f[a],d),r=new L_([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*L(new B_(n,[r],t,d))}}}if(r){let e=_===1?Ly(m,a):Pre(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Sy?l:c,r=v?.[e]??(t.is.parameter===Sy?Object.keys(f):ky(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Zc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Ka();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Sy?Object.keys(f):ky(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*L(new B_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return R(Pp(n),n=>{let i=Fy(e,r,n);if(i)return i;let o=()=>E_(e.out),s=Ly(e,a.slice(t+1));return s?Qm(s,o):o()})};return(e,t)=>{if(e===T_)return D_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&du(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return L(new V_(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=Yy(i,s),l=c?i[s]:T_,d=n.parser(l,t);if(!Zc(d))return u(o,e,d);if(d===O_){c&&ar(a,s,l);continue}let f=Fy(o,n,d);if(f)return f}}catch(e){return Dp(e)}return E_(a)}}_rebuild(e,t,n,r){let i=Cb(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Ay(t.name,n)}),a=Cb(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 Py(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 Fy(e,t,n){if(n._tag===`Failure`)return Dy(e,e.ast,t.name,n);if(n===O_)return;let r=n[ur];if(r!==T_){ar(e.out,t.name,r);return}if(delete e.out[t.name],!Db(t.type)){let n=new L_([t.name],new R_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Hd(new B_(e.ast,[n],e.input,e.options))}}const Iy={onItem(e,t){if(!Yy(e.input,t.name))return t.parser(T_,e.options);let n=e.input[t.name];return ar(e.out,t.name,n),t.parser(n,e.options)},step:Fy},Ly=/*#__PURE__*/ fu()(Iy),Pre=/*#__PURE__*/ mu()(Iy);function Ry(e,t){return e?t?[...e,...t]:e:t}function zy(e,t,n){return new Py(Reflect.ownKeys(e).map(t=>new Ay(t,e[t].ast)),[],n,t)}function By(e){return e.ast}function Vy(e,t=void 0){return new Ty(!1,e.map(e=>e.ast),[],void 0,t)}function Hy(e,t,n){return new Xy(e.map(By),t,void 0,n)}function Fre(e,t){if(e.encoding||t.some(e=>e.encoding))throw Error(`StructWithRest does not support encodings`);let n=e.propertySignatures,r=e.indexSignatures,i=e.checks;for(let e of t){for(let t of e.propertySignatures)if(n.some(e=>e.name===t.name))throw Error(`Duplicate identifier: ${JSON.stringify(t.name)}. ts(2300)`);n=n.concat(e.propertySignatures),r=r.concat(e.indexSignatures),i=Ry(i,e.checks)}return new Py(n,r,void 0,i)}const Uy=/*#__PURE__*/ jt(e=>{for(;;){if(sy(e))return _y;let t=e.encoding;if(!t)return e.recur?.(Uy,k)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==k))return _y;e=t[t.length-1].to}});function Wy(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(Wy)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function Gy(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[__];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Db(t)){if(ny(t))return[{key:e.name,literal:t.literal}];if(ry(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Db(e)){if(ny(e))return[{key:t,literal:e.literal}];if(ry(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>Gy(Uy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return Gy(e.thunk())}}const Ky=/*#__PURE__*/ new WeakMap,qy=/*#__PURE__*/ Object.freeze([]),Jy=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Yy=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Ire(e){let t=Ky.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=Uy(c);if(yre(l))continue;if(ny(l)||ry(l)){a??=/* @__PURE__ */ new Map;let e=ny(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=Gy(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=Wy(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??qy);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??qy;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(Xt(e)){let n=Yy(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??qy;if(t)return o}return qy}}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=Jy(t);if(!Xt(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Yy(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=Yy(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=Yy(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(Jy(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Ky.set(e,t),t}const Xy=class extends fy{_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===T_)return D_;let i=(o??=Ire(n.types))(e,r);if(i.length===0)return L(new G_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Zc(r)?Zy(n,r.cause,e,t):Lre(n,r,e,t)}return Qy(n,a,i,e,t)}}_rebuild(e,t,n){let r=Cb(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Xy(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=Ab(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(ny);if(t.length>0)return`${nb(n.isMutable)}[ ${t.map(t=>e(t)+rb(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>ny(e.type));if(t.length>0)return`{ ${t.map(t=>`${nb(t.type.context?.isMutable)}${Vn(t.name)}${rb(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Zy(e,t,n,r){let i=cv(t);return i?Hd(new G_(e,[i],n,r)):Vd(t)}function Lre(e,t,n,r){return zp(t,t=>Zy(e,t,n,r))}function Qy(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=eb(a,n);if(!o)return a.out?a.out:L(new G_(e,a.issues??[],r,i));if(Zc(o))return $y(o,a);let s=!0;return Sp(()=>s?(s=!1,$y(o,a)):Qy(e,t,n,r,i))}function $y(e,t){return Qm(e,e=>t.out===O_?N(t.input):t.out?t.out:L(new G_(t.ast,t.issues??[],t.input,t.options)))}const eb=/*#__PURE__*/ fu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=cv(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]),Hd(new K_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Gd}}}),tb=/*#__PURE__*/ new Xy([/*#__PURE__*/ new by(`Infinity`),/*#__PURE__*/ new by(`-Infinity`),/*#__PURE__*/ new by(`NaN`)]);function nb(e){return e?``:`readonly `}function rb(e){return e?`?`:``}const ib=class extends St{_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 ib(this.run,{...this.annotations,...e},this.aborted)}abort(){return new ib(this.run,this.annotations,!0)}and(e,t){return new ab([this,e],t)}},ab=class extends St{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new ab(this.checks,{...this.annotations,...e})}and(e,t){return new ab([this,e],t)}};function ob(e,t,n=!1){return new ib((t,n,r)=>Y_(n,e(t,n,r),t,r),t,n)}function Rre(e){return ob(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 sb=/*#__PURE__*/ _b(wy,[/*#__PURE__*/ Rre()]),zre=/*#__PURE__*/ new cy(/*#__PURE__*/ new Xy([sb,tb]),/*#__PURE__*/ new Iv(/*#__PURE__*/ Ev(),/*#__PURE__*/ yv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function cb(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return ob(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 lb=/*#__PURE__*/ new WeakMap;function ub(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&lb.set(n,db(e)),n}function db(e){let t=lb.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 lb.set(e,n),n}function fb(e,t){return e.encoding===t?e:ub(e,{encoding:t})}function pb(e,t){if(e.context===t)return e;let n=db(e);return n.context===t&&n.encoding===e.encoding?n:ub(e,{context:t})}function mb(e){return e.encoding?mb(e.encoding[e.encoding.length-1].to):e}function hb(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return gb(e,Ua(e.checks.slice(0,-1),n.annotate(t)))}return ub(e,{annotations:{...e.annotations,...t}})}function gb(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:ub(e,{checks:t})}function _b(e,t){return gb(e,Ry(e.checks,t))}function vb(e,t){let n=t(e.to);return n===e.to?e:new cy(n,e.transformation)}function yb(e,t){let n=e,r=n[n.length-1],i=vb(r,t);return i===r?e:Ua(e.slice(0,e.length-1),i)}function bb(e){return t=>t.encoding?fb(t,yb(t.encoding,e)):t}function xb(e,t){return bb(e=>pb(e,t))(e)}function Bre(e){function t(n){return n.encoding?fb(n,yb(n.encoding,t)):e(n)}return At(t)}function Sb(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:fb(r,yb(r.encoding,n))}return e(r)}return jt(n)}function Vre(e,t,n){let r=new cy(e,t);return fb(n,n.encoding?[...n.encoding,r]:[r])}function Cb(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 wb(e,t){return pb(e,e.context?new uy(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new uy(!1,!1,void 0,t))}const Tb=/*#__PURE__*/ jt(e=>{let t=e.context?e.context.isOptional===!1?new uy(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new uy(!0,!1);return Hre(pb(e,t))}),Hre=/*#__PURE__*/ bb(Tb),Ure=/*#__PURE__*/ At(e=>Tb(new Xy([e,gy])));function Wre(e,t){return pb(e,e.context?new uy(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new uy(!1,!1,t))}function Eb(e,t,n){return Vre(e,n,t)}function Gre(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Bt(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 Kre(e,t){let{literals:n,parameters:r}=Gre(e);return new Py(n.map(e=>new Ay(e,t)),r.map(e=>new Ny(e,t)))}function Db(e){return e.context?.isOptional??!1}function qre(e){return e.context?.isMutable??!1}function Ob(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Ob)}function Jre(e){function t(e){return Ob(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Wa(n)?n:void 0}function Yre(e){let t=!0;function n(e){return t=t&&!e.encoding&&!sy(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const kb=/*#__PURE__*/ jt(e=>{let t=db(e);if(t!==e){let n=kb(t);return n===t&&e.encoding===void 0?e:pb(n,e.context)}let n=`recur`in e?e.recur(kb):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Yre(e)?n.encodingChecks:iy(n)||ay(n)||ey(n)&&n.typeParameters.length>0?Jre(n.encodingChecks):void 0;return ub(n,{encodingChecks:void 0,checks:Ry(n.checks,t)})}return n}),Ab=/*#__PURE__*/ jt(e=>kb(jb(e)));function Xre(e,t){let n=t,r=n.length,i=n[r-1],a=[new cy(jb(fb(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new cy(jb(n[e-1].to),n[e].transformation.flip()));let o=jb(i.to);return o.encoding?fb(o,[...o.encoding,...a]):fb(o,a)}const jb=/*#__PURE__*/ At(e=>{if(e.encoding)return Xre(e,e.encoding);let t=db(e);if(t!==e){let n=jb(t);return n===t?e:pb(n,e.context)}return`flip`in e?e.flip(jb):`recur`in e?e.recur(jb):e});function Mb(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Mb);default:return!1}}function Nb(e,t){let n=t===0?O_:E_(t);return(r,i)=>r===T_?D_:r===t?n:L(new V_(e,r,i))}function Pb(e,t){return(n,r)=>n===T_?D_:t(n)?O_:L(new V_(e,n,r))}function Fb(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__*/ Sb(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Ib)}}),Lb=/*#__PURE__*/ Sb(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Lb)}}),Rb=/*#__PURE__*/ Sb(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(Rb)}}),zb=/*#__PURE__*/ new globalThis.RegExp(`^${Oy}$`),Zre=/*#__PURE__*/ new globalThis.RegExp(`^(?:${Oy}|Infinity|-Infinity|NaN)$`);function Qre(e){return cb(zb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:zb.source}),...e})}const Bb=/*#__PURE__*/ _b(Sy,[/*#__PURE__*/ Qre()]),$re=/*#__PURE__*/ new cy(Bb,Wv),eie=/*#__PURE__*/ new cy(/*#__PURE__*/ new Xy([Bb,tb]),Wv),Vb=/*#__PURE__*/ new globalThis.RegExp(`^-?\\d+$`);function tie(e){return cb(Vb,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Vb.source}),...e})}const nie=/*#__PURE__*/ new cy(/* @__PURE__ */ _b(Sy,[/*#__PURE__*/ tie({expected:`a string representing a bigint`})]),Gv);function Hb(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Hb(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new F_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function rie(e){if(!ey(e))return;let t=e.annotations?.[v_];return Vt(t)?t(e.typeParameters):void 0}const Ub=m_,Wb=b_,Gb=S_;function iie(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function aie(e){return e===void 0||typeof e==`string`}function Kb(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 qb(e){return Kb(e,iie)}const Jb=/*#__PURE__*/ new py([],()=>(e,t,n)=>qb(e)?O_:L(new V_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Xb}),oie=/*#__PURE__*/ hb(Jb,{representation:{id:`effect/schema/MutableJson`,payload:null}}),Yb=/*#__PURE__*/ new cy(Jb,/*#__PURE__*/ Uv()),sie=/*#__PURE__*/ new cy(/*#__PURE__*/ new Xy([/*#__PURE__*/ new Ty(!1,[],[Jb]),/*#__PURE__*/ new Py([],[/*#__PURE__*/ new Ny(Sy,Jb)])]),/*#__PURE__*/ Uv());function cie(e){return Kb(e,aie)}const Xb=/*#__PURE__*/ new cy(/* @__PURE__ */ new py([],()=>(e,t,n)=>cie(e)?O_:L(new V_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ Uv()),Zb=(e,t,n)=>e===O_?n(t):Qm(e,n);function Qb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===O_?e.decode(E_(k_(n)),r):e.decode(Ym(t,k_),r);return $b(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===O_?E_(t):e;case`Transform`:{let e=e=>e===T_?D_:E_(t.transform(e));return(t,n)=>Zb(t,n,e)}case`TransformOptional`:{let e=e=>A_(t.transform(k_(e)));return(t,n)=>Zb(t,n,e)}case`TransformEffect`:return(e,n,r)=>Zb(e,n,e=>e===T_?D_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>Zb(e,n,e=>$b(t.transform(k_(e),r)))}}const $b=e=>Qm(e,A_),ex=(e,t,n,r)=>zp(r,r=>Ep(()=>bd(r,r=>new I_(e,r,t,n))));function lie(e,t){let n=Qb(e.link.transformation),r;return(i,a)=>{if(i===T_)return D_;if(e.isConstructed(i))return O_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function uie(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==T_&&r!==void 0)return t(r,i);let a=n;if(Zc(a)&&a._tag===`Success`){let e=t(a[ur],i);return e===O_?a:e}return Qm(ex(e,r,i,a),e=>{let n=t(e,i);return n===O_?E_(e):n})}}function die(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:uie(e,n)}function tx(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?rie(e):void 0,o=a?lie(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>Qb(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(Zc(r)){if(r._tag===`Success`){let i=r===O_?t:r[ur];if(t!==T_&&i!==T_){let i=Hb(u,t,void 0,e,n);i&&(r=L(new B_(e,i,t,n)))}}}else r=R(r,r=>{if(t!==T_&&r!==T_){let r=Hb(u,t,void 0,e,n);if(r)return L(new B_(e,r,t,n))}return N(r)})}if(s&&!n.disableChecks){if(Zc(r)){if(r._tag===`Success`){let i=r===O_?t:r[ur];if(i===T_)return r;let a=Hb(s,i,void 0,e,n);a&&(r=L(new B_(e,a,i,n)))}}else r=R(r,t=>{if(t!==T_){let r=Hb(s,t,void 0,e,n);if(r)return L(new B_(e,r,t,n))}return N(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=Qm(o,e=>{let n=t(e,r);return n===O_?E_(e):n})}if(o._tag===`Success`){let e=o[ur],t=p(e,r);return t===O_?o:t}return o=ex(e,n,r,o),Qm(o,e=>{let t=p(e,r);return t===O_?E_(e):t})}:p}const fie=/*#__PURE__*/ Symbol(),nx=/*#__PURE__*/ new WeakMap,pie=e=>ix(e).parser,rx=e=>ix(e).makeEffect,mie=e=>die(e,rx);var hie=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=tx(this.ast,pie)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=tx(this.ast,rx,mie)}};function ix(e){let t=nx.get(e);if(t!==void 0)return t;let n=new hie(e);return nx.set(e,n),n}function ax(e){let t=e.ast,n;return(e,r)=>(n??=mx(Eie,kb(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function ox(e){let t=ax(e);return(e,n)=>{let r=Bm(t(e,n));return Kd(r)?ki(r.value):(lv(r.cause,`Option adapter can only return none for schema issues`),Oi())}}function sx(e){return wie(kb(e.ast))}function gie(e){return cx(e.ast)}function _ie(e){{let t=hx(px(e));return e=>{let n=t(e,ly);return Kd(n)?!0:(lv(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function cx(e){let t=kb(e),n=e=>(n=_ie(t),n(e));return e=>n(e)}function lx(e,t){let n=px(e.ast);return t===void 0?n:(e,r)=>n(e,dx(t,r))}function vie(e,t){return xie(lx(e,t))}function yie(e,t){return Sie(lx(e,t))}function ux(e,t){let n=px(jb(e.ast));return t===void 0?n:(e,r)=>n(e,dx(t,r))}const dx=(e,t)=>t?{...e,...t}:e,fx=e=>e===T_?L(new H_):N(e);function px(e){return mx(Tie,e)}function bie(e,t){return e===O_?N(t):Zc(e)?e[ur]===T_?fx(T_):e:Qm(e,fx)}function mx(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??ly);return a===O_?N(r):Zc(a)?a[ur]===T_?fx(T_):a:Qm(a,fx)}}function hx(e){return(t,n)=>Bm(e(t,n))}function xie(e){let t=hx(e);return(e,n)=>{let r=t(e,n);return Kd(r)?ki(r.value):(lv(r.cause,`Option adapter can only return none for schema issues`),Oi())}}function Sie(e){let t=hx(e);return(e,n)=>{let r=t(e,n);return Kd(r)?Sa(r.value):Ca(lv(r.cause,`Result adapter can only return schema issues`))}}function Cie(e,t){let n=Bm(e);if(Kd(n))return n.value;let r=lv(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function wie(e){let t,n;return(r,i)=>{t??=ix(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??ly,o=t.make;if(o!==void 0&&r!==T_){let e;try{e=o(r,a)}catch(e){throw lv(gd(e),`Constructor adapter can only throw schema issues`),e}if(e!==fie&&e!==T_)return e}return Cie(bie((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const Tie=e=>ix(e).parser,Eie=e=>ix(e).makeEffect,gx=`~effect/Schema/Schema`,_x=/*#__PURE__*/ Symbol(),Die={[gx]:gx,get make(){let e=sx(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=ax(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=ox(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return bt(this,arguments)},annotate(e){return this.rebuild(hb(this.ast,e))},annotateKey(e){return this.rebuild(wb(this.ast,e))},check(...e){return this.rebuild(_b(this.ast,e))},rebuild(e){return vx(e,this[_x])}};function vx(e,t){function n(){}let r=Object.setPrototypeOf(n,Die);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[_x]=t,r.ast=e,r}function Oie(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function yx(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function bx(e){return encodeURI(Oie(e)).replace(/#/g,`%23`)}function xx(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 Sx(e){let t=xx(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(yx)}function kie(e){return e.reduce((e,t)=>`${e}/${bx(t)}`,`#`)}const Aie=[`example`,`discriminator`,`xml`,`externalDocs`];function jie(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>Cx.test(e))),i=t.filter(e=>!Cx.test(e)).sort().map(e=>[e,Mie(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=Ex(t.$id),a=Jt(t.$defs)?t.$defs:void 0;return wx(t,(t,o)=>{Fie(t,Aie,`OpenAPI 3.1`,`Draft 2020-12`),Tx(t,(t,s)=>{let c=t.startsWith(`#`)?Sx(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))&&Ox(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:kie([`components`,`schemas`,n.get(l)??l,...c.slice(2)])})})}let o=e.schemas.map(e=>a(e,!0)),s={};for(let r of t)ar(s,n.get(r)??r,a(e.definitions[r]));return{dialect:`openapi-3.1`,schemas:o,definitions:s}}const Cx=/^[a-zA-Z0-9.\-_]+$/;function Mie(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function wx(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!Jt(e))return e;let a=r||!i&&Ex(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=Pie(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)}ar(o,t,i)}return t(o,a),o}}function Nie(e,t){return wx(e,e=>{Tx(e,t)})}function Tx(e,t){typeof e.$ref==`string`&&ar(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&ar(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function Pie(e,t){if(!Jt(e))return;let n={};for(let r of Object.keys(e))ar(n,r,t(e[r],r));return n}function Ex(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const Dx=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Dx],[...Dx];function Ox(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Fie(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Ox(i,n,`it is not active in ${r} but would become active in the target`)}function Iie(e){return vx(kx(e.ast),{schema:e})}const kx=/*#__PURE__*/ Sb(e=>{let t=Rie(e,kx),n=e.context;return t===e||n===void 0?t:xb(t,Ax(n))});function Ax(e){return e.constructorDefault===void 0?e:new uy(e.isOptional,e.isMutable,void 0,e.annotations)}function jx(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Mx(e){return t=>{let n=[...t].sort((t,n)=>e(Ab(t))-e(Ab(n)));return n.some((e,n)=>e!==t[n])?n:t}}const Lie=/*#__PURE__*/ Mx(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Rie(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Vt(n))return fb(e,[Yb]);let r=n(e.typeParameters.map(e=>vx(Ab(e))));return r===void 0?e:fb(e,[vb(r,t)])}case`Unknown`:return fb(e,[Yb]);case`ObjectKeyword`:return fb(e,[sie]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return jx(e),e.recur(t,Lb);case`Union`:{let n=Lie(e.types);return n===e.types?e.recur(t):new Xy(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 zie(e){return vx(Fx(e.ast),{schema:e})}function Bie(e){return vx(Lx(e.ast))}const Vie=/*#__PURE__*/ Mx(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Hie(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>vx(t(Ab(e)))),i=e.annotations?.toCodecStringTree;if(Vt(i)){let n=i(r);return n===void 0?e:fb(e,[vb(n,t)])}let a=e.annotations?.toCodecJson,o=Vt(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(Vt(s)?s(r):void 0);return c===void 0?n(e):fb(e,[vb(c,t)])}case`Null`:return fb(e,[Uie]);case`Boolean`:return fb(e,[Wie]);case`Unknown`:case`ObjectKeyword`:return fb(e,[Xb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return jx(e),e.recur(t,Lb);case`Union`:{let n=Vie(e.types);return n===e.types?e.recur(t):new Xy(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 Uie=/*#__PURE__*/ new cy(/*#__PURE__*/ new by(`null`),/*#__PURE__*/ new Iv(/*#__PURE__*/ yv(()=>null),/*#__PURE__*/ yv(()=>`null`))),Wie=/*#__PURE__*/ new cy(/*#__PURE__*/ new Xy([/*#__PURE__*/ new by(`true`),/*#__PURE__*/ new by(`false`)]),/*#__PURE__*/ new Iv(/*#__PURE__*/ yv(e=>e===`true`),/*#__PURE__*/ Tv())),Nx=/*#__PURE__*/ new Iv(/*#__PURE__*/ yv(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ vv()),Px=e=>e.transformation===Nx,Fx=/*#__PURE__*/ Sb(e=>{let t=Hie(e,Fx,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?xb(t,Ax(e.context)):t},{stopAt:Px}),Ix=e=>Db(e)?Tb(_y):_y,Lx=/*#__PURE__*/ Sb(e=>{let t=Gie(e);if(iy(t)){let n=Eb(new Xy([new Ty(t.isMutable,t.elements.map(Ix),t.rest.map(Ix)),Sy],{mode:`anyOf`}),t,Nx);return Db(e)?Tb(n):n}return t},{stopAt:Px});function Gie(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur(Lx):e}globalThis.RegExp;const Kie=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Rx(e,t){return t.length>0&&(e+=`\n at ${Hn(t)}`),Error(e)}function zx(e){return`#/$defs/${bx(e)}`}const qie=/*#__PURE__*/ new Set([...w_,g_,...y_]);function Bx(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;qb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&qb(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(qb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!qie.has(r)&&t.includeAnnotationKey(r)&&qb(i)&&ar(n,r,i);return Object.keys(n).length===0?void 0:n}function Vx(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=Vx(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 Jie(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 Hx(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function Ux(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}const Wx=`|title|description|default|examples|readOnly|writeOnly|`;function Gx(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Jie(e);if(i!==void 0||a){let r=Vx(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:Hx(r.schema,Wx)&&Ux(o,s)?{...o,...r.schema}:Gx(o,r.schema,n)}}if(n&&Ux(e,r))return{...e,...t};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 Kx(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>Kx(e,t)))}function Yie(e){return Array.isArray(e)}function qx(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=Ja(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!Kx(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=>bn(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Ja(u,h),f={};for(let e of l)a.has(e)||ar(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 Rx(`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 Nie(e,e=>{let t=xx(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(yx(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,zx(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[g_]: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=Yie(s);c&&i.push(!1);let l=c?s[0]:s,u=Bx(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`&&Hx(d,f)&&(u===void 0||Hx(u,Wx))?!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=Bx(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:zx(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=Bx(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&Xie(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=Gx(s,...i))}return o.set(e,[s,a]),p(s)}function y(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return v(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw Rx(`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(Jx).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Rx(`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=Bx(e.annotations,r);return s===void 0?o:p(Gx(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=v(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw Rx(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=Bx(s.annotations,r);ar(a,c,u===void 0?l:p(Gx(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=v(i.type,[...t,`indexSignatures`,r,`type`],n);bn(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);continue}if(o.length===0)c.push(a);else for(let e of o){let t=s[e];ar(s,e,t===void 0?a:t===!1||a===!1?!1:p(Gx(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(v(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>v(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=Zie(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 Rx(`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 Kx(n)&&r.type===`string`&&typeof r.pattern==`string`&&Hx(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(Jx).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 Rx(`Invalid schema representation document`,t)}}}function Xie(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function Zie(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 Jx(e){switch(e._tag){case`Literal`:return Kie(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return Oy;case`TemplateLiteral`:return e.parts.map(Jx).join(``);case`Union`:return`(?:${e.types.map(Jx).join(`|`)})`;default:throw Rx(`Invalid schema representation document`,[])}}function Qie(e,t){let n=qx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function $ie(e,t){return qx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const eae=({identifier:e})=>e;function Yx(e){return e===void 0?void 0:{annotations:e}}function tae(e,t){let{references:n,representations:r}=Xx([e],t);return{representation:r[0],references:n}}function Xx(e,t){let n={},r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set;for(let t of e)f(t);let s=t?.referencePolicy??eae;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:Ja(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:hb(e,{identifier:n}):x_(e)===r?e:hb(e,{[g_]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),ar(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=mb(e),n=db(t),r=b_(t),i=r===void 0?(t===e?void 0:b_(e))??x_(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;return}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(kb(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,...Yx(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...Yx(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...Yx(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...Yx(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...Yx(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=mb(e),n=t.context?.annotations;return{isOptional:Db(t),type:m(e),...Yx(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...Yx(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=mb(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Db(t),isMutable:qre(t),...Yx(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...Yx(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...Yx(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...Yx(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:Ja(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(kb(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function Zx(e){return Kd(e)?e.value:{issues:[{message:Od(e.cause)}]}}function nae(e,t){let n=lx(e),r={errors:`all`,...t?.parseOptions},i=Q_(t),a=e=>{let t=new Mo(`sync`),a=Fm(Zp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?Zx(o):new Promise(e=>{a.addObserver(t=>{e(Zx(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 rae=/*#__PURE__*/ O(2,(e,t)=>({...e,...t})),Qx=e=>e,$x=`~effect/Schema/SchemaError`;function eS(e){return A(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}const tS=gx;function nS(){return(e,t,n)=>gS(new py(e.map(By),e=>t(e.map(e=>gS(e))),n))}function rS(e,t){return nS()([],()=>(t,n,r)=>e(t)?N(t):L(new V_(n,t,r)),t)}var iS=class extends (/*#__PURE__*/ Vo(`SchemaError`)){[$x]=$x;constructor(e){let t=tr();nr(0);try{super({issue:e})}finally{nr(t)}}get message(){return av(this.issue)}toString(){return`SchemaError(${this.message})`}};function aS(e){return eS(e)}function oS(e){return Zc(e)?iae(e):zp(e,e=>Ep(()=>bd(e,e=>new iS(e))))}function iae(e){return Kd(e)?e:Vd(bd(e.cause,e=>new iS(e)))}function aae(e,t){let n;for(let r of e.reasons){if(!fd(r)||!aS(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 sS(e){let t=Bm(e);if(Kd(t))return t.value;throw aae(t.cause,`Sync adapter can only throw schema errors`)}function oae(e,t){return nae(e,t)}const cS=gie;function lS(e,t){let n=lx(e,t);return(e,t)=>oS(n(e,t))}const uS=lS,sae=vie;function cae(e,t){let n=yie(e,t);return(e,t)=>Oa(n(e,t),e=>new iS(e))}function dS(e,t){let n=lS(e,t);return(e,t)=>sS(n(e,t))}const lae=dS;function fS(e,t){let n=ux(e,t);return(e,t)=>oS(n(e,t))}const pS=fS;function mS(e,t){let n=fS(e,t);return(e,t)=>sS(n(e,t))}const hS=mS,gS=vx;function _S(e){return A(e,tS)&&e[tS]===tS}const vS=/*#__PURE__*/ Qx(e=>gS(Tb(e.ast),{schema:e})),yS=/*#__PURE__*/ Qx(e=>{let t=HS(e);return gS(Ure(e.ast),{schema:t})}),bS=/*#__PURE__*/ Qx(e=>gS(kb(e.ast),{schema:e})),xS=/*#__PURE__*/ Qx(e=>gS(Ab(e.ast),{schema:e}));function SS(e){let t=gS(new by(e),{literal:e,transform(n){return t.pipe(US(SS(n),{decode:yv(()=>n),encode:yv(()=>e)}))}});return t}function uae(e){return e.map(e=>_S(e)?e.ast:new by(e))}function CS(e){return gS(new Tre(uae(e)),{parts:e})}const wS=/*#__PURE__*/ gS(Cre),TS=/*#__PURE__*/ gS(wre),ES=/*#__PURE__*/ gS(_y),DS=/*#__PURE__*/ gS(my),dae=/*#__PURE__*/ gS(gy),H=/*#__PURE__*/ gS(Sy),OS=/*#__PURE__*/ gS(wy),kS=/*#__PURE__*/ gS(Ore),AS=/*#__PURE__*/ gS(kre),jS=/*#__PURE__*/ gS(Sre);function MS(e,t){return gS(e,{fields:t,mapFields(e,t){let n=e(this.fields);return MS(zy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function U(e){return MS(zy(e,void 0),e)}function NS(e){return Qx(t=>t.mapFields(rae(e)))}function PS(e,t){return gS(Kre(e.ast,t.ast),{key:e,value:t})}function FS(e,t){return gS(Fre(e.ast,t.map(By)),{schema:e,records:t})}function IS(e,t){return gS(e,{elements:t,mapElements(e,t){let n=e(this.elements);return IS(Vy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function LS(e){return IS(Vy(e),e)}const W=/*#__PURE__*/ Qx(e=>gS(new Ty(!1,[],[e.ast]),{value:e})),RS=/*#__PURE__*/ Qx(e=>gS(new Ty(!1,[e.ast],[e.ast]),{value:e}));function zS(e,t){return gS(e,{members:t,mapMembers(e,t){let n=e(this.members);return zS(Hy(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function G(e,t){return zS(Hy(e,t,void 0),e)}function BS(e){let t=e.map(SS);return gS(Hy(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return G(e(this.members))},pick(e){return BS(e)},transform(e){return G(t.map((t,n)=>t.transform(e[n])))}})}const VS=/*#__PURE__*/ Qx(e=>G([e,DS])),HS=/*#__PURE__*/ Qx(e=>G([e,dae]));function US(e,t){return n=>gS(Eb(n.ast,e.ast,t?Rv(t):Uv()),{from:n,to:e})}function WS(){return(e,t)=>eC()(e,{decode:t,encode:gv})}const GS=/*#__PURE__*/ BS([`true`,`yes`,`on`,`1`,`y`]),KS=/*#__PURE__*/ BS([`false`,`no`,`off`,`0`,`n`]),qS=/*#__PURE__*/ BS([...GS.literals,...KS.literals]).pipe(/*#__PURE__*/ US(kS,/*#__PURE__*/ Bv({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function JS(e){return t=>US(bS(t),e)(t)}function YS(e){return t=>gS(Wre(t.ast,e),{schema:t})}function XS(e){return zp(e,e=>Ep(()=>bd(e,e=>e.issue)))}function fae(e,t){let n=t?.encodingStrategy===`omit`?Cv():vv();return t=>yS(xS(t)).pipe(US(t,{decode:wv(XS(e)),encode:n}))}function ZS(e){return SS(e).pipe(YS(N(e)))}function QS(e,t){return U({_tag:ZS(e),...t})}function $S(){return e=>e}function pae(e,t){return rS(t=>t instanceof e,t)}function eC(){return(e,t)=>new cy(e.ast,Rv(t))}const tC=ob,nC=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function mae(e){let t=new globalThis.RegExp(nC);return tC(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:nC,flags:``}]},...e})}function rC(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${zn(n)})`:`new RegExp(${zn(n)}, ${zn(r)})`;return cb(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const iC=/*#__PURE__*/ gS(sb);function aC(e){let t=Di(e.order),n=e.formatter??zn;return(r,i)=>tC(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 oC(e){let t=Di(e.order),n=Ei(e.order),r=Lee(e.order),i=Iee(e.order),a=e.formatter??zn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return tC(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 sC(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${zn(e)}`);return e}const cC=/*#__PURE__*/ aC({order:Ti,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:sC(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${zn(e)})`})})}),lC=/*#__PURE__*/ oC({order:Ti,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:sC(e.minimum),maximum:sC(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${zn(e.minimum)}, maximum: ${zn(e.maximum)}, exclusiveMinimum: ${zn(t)}, exclusiveMaximum: ${zn(n)} })`})}}});function uC(e){return tC(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}const dC=/*#__PURE__*/ OS.check(/*#__PURE__*/ uC());function fC(e,t){return e=gC(e),pC(e,Math.ceil(e/2),t)}function pC(e,t,n){return tC(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})`}),[h_]:!0,arbitraryConstraint:{minLength:e},...n})}function mC(e){return pC(1,1,e)}function hC(e,t){return e=gC(e),tC(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})`}),[h_]:!0,arbitraryConstraint:{maxLength:e},...t})}function gC(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function _C(e,t){return e=gC(e),tC(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})`}),[h_]:!0,arbitraryConstraint:{minProperties:e},...t})}function vC(e){return tC(e=>Qee(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:k},...e})}const yC=/*#__PURE__*/ H.check(/*#__PURE__*/ mC()),bC=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),xC=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},SC=[];function CC(e){let t=bC(e),n=SC[t];if(n!==void 0)return n;let r=QC.pipe(US(ES,hre(xC(t))));return SC[t]=r,r}globalThis.RegExp,globalThis.URL;const wC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function TC(e,t){return wC.pipe(US(e,gre(t)))}const EC=/*#__PURE__*/ TC(ES);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const DC=/*#__PURE__*/ H.check(/*#__PURE__*/ mae()),OC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ US(DC,/*#__PURE__*/ Vv())),kC=/*#__PURE__*/ H.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),AC=/*#__PURE__*/ pae(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>eC()(kC,Qv)}),jC=/*#__PURE__*/ kC.pipe(/*#__PURE__*/ US(AC,Qv));function MC(e,t){let n=nS()([e,t],([e,t])=>(n,r,i)=>{if(!zne(n))return L(new V_(r,n,i));switch(n._tag){case`Fail`:return Zm(lx(e)(n.error,i),{onSuccess:_d,onFailure:e=>U_(r,`error`,e,n,i)});case`Die`:return Zm(lx(t)(n.defect,i),{onSuccess:vd,onFailure:e=>U_(r,`defect`,e,n,i)});case`Interrupt`:return N(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])=>eC()(G([U({_tag:SS(`Fail`),error:e}),U({_tag:SS(`Die`),defect:t}),U({_tag:SS(`Interrupt`),fiberId:HS(iC)})]),Bv({decode:e=>{switch(e._tag){case`Fail`:return _d(e.error);case`Die`:return vd(e.defect);case`Interrupt`:return yd(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 gS(n.ast,{error:e,defect:t})}function NC(e,t){let n=nS()([e,t],([e,t])=>{let n=W(MC(e,t));return(e,t,r)=>Rne(e)?Zm(lx(n)(e.reasons,r),{onSuccess:md,onFailure:n=>U_(t,`failures`,n,e,r)}):L(new V_(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])=>eC()(W(MC(e,t)),Bv({decode:md,encode:({reasons:e})=>e}))});return gS(n.ast,{error:e,defect:t})}const PC=/*#__PURE__*/ zv({decode:(e,t)=>Ni(Wh(e),{onNone:()=>L(new H_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>N(Gh(e))}),encode:e=>N(qh(e))});function FC(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 IC(e,t){return dC.check(lC({minimum:e,maximum:t}))}const LC=/*#__PURE__*/ rS(e=>Bh(e)&&Vh(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]=FC(e,-864e13,864e13);return WS()(IC(t,n),yv(Uh))},toCodecJson:()=>eC()(H,PC),toFormatter:()=>e=>e.toString()}),RC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ US(LC,PC)),zC=/*#__PURE__*/ rS(lo,{representation:{id:`effect/schema/Duration`,payload:null},toCode:()=>({runtime:`Schema.Duration`,Type:`Duration.Duration`,importDeclarations:[`import * as Duration from "effect/Duration"`]}),expected:`Duration`,toCodecJson:()=>eC()(G([U({_tag:SS(`Infinity`)}),U({_tag:SS(`NegativeInfinity`)}),U({_tag:SS(`Nanos`),value:AS}),U({_tag:SS(`Millis`),value:dC})]),Bv({decode:e=>{switch(e._tag){case`Infinity`:return mo;case`NegativeInfinity`:return ho;case`Nanos`:return go(e.value);case`Millis`:return _o(e.value)}},encode:e=>{switch(e.value._tag){case`Infinity`:return{_tag:`Infinity`};case`NegativeInfinity`:return{_tag:`NegativeInfinity`};case`Nanos`:return{_tag:`Nanos`,value:e.value.nanos};case`Millis`:return{_tag:`Millis`,value:e.value.millis}}}}))});function BC(e,t,n){let r=nS()([e,t,n],([e,t,n])=>{let r=NC(t,n);return(t,n,i)=>{if(!zd(t))return L(new V_(n,t,i));switch(t._tag){case`Success`:return Zm(lx(e)(t.value,i),{onSuccess:Bd,onFailure:e=>U_(n,`value`,e,t,i)});case`Failure`:return Zm(lx(r)(t.cause,i),{onSuccess:Vd,onFailure:e=>U_(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])=>eC()(G([U({_tag:SS(`Success`),value:e}),U({_tag:SS(`Failure`),cause:NC(t,n)})]),Bv({decode:e=>e._tag===`Success`?Bd(e.value):Vd(e.cause),encode:e=>Kd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return gS(r.ast,{value:e,error:t,defect:n})}function VC(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:lx(SS(n)),o=nS()([e],([e])=>(t,n,r)=>{if(Fg(t)){let i=a===void 0?F:Xm(a(t.label,r),e=>new L_([`label`],e));return Qm(i,()=>Zm(lx(e)(Rg(t),r),{onSuccess:e=>Ig(e,{label:t.label}),onFailure:()=>new B_(n,[new L_([`value`],new H_(void 0,t,r))],t,r)}))}return L(new V_(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}, ${zn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>eC()(e,{decode:yv(e=>Ig(e,{label:n})),encode:r?hv(e=>`Cannot serialize Redacted`+(Mi(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):yv(Rg)}),toEquivalence:([e])=>zg(e)});return gS(o.ast,{value:e})}const hae=/*#__PURE__*/ globalThis.Symbol.for(`immer-draftable`),HC={};function UC(e,t,n,r,i){let a=_ae(n,t,r),o=WC(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===HC?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:HC,value:i}})}static[tS]=tS;get[o](){return o}static[hae]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return bt(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return sx(a(this))(e??{},t)}static makeOption(e,t){return ox(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(hb(this.ast,e))}static annotateKey(e){return this.rebuild(wb(this.ast,e))}static check(...e){return this.rebuild(_b(this.ast,e))}static extend(e){return(t,r)=>{let a=GC(t)?t:U(t),o={...n.fields,...a.fields},s=zy(o,n.ast.checks,{identifier:e});return UC(this,e,MS(_b(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 gae(e){return new Iv(yv(t=>new e(t,{"~payload":{token:HC,value:t}})),vv())}function WC(e){return`~effect/Schema/Class/${e}`}function _ae(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=WC(t),o=e=>e instanceof i||A(e,a),s=gae(i);return r=US(gS(new py([e.ast],()=>(e,t,n)=>o(e)?N(e):L(new V_(t,e,n)),{identifier:t,[v_]:([e])=>({isConstructed:o,link:new cy(e,s)}),toCodec:([e])=>new cy(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[__]:Gy(e.ast),...n})),s)(e)}}function GC(e){return _S(e)}const KC=e=>(t,n)=>{let r=GC(t)?t:U(t);return UC(Io,e,r,n,e=>({toString(){return`${e}(${zn({...this})})`}}))},qC=e=>(t,n)=>{let r=GC(t)?t:U(t);return UC(Xr,e,r,n,e=>({name:e}))},JC=e=>(t,n,r)=>{let i=GC(n)?n.mapFields(e=>({_tag:ZS(t),...e}),{unsafePreserveChecks:!0}):QS(t,n);return qC(e??t)(i,r)};function vae(e,t){return Qie(tae(kx(e.ast),t),t)}const YC=Iie,XC=zie,ZC=Bie,QC=/*#__PURE__*/ gS(/*#__PURE__*/ hb(Jb,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),K=/*#__PURE__*/ PS(H,QC),yae=/*#__PURE__*/ gS(/*#__PURE__*/ hb(oie,{toCode:()=>({runtime:`Schema.MutableJson`,Type:`Schema.MutableJson`})}));function $C(){return Object.assign(e=>e,{option:e=>ki(e),result:e=>Sa(e),is:e=>!0})}const ew=`~effect/MutableHashMap`,bae={[ew]:ew,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${zn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:Xn(Array.from(this))}},[Yn](){return this.toJSON()},pipe(){return bt(this,arguments)}},xae=()=>{let e=Object.create(bae);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},tw=/*#__PURE__*/ O(2,(e,t)=>{if(e.backing.has(t))return ki(e.backing.get(t));if(nw(t))return Oi();let n=tn(t),r=e.buckets.get(n);return r===void 0?Oi():Sae(e,r,t)}),nw=e=>typeof e!=`object`&&typeof e!=`function`,Sae=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(bn(n,t[r])){let n=t[r];return ki(e.backing.get(n))}return Oi()},Cae=/*#__PURE__*/ O(3,(e,t,n)=>{if(e.backing.has(t)||nw(t))return e.backing.set(t,n),e;let r=tn(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=wae(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),wae=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(bn(t,e[n]))return e[n]},rw=/*#__PURE__*/ O(2,(e,t)=>{if(nw(t))return e.backing.delete(t),e;let n=tn(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||bn(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Tae=e=>(e.backing.clear(),e.buckets.clear(),e),Eae=e=>e.backing.size,iw=ac,aw=oc,ow=Ys,sw=wne,cw=Ou,lw=ku,uw=`~effect/MutableRef`,dw={[uw]:uw,...gr,toJSON(){return{_id:`MutableRef`,current:Xn(this.current)}}},fw=e=>{let t=Object.create(dw);return t.current=e,t},pw=/*#__PURE__*/ O(2,(e,t)=>(e.current=t,e)),mw=/*#__PURE__*/ Symbol.for(`effect/MutableList/Empty`),hw=()=>({head:void 0,tail:void 0,length:0}),gw=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})},_w=()=>({array:[],mutable:!0,offset:0,next:void 0}),vw=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=_w(),e.tail=e.tail.next):e.head=e.tail=_w(),e.tail.array.push(t),e.length++},yw=(e,t)=>{e.head={array:[t],mutable:!0,offset:0,next:e.head},e.tail||=e.head,e.length++},bw=(e,t)=>xw(e,Va(t),!Array.isArray(t)),xw=(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},Sw=e=>{e.head=e.tail=void 0,e.length=0},Cw=(e,t)=>{if(t=xa(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 Sw(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?Sw(e):gw(e),n;i=i.next}return Sw(e),n},ww=e=>Cw(e,e.length),Tw=e=>{if(!e.head)return mw;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:Sw(e):gw(e),t},Ew=(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}if(n.length===0){Sw(e);return}e.head=e.tail={array:n,mutable:!0,offset:0,next:void 0},e.length=n.length},Dw=(e,t)=>Ew(e,e=>e!==t),Ow=e=>P(()=>Ww(e.atomicPubSub(),/* @__PURE__ */ new Map,gf(),cw(!1),fw(!1),e.strategy(),fw(Oi()))),kw=e=>Ow({atomicPubSub:()=>Aw(e),strategy:()=>new Gw}),Aw=e=>{let t=e?.replay;return new Bw(t&&t>0?new Jw(Math.ceil(t)):void 0)},jw=/*#__PURE__*/ O(2,(e,t)=>Sp(()=>e.shutdownFlag.current||Mi(e.ended.current)?N(!1):e.pubsub.publish(t)?(e.strategy.completeSubscribersUnsafe(e.pubsub,e.subscribers),N(!0)):e.strategy.handleSurplus(e.pubsub,e.subscribers,[t],e.shutdownFlag,e.ended))),Mw=e=>wm(nm(t=>{let n=da(t,mf),r=xf(e.scope),i=zw(e.pubsub,e.subscribers,e.strategy,e.ended);return yf(r,Nw(i)).pipe(jp(vf(n,e=>Sf(r,e))),Fp(i))})),Nw=e=>wm(kp(t=>(pw(e.shutdownFlag,!0),_p(ww(e.pollers),e=>of(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(Mp(()=>P(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),mre(e.shutdownHook.open),Ip)))),Pw=e=>Sp(()=>{if(e.shutdownFlag.current)return xm;if(e.replayWindow.remaining>0){let t=e.replayWindow.take();return N(t)}let t=e.pollers.length===0?e.subscription.poll():mw;return t===mw?Fw(e):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),N(t))}),Fw=e=>Cp(t=>{if(e.shutdownFlag.current)return t(xm);if(Mi(e.ended.current)){let n=e.pollers.length===0?e.subscription.poll():mw;return n===mw?t(N(e.ended.current.value)):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),t(N(n)))}let n=ef(),r=e.subscribers.get(e.subscription);return r||(r=/* @__PURE__ */ new Set,e.subscribers.set(e.subscription,r)),r.add(e.pollers),vw(e.pollers,n),e.strategy.completePollersUnsafe(e.pubsub,e.subscribers,e.subscription,e.pollers),n.effect?t(n.effect):(n.resumes=[t],P(()=>Dw(e.pollers,n)))}),Iw=/*#__PURE__*/ Symbol.for(`effect/PubSub/AbsentValue`),Lw=(e,t,n)=>{e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(n)},Rw=(e,t,n)=>{if(!e.has(t))return;let r=e.get(t);r.delete(n),r.size===0&&e.delete(t)},zw=(e,t,n,r)=>new Hw(e,t,e.subscribe(),hw(),cw(!1),fw(!1),n,e.replayWindow(),r);var Bw=class{publisherHead={value:Iw,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 Yw(this.replayBuffer):Xw}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=Iw,this.subscribersIndex+=1,this.replayBuffer?.slide(t,e.replayIndex)}}subscribe(){return this.publisherTail.subscribers+=1,new Vw(this,this.publisherTail,this.publisherIndex,!1)}},Vw=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===Iw?(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 mw;let e=!0,t=mw;for(;e;)if(this.subscriberHead===this.self.publisherTail)e=!1;else{let n=this.subscriberHead.next.value;n!==Iw&&(t=n,--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=Iw,this.self.subscribersIndex+=1),e=!1),this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return t}pollUpTo(e){e=xa(e);let t=[],n=0;for(;n!==e;){let r=this.poll();r===mw?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!==Iw&&(--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=Iw,this.self.subscribersIndex+=1)),this.subscriberHead=this.subscriberHead.next}},Hw=class{"~effect/PubSub/Subscription"={_A:k};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 bt(this,arguments)}},Uw=class{"~effect/PubSub"={_A:k};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 bt(this,arguments)}};const Ww=(e,t,n,r,i,a,o)=>new Uw(e,t,n,r,i,a,o);var Gw=class{get shutdown(){return F}handleSurplus(e,t,n,r){return N(!1)}onPubSubEmptySpaceUnsafe(e,t){}completePollersUnsafe(e,t,n,r){return Kw(this,e,t,n,r)}completeSubscribersUnsafe(e,t){return qw(this,e,t)}};const Kw=(e,t,n,r,i)=>{let a=!0;for(;a&&!r.isEmpty();){let o=Tw(i);if(o===mw)Rw(n,r,i),i.length===0?a=!1:Lw(n,r,i);else{let a=r.poll();a===mw?yw(i,o):(uf(o,Bd(a)),e.onPubSubEmptySpaceUnsafe(t,n))}}},qw=(e,t,n)=>{for(let[r,i]of n)for(let a of i)e.completePollersUnsafe(t,n,r,a)};var Jw=class{capacity;head={value:Iw,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:Iw,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)}},Yw=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]=Iw,this.index=(this.index+1)%this.values.length,this.remaining--,this.remaining===0&&this.close(),e}takeN(e){e=xa(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 Xw={remaining:0,take:()=>void 0,takeN:()=>[],takeAll:()=>[],close:()=>void 0},Zw={_A:k,_E:k},Qw={"~effect/Queue":Zw,"~effect/Queue/Enqueue":Zw,"~effect/Queue/Dequeue":Zw,...gr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:vT(this)}}},$w=e=>Jr(t=>{let n=Object.create(Qw);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=hw(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Set,awaiters:/* @__PURE__ */ new Set},lc(n)}),eT=e=>$w({capacity:e}),tT=e=>$w({capacity:e,strategy:`dropping`}),nT=/*#__PURE__*/ O(2,(e,t)=>pc(()=>rT(e,t)?bT:e.state._tag===`Open`&&e.strategy===`suspend`?kT(e,t):yT)),rT=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Tw(e.messages),vw(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(vw(e.messages,t),CT(e),!0):(vw(e.messages,t),wT(e),!0):!1,iT=/*#__PURE__*/ O(2,(e,t)=>kc(n=>{let r=aT(e,t);return r.length===0||e.strategy===`dropping`?n(Hr(r)):AT(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),aT=(e,t)=>{if(e.state._tag!==`Open`)return Va(t);if(e.capacity===1/0||e.strategy===`sliding`)return bw(e.messages,t),e.strategy===`sliding`&&Cw(e.messages,e.messages.length-e.capacity),wT(e),[];let n=e.capacity<=0?e.state.takers.size:e.capacity-e.messages.length;if(n===0)return Va(t);let r=[],i=0;for(let a of t)i<n?vw(e.messages,a):r.push(a),i++;return wT(e),r},oT=/*#__PURE__*/ O(2,(e,t)=>fc(()=>sT(e,t))),sT=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Gr(t),r=Nte(n,xT);return e.state.offers.size===0&&e.messages.length===0?(PT(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},wT(e),!0)},cT=e=>oT(e,jr(ii())),lT=e=>sT(e,jr(ii())),uT=e=>fc(()=>dT(e)),dT=e=>{if(e.state._tag===`Done`)return!1;Sw(e.messages);let t=e.state.offers;PT(e,e.state._tag===`Open`?ST:e.state.exit);for(let e of t)jT(e);return!0},fT=e=>mT(e,1,1/0),pT=e=>pc(()=>{let t=Ka();return Rc(up(lu({while:wt,body:Ct(fT(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>Sc),t)}),mT=/*#__PURE__*/ O(3,(e,t,n)=>(t=xa(t),n=xa(n),ET(()=>TT(e,t,n)??Kc(OT(e,()=>DT(e,t)),mT(e,t,n))))),hT=e=>ET(()=>_T(e)??Kc(OT(e,()=>DT(e,1)),hT(e))),gT=e=>ET(()=>{let t=_T(e);return t===void 0?lc(Oi()):t._tag===`Success`?lc(ki(t.value)):lc(Oi())}),_T=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Tw(e.messages);return NT(e),Hr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=MT(e.state.offers);return NT(e),Hr(t)}},vT=e=>e.state._tag===`Done`?0:e.messages.length,yT=/*#__PURE__*/ Hr(!1),bT=/*#__PURE__*/ Hr(!0),xT=/*#__PURE__*/ Kr(/*#__PURE__*/ ii()),ST=/*#__PURE__*/ $c(),CT=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(nl),e.messages.length===0))break}},wT=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,CT(e)},0))},TT=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Hr([]);if(!DT(e,t))return;let r=e.messages.length>0?Cw(e.messages,n):[MT(e.state.offers)];return NT(e),Hr(r)},ET=/*#__PURE__*/ Br({op:`QueueTake`,[dr](e){let t=this[ur]();return vr(t)?t[dr](e):t}}),DT=(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,OT=(e,t)=>kc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(nl);let r={ready:t,resume:n};return e.state.takers.add(r),fc(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),kT=(e,t)=>kc(n=>rT(e,t)?n(bT):AT(e,{_tag:`Single`,message:t,resume:n})),AT=(e,t)=>{if(e.state._tag!==`Open`)return jT(t);let n=e.state.offers;return n.add(t),fc(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&PT(e,e.state.exit))})},jT=e=>e._tag===`Single`?e.resume(yT):e.resume(Hr(e.remaining.slice(e.offset))),MT=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(bT),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Hr([]))),n},NT=e=>{if(e.state._tag===`Done`)return dp(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(PT(e,e.state.exit),dp(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`)vw(e.messages,t.message),e.state.offers.delete(t),t.resume(bT);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;vw(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Hr([]))}let r=e.state;if(r._tag===`Done`)return dp(r.exit.cause)}return!1},PT=(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()},FT=e=>new LT(e),IT=(e,t,n)=>kc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),fc(()=>{e.waiters.delete(i)})});var LT=class{waiters=/*#__PURE__*/ new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=pc(()=>this.free<e?IT(this,e,t):(this.taken+=e,lc(e)));return t}takeIfAvailable(e){return pc(()=>this.free<e?lc(!1):(this.taken+=e,lc(!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 Jr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Sc))}release(e){return Jr(t=>lc(this.releaseUnsafe(t,e)))}get releaseAll(){return Jr(e=>lc(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>cu(n=>{let r=pc(()=>{if(this.free<e){let t=IT(this,e,Sc);return Xc(n(t),()=>r)}return this.taken+=e,Wl(n(t),()=>{this.releaseUnsafe(Ys(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>cu(n=>this.free<e?vc:(this.taken+=e,Wl(n(Gc(t)),()=>{this.releaseUnsafe(Ys(),e)},!0)))}};const RT=e=>fc(()=>new LT(e)),zT=`~effect/Channel`,BT=e=>A(e,zT),VT={[zT]:{_Env:k,_InErr:k,_InElem:k,_OutErr:k,_OutElem:k},pipe(){return bt(this,arguments)}},HT=e=>{let t=Object.create(VT);return t.transform=(t,n)=>zp(e(t,n),e=>N(Tp(e))),t},UT=(e,t)=>HT((n,r)=>R(KT(e)(n,r),e=>t(e,r))),WT=e=>HT((t,n)=>e),GT=e=>HT(B(function*(t,n){let r=xf(n),i=e=>Sf(r,mp(e)),a=yield*gm(e(t,n,r),i);return gm(a,i)})),KT=e=>e.transform,qT=(e,t,n)=>$w({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(Mp(t=>yf(e,uT(t))),Mp(n=>_f(t(n),e).pipe(zp(e=>oT(n,e)),Nm(e)))),JT=(e,t)=>HT((n,r)=>z(qT(r,e,t),fT)),YT=e=>HT((t,n)=>Sp(()=>KT(e())(t,n))),XT=e=>WT(P(()=>{let t=e();return Sp(()=>{let e=t.next();return e.done?Md(e.value):N(e.value)})})),ZT=e=>nE(N(e)),QT=/*#__PURE__*/ WT(/*#__PURE__*/ N(/*#__PURE__*/ Md())),$T=e=>WT(N(L(e))),eE=e=>WT(Tp(e)),tE=e=>eE(gd(e)),nE=e=>WT(P(()=>{let t=!1;return Sp(()=>t?Md():(t=!0,e))})),rE=e=>WT(R(e,()=>Md())),iE=e=>WT(N(fT(e))),aE=e=>HT((t,n)=>oE({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),oE=e=>{let t=e.readable.getReader(),n=e.exit??fw(void 0),r=Sp(()=>n.current?n.current:$p(bp({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Tp(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Md():N(qa(t))}));return Fp(yf(e.scope,e.releaseLockOnEnd?P(()=>t.releaseLock()):yp(()=>t.cancel().catch(Dt))),r)},sE=/*#__PURE__*/ O(2,(e,t)=>UT(e,e=>P(()=>{let n=0;return z(e,e=>t(e,n++))}))),cE=/*#__PURE__*/ O(2,(e,t)=>lE(e,e=>N(t(e)))),lE=/*#__PURE__*/ O(2,(e,t)=>UT(e,e=>N(up(e,e=>R(t(e),Md))))),uE=e=>e===void 0||e!==`unbounded`&&e<=1,dE=/*#__PURE__*/ O(e=>BT(e[0]),(e,t,n)=>uE(n?.concurrency)?fE(e,t):pE(e,t,n)),fE=(e,t)=>HT((n,r)=>{let i=0;return z(KT(e)(n,r),R(e=>t(e,i++)))}),pE=(e,t,n)=>GT(B(function*(r,i,a){let o=0,s=yield*KT(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*eT(0);yield*yf(a,uT(l));let u=Im(yield*tm()),d=sw(a);if(n.unordered){let e=FT(c),n=Ct(e.release(1)),r=$p({onFailure:e=>R(oT(l,e),n),onSuccess:e=>R(nT(l,e),n)});yield*e.take(1).pipe(R(()=>s),R(e=>{let n=o++;return d(u(r(Sp(()=>t(e,n))))),F}),Em({disableYield:!0}),zp(t=>e.withPermits(c-1)(oT(l,t))),Nm(a))}else{let e=yield*eT(c-2);yield*yf(a,uT(e)),yield*hT(e).pipe(ore,R(e=>nT(l,e)),Em({disableYield:!0}),zp(e=>oT(l,e)),Nm(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,sT(l,e.cause))};yield*s.pipe(R(i=>{if(n)return Tp(n);let a=o++,s=u(Sp(()=>t(i,a)));return d(s),s.addObserver(r),nT(e,iw(s))}),Em({disableYield:!0}),zp(t=>nT(e,Vd(t)).pipe(jp(oT(e,t)))),Nm(a))}return hT(l)})),Dae=/*#__PURE__*/ O(e=>BT(e[0]),(e,t,n)=>uE(n?.concurrency)?Oae(e,t):kae(e,t,n)),Oae=(e,t)=>HT((n,r)=>z(KT(e)(n,r),e=>{let i,a,o=R(e,e=>(a??=xf(r),Qm(KT(t(e))(n,a),e=>(i=s(e),i)))),s=up(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Sf(a,Gd);return a=void 0,R(t,()=>o)});return Sp(()=>i??o)})),kae=(e,t,n)=>e.pipe(sE(t),Fae(n)),Aae=e=>Dae(e,k),jae=e=>UT(e,e=>{let t,n=0,r=Sp(function r(){if(t===void 0)return R(e,e=>{switch(e.length){case 0:return r();case 1:return N(e[0]);default:return t=e,N(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),N(i)});return N(r)}),mE=/*#__PURE__*/ O(2,(e,t)=>HT((n,r)=>{let i=xf(r);return z(KT(e)(n,i),e=>{let a=e.pipe(zp(e=>{if(dp(e))return Tp(e);let o=i;return i=xf(r),Sf(o,Vd(e)).pipe(jp(KT(t(e))(n,i)),R(e=>(a=e,e)))}));return Sp(()=>a)})})),Mae=/*#__PURE__*/ O(2,(e,t)=>mE(e,e=>rE(R(t(e),t=>Tp(e))))),Nae=/*#__PURE__*/ O(3,(e,t,n)=>mE(e,e=>{let r=t(e);return Ea(r)?eE(r.failure):n(r.success,e)})),hE=/*#__PURE__*/ O(2,(e,t)=>Nae(e,wd,e=>t(e))),Pae=e=>hE(e,tE),Fae=/*#__PURE__*/ O(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>GT(B(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:FT(s),l=yield*lw(!0),u=/* @__PURE__ */ new Set,d=yield*eT(t);yield*yf(o,uT(d));let f=yield*KT(e)(i,a);return yield*I(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*Mm(f),yield*Xp(c.take(1),jp(iw(e),wp))));let t=e===void 0?yield*f:yield*iw(e),n=xf(o),r=yield*KT(t)(i,n);for(;u.size>=s;){let e=Na(u);u.delete(e),u.size===0&&(yield*l.open),yield*aw(e)}let a=yield*r.pipe(Mp(()=>ire),R(e=>nT(d,e)),Em({disableYield:!0}),gm(B(function*(e){let t=mp(e),r=yield*Pp(Sf(n,t));if(!u.has(a))return;let i=Yd([t,r]);qd(i)&&(yield*oT(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),Mm);l.closeUnsafe(),u.add(a)}}).pipe(zp(e=>{let t=pp(e);return Da(t)?l.whenOpen(oT(d,e)):oT(d,e)}),Nm(o)),hT(d)}))),Iae=/*#__PURE__*/ O(e=>BT(e[0])&&BT(e[1]),(e,t,n)=>GT(B(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*eT(0);yield*yf(a,uT(s));let c=0;function l(e,t){if(c++,!dp(t))return oT(s,t);switch(o){case`both`:return c===2?oT(s,t):F;case`left`:case`right`:return e===o?oT(s,t):F;case`either`:return oT(s,t)}}let u=(e,t,n)=>KT(t)(r,n).pipe(R(e=>e.pipe(R(e=>nT(s,e)),Em)),gm(t=>_m(mp(t),e=>Sf(n,e)).pipe($p({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Nm(a));return yield*u(`left`,e,xf(a)),yield*u(`right`,t,xf(a)),hT(s)}))),Lae=()=>HT((e,t)=>P(()=>{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(`
|
|
11
|
+
`)},Ls=(e,t)=>{let n=t?.get(Hr.key);return n&&(e=`${e}\n${zs(n)}`),e},Rs=(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(Ur.key);n.push(` at fiber (${t})`),r&&n.push(zs(r))}return n.join(`
|
|
12
|
+
`)},zs=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Fs),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
|
+
`)},Bs=e=>Ms(e).map(Vs).join(`
|
|
14
|
+
`),Vs=e=>e.cause?`${e.stack} {\n${Hs(e.cause,` `)}\n}`:e.stack,Hs=(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${Hs(e.cause,`${t} `)}\n${t}}`),r},Us=`~effect/Fiber`,Ws={_A:k,_E:k},Gs={id:0},Ks=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),qs=()=>Ks===void 0?void 0:new Ks(`effect/Fiber`),Js=()=>globalThis[Fn];var Ys=class{constructor(e,t=!0){this.setContext(e),this.id=++Gs.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[Us](){return Ws}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return la(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Dt):(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=bs(e);this.cache.stackFrame&&(n=Nr(n,na(Hr,this.cache.stackFrame))),t&&(n=Nr(n,t)),this._interruptedCause=this._interruptedCause?Or(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(lc(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===mr){this._asyncContext=qs();return}let n=$s.interruptChildren&&$s.interruptChildren(this);if(n!==void 0)return this.evaluate(Xc(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=ea()}runLoop(e){let t=globalThis[Fn];globalThis[Fn]=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=lc(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Xc(hc,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[ur](this),i===mr){let e=this._yielded;if(sr in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return mr}}catch(e){if(!A(i,ur))return Kr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=Kr(e)}}finally{this._running=n,globalThis[Fn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Zs;for(;;){let t=this._stack.pop();if(!t)return;let n=t[pr];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&Qs-1))return Vr(e);let t=this.getCont(dr);return t?t[dr](e,this):this.yieldWith(Vr(e))}yieldWith(e){return this._yielded=e,mr}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return bt(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Uee(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Xs(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 Xs=e=>{let t=sa(e,ts);return{scheduler:la(e,Eo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:la(e,ss),span:sa(e,Jo),logLevel:la(e,fs),minimumLogLevel:la(e,ps),stackFrame:la(e,os),runtimeMetrics:sa(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:la(e,No),preventYield:la(e,Po)}},Zs={[dr](e,t){return lc(t._interruptedCause)},[fr](e,t){return lc(t._interruptedCause)}},Qs=32,$s={interruptChildren:void 0},ec=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(Ur.key,e.cache.stackFrame),Xi(t)},tc=e=>{if(e._children!==void 0&&e._children.size!==0)return sc(e._children)},nc=e=>{let t=e;return t._exit?cc(t._exit):Oc(n=>t._exit?n(cc(t._exit)):dc(e.addObserver(e=>n(cc(e)))))},rc=e=>Oc(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();continue}i=e.value.addObserver(e=>{r.push(e),a()});return}t(cc(r))}return a(),dc(()=>i?.())}),ic=e=>{let t=e;return t._exit?t._exit:Oc(n=>t._exit?n(t._exit):dc(e.addObserver(n)))},ac=e=>qr(t=>oc(e,t.id)),oc=/*#__PURE__*/ O(e=>A(e[0],Us),(e,t,n)=>qr(r=>{let i=ec(r);return i=i&&n?ma(i,n):i??n,e.interruptUnsafe(t,i),Jc(nc(e))})),sc=e=>qr(t=>{let n=ec(t),r=Ka();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Jc(rc(r))}),cc=Vr,lc=Wr,uc=Gr,dc=/*#__PURE__*/ zr({op:`Sync`,[ur](e){let t=this[lr](),n=e.getCont(dr);return n?n[dr](t,e):e.yieldWith(Vr(t))}}),fc=/*#__PURE__*/ zr({op:`Suspend`,[ur](e){return this[lr]()}}),pc=/*#__PURE__*/ O(e=>e.length>=2||zee(e[0]),(e,t)=>ki(e)?uc(t?t():new $r(`Effect.fromOption: Option.none`)):cc(e.value)),mc=/*#__PURE__*/ Oa({onFailure:uc,onSuccess:cc}),hc=/*#__PURE__*/ (/* @__PURE__ */ zr({op:`Yield`,[ur](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(nl)},this[lr]??0),e.yieldWith(()=>{t=!0})}}))(0),gc=e=>cc(Oi(e)),_c=/*#__PURE__*/ cc(/*#__PURE__*/ Di()),vc=e=>fc(()=>lc(e())),yc=e=>Kr(e),bc=e=>fc(()=>uc(e())),xc=/*#__PURE__*/ cc(void 0),Sc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new od(e,`An error occurred in Effect.try`):e.catch;return fc(()=>{try{return cc(t())}catch(e){return uc(n(e))}})},Cc=e=>Ec(function(t,n){e(n).then(e=>t(cc(e)),e=>t(yc(e)))},e.length!==0),wc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new od(e,`An error occurred in Effect.tryPromise`):e.catch;return Ec(function(e,r){let i=e=>fc(()=>{try{return uc(rr(()=>n(e)))}catch(e){return yc(e)}});try{t(r).then(t=>e(cc(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},Tc=e=>qr(t=>e(t.id)),Ec=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Rr({op:`Async`,[ur](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(Dc(()=>(t=!0,r?.abort(),i??nl))),mr):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Dc=/*#__PURE__*/ zr({op:`AsyncFinalizer`,[pr](e){e.interruptible&&(e.interruptible=!1,e._stack.push(ru))},[fr](e,t){return Ts(e)?Xc(kl(Wr(e),this[lr]()),()=>lc(e)):lc(e)}}),Oc=e=>Ec(e,e.length>=2),kc=/*#__PURE__*/ Oc(Dt),Ac=(...e)=>{if(e.length===1){let t=e[0];return fc(()=>Lc(t()))}let[t,n]=e;return fc(()=>Lc(n.call(t.self)))},jc=(e,...t)=>{let n=t.length===0?function(){return fc(()=>Lc(e.apply(this,arguments)))}:function(){let n=fc(()=>Lc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Mc(e.length,n)},Mc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Nc=/*#__PURE__*/ gs(2),Pc=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)=>Fc(t,r,i,a,e,n):Fc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Fc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Nc(()=>n.stack):Et;return Mc(o.length,function(...t){let n=fc(()=>{let e=o.apply(this,arguments);return gr(e)?e:Lc(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!gr(n))return n;let l=er(),u;return l!==0&&(tr(2),u=new globalThis.Error,tr(l)),al(i?Ru(e,a,e=>zu(n,e)):n,os,t=>({name:e,stack:u?Nc(()=>u.stack):Et,parent:{name:s,stack:c,parent:t}}))})},pte=(e,...t)=>Mc(e.length,t.length===0?function(){return Ic(()=>e.apply(this,arguments))}:function(){let n=Ic(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),Ic=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return cc(r.value);let i=r.value;if(i&&i._tag===`Success`){n=i.value;continue}if(i&&i._tag===`Failure`)return r.value;{let n=!0;return fc(()=>n?(n=!1,Xc(r.value,e=>Lc(t,e))):fc(()=>Lc(e())))}}}catch(e){return yc(e)}},Lc=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Rr({op:`Iterator`,[dr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return cc(r.value);if(!Zc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[ur](e){return this[dr](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)}}(),Rc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,Vc,cc(t))),zc=function(e){return e._stack.push(this),this[lr]},mte=/*#__PURE__*/ Rr({op:`OnSuccess`,[ur]:zc}),Bc=function(e,t,n){this[lr]=e,this[dr]=t,this.payload=n};Bc.prototype=mte;const Vc=function(){return this.payload},Hc=function(e,t){return t.succeedWith(this.payload)},Uc=/*#__PURE__*/ (()=>{let e=`~effect/Effect/stackProbe`;return{[e]:function(){return(/* @__PURE__ */ Error()).stack}}[e]()?.includes(`[as `+e+`]`)===!0})(),hte=function(e,t){let n=this.payload;return t.succeedWith(Uc?n(e):rr(()=>n(e)))},Wc=function(e){let t=this.payload;return t(e)},gte=function(e){let t=this.payload;return new Bc(t(e),Hc,e)},_te=function(e){return new Bc(this.payload,Hc,e)},Gc=e=>Qc(e,Oi),Kc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,gr(t)?Vc:Wc,t)),qc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,gr(t)?_te:gte,t)),Jc=e=>new Bc(e,Vc,nl),vte=(e,t)=>qr(n=>{let r=/* @__PURE__ */ new Set;return Kl(n,()=>r.size===0?void 0:sc(r)),Oc(i=>{let a=Va(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(lc(Er(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=_u(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),yte=(e,t)=>qr(n=>{let r=/* @__PURE__ */ new Set;return Kl(n,()=>r.size===0?void 0:sc(r)),Oc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=_u(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})})}})}),bte=/*#__PURE__*/ O(e=>gr(e[1]),(e,t,n)=>vte([e,t],n)),Yc=/*#__PURE__*/ O(e=>gr(e[1]),(e,t,n)=>yte([e,t],n)),Xc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,Wc,t)),xte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):_l(e,t)),Zc=e=>e[sr]!==void 0,Ste=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e._tag===`Success`?t(e.value):e:Xc(e,t)),Cte=e=>Xc(e,k),Qc=/*#__PURE__*/ O(2,(e,t)=>new Bc(e,hte,t)),wte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?Ate(e,t):Qc(e,t)),Tte=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?jte(e,t):hl(e,t)),Ete=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?Mte(e,t):Xte(e,t)),Dte=/*#__PURE__*/ O(2,(e,t)=>{if(Zc(e)){if(e._tag===`Success`)return e;let n=Ss(e.cause);return wa(n)?e:t(n.success)}return pl(e,t)}),$c=e=>Wr(bs(e)),el=e=>e._tag===`Success`,Ote=e=>e._tag===`Failure`,kte=e=>e._tag===`Failure`?ba(e.cause):xa(e),tl=e=>e._tag===`Failure`&&Ts(e.cause),nl=/*#__PURE__*/ Vr(void 0),Ate=/*#__PURE__*/ O(2,(e,t)=>e._tag===`Success`?Vr(t(e.value)):e),jte=/*#__PURE__*/ O(2,(e,t)=>{if(e._tag===`Success`)return e;let n=Ss(e.cause);return wa(n)?e:Gr(t(n.success))}),Mte=/*#__PURE__*/ O(2,(e,t)=>{if(e._tag===`Success`)return Vr(t.onSuccess(e.value));let n=Ss(e.cause);return wa(n)?e:Gr(t.onFailure(n.success))}),Nte=/*#__PURE__*/ O(2,(e,t)=>el(e)?t:e),rl=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?nl:Wr(Er(t))},Pte=e=>e,Fte=e=>qr(t=>cc(pa(t.context,e))),il=/*#__PURE__*/ O(2,(e,t)=>qr(n=>{let r=n.context,i=t(r);return r===i?e:(n.setContext(i),Kl(n,()=>{n.setContext(r)}),e)})),al=/*#__PURE__*/ O(3,(e,t,n)=>il(e,e=>{let r=ca(e,t),i=n(r);return r===i?e:ra(e,t,i)})),Ite=()=>Lte,Lte=/*#__PURE__*/ qr(e=>cc(e.context)),ol=e=>qr(t=>e(t.context)),Rte=/*#__PURE__*/ O(2,(e,t)=>il(e,Ct(t))),sl=/*#__PURE__*/ O(2,(e,t)=>Zc(e)?e:il(e,ma(t))),cl=function(){return arguments.length===1?O(2,(e,t)=>ll(e,arguments[0],t)):O(3,(e,t,n)=>ll(e,t,n)).apply(this,arguments)},ll=(e,t,n)=>il(e,ra(t,n)),zte=/*#__PURE__*/ O(2,(e,t)=>Xc(t,t=>t?Gc(e):_c)),Bte=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>du({while:wt,body:Ct(t?.disableYield?e:Xc(e,e=>hc)),step:Dt})),ul=/*#__PURE__*/ O(2,(e,t)=>new dl(e,t.length===1?t:e=>t(e))),Vte=/*#__PURE__*/ Rr({op:`OnFailure`,[ur]:zc}),dl=function(e,t){this[lr]=e,this[fr]=t};dl.prototype=Vte;const Hte=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>t(e)?n(e):lc(e))),fl=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>{let r=t(e);return wa(r)?lc(r.failure):n(r.success,e)})),pl=/*#__PURE__*/ O(2,(e,t)=>fl(e,Ss,e=>t(e))),Ute=/*#__PURE__*/ O(2,(e,t)=>fl(e,ws,t)),Wte=/*#__PURE__*/ O(2,(e,t)=>ul(e,e=>Kc(t(e),lc(e)))),Gte=/*#__PURE__*/ O(3,(e,t,n)=>ul(e,e=>{let r=t(e);return wa(r)?lc(e):Kc(n(r.success,e),lc(e))})),Kte=/*#__PURE__*/ O(2,(e,t)=>Gte(e,Ss,e=>t(e))),ml=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n,r)=>ul(e,e=>{let i=Ss(e);return wa(i)?lc(i.failure):t(i.success)?n(i.success):r?r(i.success):lc(e)})),qte=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n,r)=>ul(e,e=>{let i=Ss(e);if(wa(i))return lc(i.failure);let a=t(i.success);return wa(a)?r?r(a.failure):lc(e):n(a.success)})),Jte=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>A(e,`_tag`)&&t.includes(e._tag):Zt(t);return ml(e,i,n,r)}),Yte=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n)=>{let r;return qte(e,e=>(r??=Object.keys(t),A(e,`_tag`)&&It(e._tag)&&r.includes(e._tag)?ba(e):xa(e)),e=>t[e._tag](e),n)}),hl=/*#__PURE__*/ O(2,(e,t)=>pl(e,e=>bc(()=>t(e)))),Xte=/*#__PURE__*/ O(2,(e,t)=>yl(e,{onFailure:e=>bc(()=>t.onFailure(e)),onSuccess:e=>dc(()=>t.onSuccess(e))})),Zte=e=>pl(e,yc),Qte=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>{if(!t?.log)return yl(e,{onFailure:e=>xc,onSuccess:e=>xc});let n=ud(t.log===!0?void 0:t.log);return _l(e,{onFailure(e){let r=xs(e);return wa(r)?lc(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>xc})}),$te=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>{if(!t?.log)return _l(e,{onFailure:e=>xc,onSuccess:e=>xc});let n=ud(t.log===!0?void 0:t.log);return _l(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>xc})}),ene=e=>bl(e,{onFailure:Di,onSuccess:Oi}),gl=e=>ine(e,{onFailure:xa,onSuccess:ba}),_l=/*#__PURE__*/ O(2,(e,t)=>new vl(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),tne=/*#__PURE__*/ Rr({op:`OnSuccessAndFailure`,[ur]:zc}),vl=function(e,t,n){this[lr]=e,this[dr]=t,this[fr]=n};vl.prototype=tne;const nne=function(e,t){let n=this.payload;return t.succeedWith(Uc?n.onSuccess(e):rr(()=>n.onSuccess(e)))},rne=/*#__PURE__*/ ((e,t)=>{let n=Rr({op:e,[ur]:zc,[dr]:nne,[fr]:t}),r=function(e,t){this[lr]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=e.reasons.find(Pr);if(n===void 0)return lc(e);let r=this.payload;return t.succeedWith(Uc?r.onFailure(n.error):rr(()=>r.onFailure(n.error)))}),yl=/*#__PURE__*/ O(2,(e,t)=>_l(e,{onFailure:e=>{let n=e.reasons.find(Pr);return n?t.onFailure(n.error):lc(e)},onSuccess:t.onSuccess})),bl=/*#__PURE__*/ O(2,(e,t)=>new rne(e,t)),ine=/*#__PURE__*/ O(2,(e,t)=>{if(Zc(e)){if(e._tag===`Success`)return Vr(t.onSuccess(e.value));let n=Ss(e.cause);return wa(n)?e:Vr(t.onFailure(n.success))}return bl(e,t)}),xl=e=>Zc(e)?Vr(e):ane(e),ane=/*#__PURE__*/ zr({op:`Exit`,[ur](e){return e._stack.push(this),this[lr]},[dr](e,t,n){return t.succeedWith(n??Vr(e))},[fr](e,t,n){return t.succeedWith(n??Wr(e))}}),one=/*#__PURE__*/ O(2,(e,t)=>Kc(Xu(t),e)),Sl=/*#__PURE__*/ O(2,(e,t)=>Xc(lne(e,t.duration),e=>ki(e)?t.orElse():cc(e.value))),sne=e=>new $u(`Operation timed out after '${To(e)}'`),cne=/*#__PURE__*/ O(2,(e,t)=>{let n=ao(t);return Sl(e,{duration:n,orElse:()=>uc(sne(n))})}),lne=/*#__PURE__*/ O(2,(e,t)=>Yc(Gc(e),Rc(Xu(t),Di()))),Cl=`~effect/Scope`,wl=`~effect/Scope/Closeable`,Tl=/*#__PURE__*/ j(`effect/Scope`),El=(e,t)=>qr(n=>(ou(n),Dl(e,t)??xc)),Dl=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&Nl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Ol(n.finalizer,t);let r=n.finalizers;return r.size===1?Ol(r.values().next().value,t):une(e,r,t)},Ol=(e,t)=>{try{return e(t)}catch(e){return Kr(e)}},kl=(e,t)=>el(e)?t:ul(t,t=>lc(Or(e.cause,t))),une=/*#__PURE__*/ jc(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Js();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*xl(Ol(s,n))):i.push(_u(o,Ol(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*rc(i)),yield*rl(r)}),dne=(e,t)=>dc(()=>Al(e,t)),Al=(e,t)=>{let n=Fl(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Ml(e,n,e=>El(n,e)),n)},jl=(e,t)=>fc(()=>e.state._tag===`Closed`?t(e.state.exit):(Ml(e,{},t),xc)),fne=(e,t)=>jl(e,Ct(t)),Ml=(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.set(t,n):(r.finalizers=/* @__PURE__ */ new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0,r.finalizers.set(t,n))}},Nl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=Il:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=Il))},Pl=e=>Fl(e,void 0),Fl=(e=`sequential`,t)=>({[wl]:wl,[Cl]:Cl,strategy:e,parent:t,state:Il}),Il={_tag:`Empty`},Ll=e=>dc(()=>Pl(e)),Rl=Tl,zl=/*#__PURE__*/ cl(Tl),Bl=e=>qr(t=>{let n=t.context,r=Pl();return t.setContext(ra(t.context,Tl,r)),Kl(t,e=>(t.setContext(n),Dl(r,e))),e}),Vl=/*#__PURE__*/ O(2,(e,t)=>ql(zl(e,t),e=>fc(()=>Dl(t,e)??xc))),Hl=e=>fc(()=>{let t=Pl();return ql(e(t),e=>fc(()=>Dl(t,e)??xc))}),Ul=(e,t,n)=>ol(r=>lu(i=>Xc(Rl,a=>qc(n?.interruptible?i(e):e,e=>jl(a,n=>sl(t(e,n),r)))))),pne=e=>Xc(Rl,t=>ol(n=>jl(t,t=>sl(e(t),n)))),Wl=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Rr({op:`OnExit`,[ur](e){return e._stack.push(this),this.effect},[pr](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(ru),e.interruptible=!1)},[dr](e,t,n){n??=Vr(e);let r;try{r=this.onExit(n)}catch(e){r=Kr(e)}return r?Xc(r,e=>n):n},[fr](e,t,n){n??=Wr(e);let r;try{r=this.onExit(n)}catch(e){r=Kr(e)}return r?Xc(kl(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),Gl=(e,t,n)=>new Wl(e,t,n),Kl=(e,t)=>{e._stack.push(new Wl(void 0,t,void 0))},ql=/*#__PURE__*/ O(2,Gl),Jl=/*#__PURE__*/ O(2,(e,t)=>ql(e,e=>t)),Yl=/*#__PURE__*/ O(3,(e,t,n)=>ql(e,e=>{let r=t(e);return wa(r)?xc:n(r.success,e)})),Xl=/*#__PURE__*/ O(2,(e,t)=>Yl(e,kte,t)),Zl=/*#__PURE__*/ O(3,(e,t,n)=>ql(e,e=>{if(e._tag!==`Failure`)return xc;let r=t(e.cause);return wa(r)?xc:n(r.success,e.cause)})),mne=/*#__PURE__*/ O(2,(e,t)=>Zl(Es,t)(e)),hne=/*#__PURE__*/ O(2,(e,t)=>dc(()=>Ql(e,typeof t==`function`?e=>bo(ao(t(e))):Ct(bo(ao(t)))))),gne=/*#__PURE__*/ Ct(1/0),Ql=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Kl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,ac(t.fiber)}),ic(t.fiber));return[qr(o=>{if(i!==void 0)return a(o,i);if(r!==void 0&&(n===1/0||o.getRef(Uu).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(Uu),c={fiber:void 0,awaiters:0};return i=c,c.fiber=_u(o,Gl(e,e=>{if(i!==c||(i=void 0,tl(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e}),!0,!0),c.fiber._exit??a(o,c)}),dc(()=>{r=void 0})]},_ne=/*#__PURE__*/ O(2,(e,t)=>Qc(hne(e,t),e=>e[0])),$l=e=>dc(()=>Ql(e,gne)[0]),eu=/*#__PURE__*/ qr(e=>lc(bs(e.id))),tu=e=>qr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(ru),e):e),nu=/*#__PURE__*/ zr({op:`SetInterruptible`,[pr](e){if(e.interruptible=this[lr],e._interruptedCause&&e.interruptible)return()=>lc(e._interruptedCause)}}),ru=/*#__PURE__*/ nu(!0),iu=/*#__PURE__*/ nu(!1),au=e=>{if(e.interruptible=!0,e._stack.push(iu),e._interruptedCause)return lc(e._interruptedCause)},ou=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(ru))},su=e=>{let t=e;if(!t.interruptible)return au(t)},cu=e=>qr(t=>t.interruptible?e:au(t)??e),lu=e=>qr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(ru),e(cu)):e(k)),uu=(e,t)=>$t(e)?t?.mode===`result`?fu(e,gl,t):fu(e,k,t):t?.discard?t.mode===`result`?fu(Object.values(e),gl,t):fu(Object.values(e),k,t):fc(()=>{let n={};return Rc(fu(Object.entries(e),([e,r])=>Qc(t?.mode===`result`?gl(r):r,t=>{ir(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),du=/*#__PURE__*/ zr({op:`While`,[dr](e,t){return this[lr].step(e),this[lr].while()?(t._stack.push(this),this[lr].body()):nl},[ur](e){return this[lr].while()?(e._stack.push(this),this[lr].body()):nl}}),fu=/*#__PURE__*/ O(e=>typeof e[1]==`function`,(e,t,n)=>fc(()=>{let r=pu(n?.concurrency);if(r===1)return vne(e,t,n);let i=Va(e),a=i.length;if(a===0)return n?.discard?xc:cc([]);let o=n?.discard?void 0:Array(a),s=yne({f:t,out:o},i,{concurrency:r});return s?Rc(s,o):cc(o)})),vne=(e,t,n)=>fc(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return Rc(du({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),pu=e=>e===`unbounded`?1/0:Math.max(1,e??1),mu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Xc(xl(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??xc),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!Zc(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},hu=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=Kr(e);return f=t,c=!0,u&&u.size>0?Xc(tu(sc(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(Zc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=_u(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=Er(e);f=Wr(f._tag===`Failure`?Or(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??xc)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return Oc(e=>{l=Js(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):fc(()=>(f??=nl,Xc(u?sc(u):xc,()=>f?._tag===`Failure`?f:xc)))})}if(c=!0,f){if(u&&u.size>0){let e=ec(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(xc);else return nl}};return h()}},gu=()=>e=>hu(e),yne=/*#__PURE__*/ hu({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)}}),bne=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>qr(n=>(Fne(),cc(_u(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),_u=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Ys(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=qs(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},vu=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n)=>qr(r=>{let i=_u(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};Ml(t,e,()=>Tc(e=>e===i.id?xc:ac(i))),i.addObserver(()=>Nl(t,e))}else i.interruptUnsafe(r.id,ec(r))}return cc(i)})),xne=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>Xc(Rl,n=>vu(e,n,t))),yu=e=>(t,n)=>{let r=new Ys(n?.scheduler?ra(e,Eo,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},Sne=/*#__PURE__*/ O(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(Nl(t,e),Ml(t,e,()=>ac(e)),e.addObserver(()=>Nl(t,e)),e)),Cne=/*#__PURE__*/ yu(/*#__PURE__*/ ea()),wne=e=>{let t=yu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},bu=e=>{let t=wne(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw js(e.cause);return e.value})},xu=/*#__PURE__*/ bu(/*#__PURE__*/ ea()),Su=e=>{let t=yu(e);return e=>{if(Zc(e))return e;let n=new jo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Kr(new Tne(r))}},Cu=/*#__PURE__*/ Su(/*#__PURE__*/ ea()),wu=/*#__PURE__*/ (e=>{let t=Su(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw js(n.cause);return n.value}})(/*#__PURE__*/ ea()),Tu=/*#__PURE__*/ cc(!0),Eu=/*#__PURE__*/ cc(!1);var Du=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Tu;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=[],Tu}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](nl)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](nl)}open=/*#__PURE__*/ qr(e=>this._isOpen?Eu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ qr(e=>this._isOpen?Eu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ Oc(e=>this._isOpen?e(xc):(this.waiters.push(e),dc(()=>{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__*/ dc(()=>this.closeUnsafe());whenOpen=e=>Xc(this.await,()=>e);isOpen(){return this._isOpen}};const Ou=e=>new Du(e??!1),ku=e=>dc(()=>Ou(e)),Au=/*#__PURE__*/ BigInt(0),ju={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:Au,endTime:Au,exit:nl},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},Mu=e=>Object.assign(Object.create(ju),e),Nu=e=>e?la(e.annotations,Qo)?e._tag===`Span`?Nu(Fi(e.parent)):Di():Oi(e):Di(),Pu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&la(n.annotations,Qo),i=n?.parent===void 0?n?.root?Di():Nu(e.cache.span):Oi(n.parent),a;if(r)a=Mu({name:t,parent:i,annotations:ra(n?.annotations??ea(),Qo,!0)});else{let r=e.cache.tracer??rs,o=e.getRef(Uu),s=e.getRef(cs),c=e.getRef(ls),l=e.getRef(us),u=n?.level??e.getRef($o),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ea(),links:d,startTime:s?o.currentTimeNanosUnsafe():Au,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(Ai(i)&&i.value.sampled===!1?!1:!cd(e.getRef(es),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},Fu=(e,t)=>tu(qr(n=>{let r=ca(n.context,Tl),i=Pu(n,e,t??{}),a=n.getRef(Uu),o=n.getRef(cs);return Rc(jl(r,e=>Lu(i,e,a,o)),i)})),Iu=(e,t)=>(t=typeof t==`function`?t:Et,al(os,n=>({name:e,stack:t,parent:n}))),Lu=(e,t,n,r)=>dc(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():Au,t)}),Ru=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return qr(t=>{let i=Pu(t,e,n),a=t.getRef(Uu),o=t.getRef(cs);return Kl(t,e=>Lu(i,e,a,o)),r(i)})},zu=/*#__PURE__*/ cl(Yo),Bu=function(){let e=gr(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=k;return t._tag===`Span`&&(n=hs(n),r=Iu(t.name,n?.captureStackTrace)),e?zu(r(arguments[0]),t):e=>zu(r(e),t)},Vu=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=hs(arguments[2]);if(e){let e=arguments[0];return Ru(t,arguments[2],t=>Bu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Ru(t,r?r(...a):i,t=>Bu(e,t,n))},Hu=(...e)=>qr(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 xc}),Uu=/*#__PURE__*/ _a(`effect/Clock`,{defaultValue:()=>new Gu}),Wu=2**31-1;var Gu=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ dc(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Ju()}currentTimeNanos=/*#__PURE__*/ dc(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return qu()}monotonicTimeNanos=/*#__PURE__*/ dc(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(bo(e))}sleepMillis(e){return e<=0?hc:Number.isFinite(e)?Oc(t=>{let n=e>Wu?this.sleepMillis(e-Wu):xc,r=setTimeout(()=>t(n),Math.min(e,Wu));return dc(()=>clearTimeout(r))}):kc}};const Ku=/*#__PURE__*/ BigInt(1e6),qu=/*#__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())*Ku;return e>t&&(t=e),t}}(),Ju=/*#__PURE__*/ function(){let e=/*#__PURE__*/ BigInt(1e9),t;return()=>{let n=qu(),r=BigInt(Date.now())*Ku;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}}(),Yu=e=>qr(t=>e(t.getRef(Uu))),Xu=e=>Yu(t=>t.sleep(ao(e))),Zu=/*#__PURE__*/ Yu(e=>e.currentTimeMillis),Qu=`~effect/Cause/TimeoutError`;var $u=class extends (/*#__PURE__*/ Xr(`TimeoutError`)){[Qu]=Qu;constructor(e){super({message:e})}};const ed=`~effect/Cause/IllegalArgumentError`;var td=class extends (/*#__PURE__*/ Xr(`IllegalArgumentError`)){[ed]=ed;constructor(e){super({message:e})}};const nd=`~effect/Cause/ExceededCapacityError`;var rd=class extends (/*#__PURE__*/ Xr(`ExceededCapacityError`)){[nd]=nd;constructor(e){super({message:e})}};const id=`~effect/Cause/AsyncFiberError`;var Tne=class extends (/*#__PURE__*/ Xr(`AsyncFiberError`)){[id]=id;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const ad=`~effect/Cause/UnknownError`;var od=class extends (/*#__PURE__*/ Xr(`UnknownError`)){[ad]=ad;constructor(e,t){super({message:t,cause:e})}};const Ene=/*#__PURE__*/ _a(`effect/Console`,{defaultValue:()=>globalThis.console}),sd=/*#__PURE__*/ Iee(wi,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}}),cd=/*#__PURE__*/ Ti(sd),Dne=/*#__PURE__*/ _a(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([Nne,Pne])}),One=/*#__PURE__*/ _a(`effect/Logger/LogToStderr`,{defaultValue:Tt}),kne={"~effect/Logger":{_Message:k,_Output:k},pipe(){return bt(this,arguments)}},ld=e=>{let t=Object.create(kne);return t.log=e,t},Ane=e=>e.replace(/[\s="]/g,`_`),jne=(e,t)=>`${Ane(e[0])}=${t-e[1]}ms`,ud=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];br(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Er(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=kr),qr(r=>{let i=e??r.cache.logLevel;if(cd(r.cache.minimumLogLevel,i))return xc;let a=r.getRef(Uu),o=r.getRef(Dne);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 xc})},dd={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};dd.gray,dd.blue,dd.green,dd.yellow,dd.red,dd.bgBrightRed,dd.black;const Mne=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`)}`,Nne=/*#__PURE__*/ ld(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Bs(e));let o=t.getTime(),s=n.getRef(ms),c=``;for(let e of s)c+=` ${jne(e,o)}`;let l=n.getRef(ds);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Ene);(n.getRef(One)?u.error:u.log)(`[${Mne(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Pne=/*#__PURE__*/ ld(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Uu),a=t.getRef(ds),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`]=Bs(e)),o.event(Xn(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function Fne(){$s.interruptChildren??=tc}const Ine=/*#__PURE__*/ O(e=>gr(e[0]),(e,t)=>Xl(e,e=>qr(n=>(fd(n,e,t?.defectsOnly),xc)))),fd=(e,t,n)=>{let r=e.getRef(as);if(r.size===0||n&&!Cs(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(Uu).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},Lne=br,Rne=Cee,pd=Pr,zne=Fr,md=Er,hd=Ar,gd=Mr,_d=e=>new Tr(e),vd=e=>new jr(e),yd=ys,bd=As,xd=Or,Sd=js,Cd=xs,wd=Ss,Td=Cs,Ed=Ts,Dd=Ds,Od=Bs,kd=Qr,Ad=ti,jd=ri,Md=ai,Nd=td,Pd=rd,Fd=od,Id=Nr,Ld=ks;var Rd=class extends (/*#__PURE__*/ j()(`effect/Cause/StackTrace`)){};const zd=_r,Bd=Vr,Vd=Wr,Hd=Gr,Ud=Kr,Wd=$c,Gd=nl,Kd=el,qd=Ote,Jd=tl,Yd=rl,Xd=`~effect/Deferred`,Zd=e=>A(e,Xd),Qd={[Xd]:{_A:k,_E:k},pipe(){return bt(this,arguments)}},$d=function(){this.resumes=void 0,this.effect=void 0};$d.prototype=Qd;const ef=()=>new $d,tf=()=>dc(()=>ef()),nf=e=>Oc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),dc(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),rf=/* @__PURE__ */ O(2,(e,t)=>dc(()=>uf(e,t))),af=/*#__PURE__*/ O(2,(e,t)=>rf(e,Wr(t))),of=/*#__PURE__*/ O(2,(e,t)=>af(e,bs(t))),sf=e=>dc(()=>cf(e)),cf=e=>e.effect!==void 0,lf=/*#__PURE__*/ O(2,(e,t)=>rf(e,Vr(t))),uf=(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},df=ds,ff=fs,pf=cs,mf=Tl,hf=Ll,gf=Pl,_f=zl,vf=jl,yf=fne,bf=dne,xf=Al,Sf=El,Cf=Dl,wf=Vl,Tf=`~effect/Layer/MemoMap`,Ef=(e,t)=>{let n={observers:0,deferred:ef(),scope:gf(),finalizer:r=>fc(()=>--n.observers>0?xc:(e.map.delete(t),Sf(n.scope,r)))};return n},Df=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Ml(t,{},e.finalizer),!0),Of={"~effect/Layer":{_ROut:k,_E:k,_RIn:k},pipe(){return bt(this,arguments)}},kf=e=>{let t=Object.create(Of);return t.build=e,t},Af=e=>kf((t,n)=>{let r=xf(n);return ql(e(t,r),e=>e._tag===`Failure`?Sf(r,e):xc)}),jf=e=>{let t=Af((n,r)=>n.getOrElseMemoize(t,r,e));return t};var Mf=class{get[Tf](){return Tf}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(Df(n,t),n.deferred.effect??nf(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return fc(()=>{let r;return Gl(fc(()=>{let i=this.get(e,t);if(i)return i;let a=Ef(this,e);return Df(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&uf(r,e)})})}};const Nf=()=>new Mf,Pf=e=>new Mf(e);var Ff=class e extends (/*#__PURE__*/ j()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=oa(t,e);return n?Pf(n):Nf()}};const If=/*#__PURE__*/ O(3,(e,t,n)=>cl(Qc(fc(()=>e.build(t,n)),ra(Ff,t)),Ff,t)),Lf=e=>qr(t=>If(e,Ff.forkOrCreate(t.context),ca(t.context,mf))),Rf=/*#__PURE__*/ O(2,(e,t)=>qr(n=>If(e,Ff.forkOrCreate(n.context),t))),zf=function(){return arguments.length===1?e=>Bf(na(arguments[0],e)):Bf(na(arguments[0],arguments[1]))},Bf=e=>kf(Ct(cc(e))),Vf=/*#__PURE__*/ Bf(/*#__PURE__*/ ea()),Hf=function(){return arguments.length===1?e=>Uf(arguments[0],e):Uf(arguments[0],arguments[1])},Uf=(e,t)=>Wf(Qc(t,t=>na(e,t))),Wf=e=>jf((t,n)=>_f(e,n)),Gf=e=>Wf(Rc(e,ea())),Kf=/*#__PURE__*/ j(`effect/Layer/unwrap`),qf=e=>Vne(Hf(Kf)(e),la(Kf)),Jf=(e,t,n)=>{let r=xf(n,`parallel`);return fu(e,e=>e.build(t,xf(r,`sequential`)),{concurrency:e.length}).pipe(Qc(e=>ha(...e)))},Yf=(...e)=>Af((t,n)=>Jf(e,t,n)),Bne=/*#__PURE__*/ O(2,(e,t)=>Yf(e,...Array.isArray(t)?t:[t])),Xf=(e,t,n)=>Af((r,i)=>Xc(Array.isArray(t)?Jf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(sl(t),Qc(e=>n(e,t))))),Zf=/*#__PURE__*/ O(2,(e,t)=>Xf(e,t,k)),Qf=/*#__PURE__*/ O(2,(e,t)=>Xf(e,t,(e,t)=>ma(t,e))),Vne=/*#__PURE__*/ O(2,(e,t)=>Af((n,r)=>Xc(e.build(n,r),e=>t(e).build(n,r)))),Hne=e=>kf((t,n)=>e.build(Nf(),n)),$f=Uu,ep=Zu,tp=`~effect/DateTime`,np=`~effect/DateTime/TimeZone`,rp={[tp]:tp,pipe(){return bt(this,arguments)},[Jn](){return this.toString()},toJSON(){return lp(this).toJSON()}},Une={...rp,_tag:`Utc`,[en](){return cn(this.epochMilliseconds)},[yn](e){return ap(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${lp(this).toJSON()})`}};({...rp});const ip={[np]:np,[Jn](){return this.toString()}};({...ip}),{...ip};const ap=e=>A(e,tp),Wne=e=>e._tag===`Utc`,op=e=>{let t=Object.create(Une);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},sp=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Nd(`Invalid date`);return op(t)},cp=e=>{if(ap(e))return e;if(e instanceof Date)return sp(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return sp(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return Yne(t,e),sp(t)}return typeof e==`string`&&!Gne(e)?sp(/* @__PURE__ */ new Date(e+`Z`)):sp(new Date(e))},Gne=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Kne=/*#__PURE__*/ Ii(cp),qne=e=>op(e.epochMilliseconds),lp=e=>new Date(e.epochMilliseconds),Jne=e=>e.epochMilliseconds,Yne=(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)},Xne=e=>lp(e).toISOString();globalThis.String;const Zne=e=>e.trim(),Qne=(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)},up=/*#__PURE__*/ O(2,(e,t)=>fl(e,$ne,e=>t(e))),dp=e=>e.reasons.some(fp),fp=e=>e._tag===`Fail`&&Ad(e.error),pp=e=>{let t,n=!1;for(let r of e.reasons)fp(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?xa(e):n?xa(md(e.reasons.filter(e=>!fp(e)))):ba(t)},$ne=e=>{let t=pp(e);return wa(t)?t:ba(t.success.value)},mp=e=>{let t=pp(e);return wa(t)?Vd(t.failure):Bd(t.success.value)},ere=/*#__PURE__*/ O(2,(e,t)=>_l(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=pp(e);return wa(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),tre=(e,t,n)=>Hl(r=>Xc(n?.local?If(t,Nf(),r):Rf(t,r),t=>sl(e,t))),nre=/*#__PURE__*/ O(e=>gr(e[0]),(e,t,n)=>Zi(t)?sl(e,t):tre(e,Array.isArray(t)?Yf(...t):t,n)),hp=gr,gp=uu,_p=fu,vp=du,yp=Cc,bp=wc,N=cc,xp=_c,rre=gc,Sp=fc,P=dc,F=xc,Cp=Oc,wp=kc,I=Ac,L=uc,Tp=lc,Ep=vc,Dp=yc,Op=Sc,ire=hc,kp=qr,Ap=mc,are=pc,R=Xc,ore=Cte,jp=Kc,Mp=qc,Np=gl,sre=ene,Pp=xl,z=Qc,Fp=Rc,Ip=Jc,Lp=pl,Rp=Jte,cre=Yte,zp=ul,Bp=Ute,Vp=ml,lre=Hte,Hp=hl,Up=Zte,Wp=Kte,Gp=Wte,Kp=Qte,qp=$te,ure=Ine,dre=cne,Jp=Sl,fre=one,Yp=Xu,pre=bte,Xp=Yc,mre=zte,Zp=bl,hre=xte,Qp=_l,$p=yl,em=Ite,tm=ol,nm=nre,rm=sl,im=Rte,am=Pte,om=Fte,sm=il,cm=cl,lm=Rl,um=Bl,dm=Hl,fm=Ul,pm=pne,mm=Jl,hm=Xl,gm=Gl,_m=ql,vm=$l,ym=_ne,bm=eu,xm=cu,Sm=mne,Cm=tu,wm=lu,Tm=Bte,Em=Hu,Dm=Fu,Om=Ru,km=Vu,Am=Bu,jm=bne,Mm=vu,Nm=xne,Pm=Cne,Fm=yu,Im=xu,Lm=bu,Rm=wu,zm=Cu,B=jc,V=Pc,Bm=Yu,Vm=/*#__PURE__*/ ud(`Fatal`),Hm=/*#__PURE__*/ ud(`Warn`),Um=/*#__PURE__*/ ud(`Error`),Wm=/*#__PURE__*/ ud(`Info`),Gm=/*#__PURE__*/ ud(`Debug`),Km=/*#__PURE__*/ O(e=>hp(e[0]),(e,...t)=>al(e,df,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||ir(n,t[0],t[1]),n})),qm=(e,t,n)=>(...r)=>Cp(i=>{try{e(...r,(e,n)=>{i(e?t?Sp(()=>L(t(e,r))):L(e):N(n))})}catch(e){i(n?L(n(e,r)):Dp(e))}}),Jm=wte,Ym=Tte,Xm=Ete,Zm=Ste,Qm=Dte,$m=pte,eh=`~effect/BigDecimal`,th={[eh]:eh,[en](){let e=lh(this);return an(ln(String(e.value)),cn(e.scale))},[yn](e){return nh(e)&&ph(this,e)===0},toString(){return`BigDecimal(${hh(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Jn](){return this.toJSON()},pipe(){return bt(this,arguments)}},nh=e=>A(e,eh),rh=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(th);return n.value=e,n.scale=t,n},ih=(e,t)=>{let n=rh(e,t);return n.normalized=n,n},ah=/*#__PURE__*/ BigInt(0),oh=/*#__PURE__*/ BigInt(1),sh=/*#__PURE__*/ BigInt(10),ch=/*#__PURE__*/ ih(ah,0),lh=e=>{if(e.normalized===void 0){if(e.value===ah)e.normalized=ch;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=ih(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},uh=[oh],dh=(e,t)=>e===t?0:e<t?-1:1,fh=(e,t)=>{let n=`${e.value<ah?-e.value:e.value}`,r=`${t.value<ah?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==ah)return i<ah?-1:1;let a=Math.max(n.length,r.length);return Fee(n.padEnd(a,`0`),r.padEnd(a,`0`))},ph=(e,t)=>{if(e.scale===t.scale)return dh(e.value,t.value);let n=mh(e),r=mh(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?fh(t,e):fh(e,t);let o=uh[a]??=sh**BigInt(a);return i>0?dh(e.value,t.value*o):dh(e.value*o,t.value)},mh=e=>e.value===ah?0:e.value<ah?-1:1,hh=e=>{let t=lh(e);if(Math.abs(t.scale)>=16)return gh(t);let n=t.value<ah,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},gh=e=>{if(_h(e))return`0e+0`;let t=lh(e),n=`${t.value}`,r=t.value<ah?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},_h=e=>e.value===ah,vh=globalThis.BigInt,yh=e=>e>vh(2**53-1)||e<vh(-(2**53-1))?Di():Oi(Number(e)),bh=/*#__PURE__*/ BigInt(0),xh=/*#__PURE__*/ BigInt(1),Sh=/*#__PURE__*/ BigInt(1e3),Ch=/*#__PURE__*/ BigInt(1024),wh=[{symbol:`B`,factor:xh,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Sh,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Sh**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Sh**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Sh**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Sh**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Sh**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Sh**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Sh**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Sh**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Sh**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],Th=[wh[0],{symbol:`KiB`,factor:Ch,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:Ch**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:Ch**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:Ch**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:Ch**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:Ch**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:Ch**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:Ch**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],Eh=[...wh,.../*#__PURE__*/ Th.slice(1)],Dh=/*#__PURE__*/ new Map(/*#__PURE__*/ Eh.flatMap(e=>e.names.map(t=>[t,e]))),Oh=/*#__PURE__*/ new Map(/*#__PURE__*/ Eh.map(e=>[e.symbol,e])),kh=e=>e,Ah=/*#__PURE__*/ kh(bh),jh=e=>{throw Error(`Invalid ByteSize: ${e}`)},Mh=e=>!Number.isSafeInteger(e)||e<0?jh(`expected a non-negative safe integer, received ${e}`):kh(BigInt(e)),Nh=(e,t)=>{if(typeof e==`bigint`)return e<bh?jh(`expected a non-negative quantity, received ${e}`):kh(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?jh(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):kh(BigInt(n))},Ph=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return jh(`unsupported syntax ${JSON.stringify(e)}`);let n=Dh.get(t[3]);if(n===void 0)return jh(`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===bh?kh(a/i):jh(`${JSON.stringify(e)} does not represent an integral number of bytes`)},Fh=e=>{switch(typeof e){case`bigint`:return e<bh?jh(`expected a non-negative bigint, received ${e}`):kh(e);case`number`:return Mh(e);case`string`:return Ph(e)}return jh(`unsupported input ${e}`)},Ih=/*#__PURE__*/ Ii(Fh),Lh=e=>typeof e==`bigint`?Fh(e):Mh(e),Rh=/*#__PURE__*/ (e=>t=>Nh(t,Oh.get(e)))(`MiB`),zh=ap,Bh=Wne,Vh=sp,Hh=cp,Uh=Kne,Wh=qne,Gh=Jne,Kh=Xne,qh=e=>Xh(typeof e==`string`?Zh.encode(e):e),Jh=e=>{let t=$h(e),n=t.length;if(n%4!=0)return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=ng(t.charCodeAt(e))<<18|ng(t.charCodeAt(e+1))<<12|ng(t.charCodeAt(e+2))<<6|ng(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return ba(r)}catch(e){return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Yh=e=>Da(Jh(e),e=>Qh.decode(e)),Xh=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=eg[e[r-2]>>2],n+=eg[(e[r-2]&3)<<4|e[r-1]>>4],n+=eg[(e[r-1]&15)<<2|e[r]>>6],n+=eg[e[r]&63];return r===t+1&&(n+=eg[e[r-2]>>2],n+=eg[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=eg[e[r-2]>>2],n+=eg[(e[r-2]&3)<<4|e[r-1]>>4],n+=eg[(e[r-1]&15)<<2],n+=`=`),n},Zh=/*#__PURE__*/ new TextEncoder,Qh=/*#__PURE__*/ new TextDecoder,$h=e=>e.replace(/[\n\r]/g,``),eg=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,tg=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)tg[/*#__PURE__*/ eg.charCodeAt(e)]=e;tg[61]=0;const ng=e=>{if(e>=tg.length||tg[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return tg[e]},rg=`~effect/http/Cookies`,ig=e=>A(e,rg),ag=`~effect/http/Cookies/Cookie`,og=`~effect/http/Cookies/CookieError`;var sg=class extends zo{},cg=class e extends (/*#__PURE__*/ Bo(`CookiesError`)){static fromReason(t,n){return new e({reason:new sg({_tag:t,cause:n})})}[og]=og;get message(){return this.reason._tag}};const lg={[rg]:rg,...Zn,toJSON(){return{_id:`effect/Cookies`,cookies:Fa(this.cookies,e=>e.toJSON())}},pipe(){return bt(this,arguments)}},ug=e=>{let t=Object.create(lg);return t.cookies=e,t},dg=e=>{let t={};for(let n of e)ir(t,n.name,n);return ug(t)},fg=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=pg(e.trim());t&&n.push(t)}return dg(n)};function pg(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(!_g.test(r))return;let i=t[0].slice(n+1),a=Ag(i);if(t.length===1)return Object.assign(Object.create(bg),{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=vo(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(bg),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const mg=/*#__PURE__*/ dg([]),hg=e=>Na(e.cookies),gg=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,_g=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,vg=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,yg=/^[\u0020-\u003a\u003c-\u007e]+$/,bg={[ag]:ag,...Zn,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function xg(e,t,n){let r=encodeURIComponent(t),i=Sg(e,r,n);return i===void 0?ba(Object.assign(Object.create(bg),{name:e,value:t,valueEncoded:r,options:n})):xa(i)}function Sg(e,t,n){if(!_g.test(e))return cg.fromReason(`InvalidCookieName`);if(t&&!gg.test(t))return cg.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!vg.test(n.domain))return cg.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!yg.test(n.path))return cg.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!uo(ao(n.maxAge)))return cg.fromReason(`CookieInfinityMaxAge`)}const Cg=/*#__PURE__*/ O(2,(e,t)=>ug({...e.cookies,...t.cookies})),wg=/*#__PURE__*/ O(e=>ig(e[0]),(e,t,n,r)=>Da(xg(t,n,r),n=>ug(Ra(e.cookies,t,n))));function Tg(e){let t=Sg(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=ute(ao(r.maxAge));n+=`; Max-Age=`+Math.trunc(e)}if(r.domain!==void 0&&(n+=`; Domain=`+r.domain),r.path!==void 0&&(n+=`; Path=`+r.path),r.priority!==void 0)switch(r.priority){case`low`:n+=`; Priority=Low`;break;case`medium`:n+=`; Priority=Medium`;break;case`high`:n+=`; Priority=High`}if(r.expires!==void 0&&(n+=`; Expires=`+r.expires.toUTCString()),r.httpOnly&&(n+=`; HttpOnly`),r.secure&&(n+=`; Secure`),r.partitioned&&(n+=`; Partitioned`),r.sameSite!==void 0)switch(r.sameSite){case`lax`:n+=`; SameSite=Lax`;break;case`strict`:n+=`; SameSite=Strict`;break;case`none`:n+=`; SameSite=None`}return n}const Eg=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),Dg=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},Og=e=>Object.values(e.cookies).map(Tg);function kg(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:Ag(n))}r=i+1}return t}const Ag=e=>{try{return decodeURIComponent(e)}catch{return e}},jg=/*#__PURE__*/ new WeakMap,Mg=e=>{if(jg.has(e))return jg.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},Ng=`~effect/Redacted`,Pg=e=>A(e,Ng),Fg=(e,t)=>{let n=Object.create(Ig);return t?.label&&(n.label=t.label),jg.set(n,e),n},Ig={[Ng]:{_A:e=>e},label:void 0,...hr,toJSON(){return this.toString()},toString(){return`<redacted${It(this.label)?`:`+this.label:``}>`},[en](){return tn(jg.get(this))},[yn](e){return Pg(e)&&bn(jg.get(this),jg.get(e))}},Lg=Mg,Rg=e=>si((t,n)=>e(Lg(t),Lg(n))),zg=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),Bg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[zg]:{value:zg},[jn]:{value(e){return Zg(this,la(e,$g))}},toJSON:{value(){return Nn(this)}},[yn]:{value(e){return Hg(this,e)}},[en]:{value(){return dn(this)}},toString:{value:Zn.toString},[Jn]:{value:Zn[Jn]}}),Vg=e=>Object.assign(Object.create(Bg),e),Hg=/*#__PURE__*/ Wee(/*#__PURE__*/ li()),Ug=/*#__PURE__*/ Object.create(Bg),Wg=e=>{if(e===void 0)return Ug;if(Symbol.iterator in e){let t=Object.create(Bg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(Bg);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},Gg=e=>Object.setPrototypeOf(e,Bg),Kg=/*#__PURE__*/ O(3,(e,t,n)=>{let r=Vg(e);return r[t.toLowerCase()]=n,r}),qg=/*#__PURE__*/ O(2,(e,t)=>Vg({...e,...Wg(t)})),Jg=/*#__PURE__*/ O(2,(e,t)=>{let n=Vg(e);return Object.assign(n,t),n}),Yg=/*#__PURE__*/ O(2,(e,t)=>{let n=Vg(e);return delete n[t.toLowerCase()],n}),Xg=/*#__PURE__*/ O(2,(e,t)=>{let n=Vg(e);for(let e of t)delete n[e.toLowerCase()];return n}),Zg=/*#__PURE__*/ O(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=Fg(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=Fg(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),Qg=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(typeof r==`string`){if(r.toLowerCase()===e.toLowerCase())return!0}else if(e.search(r)!==-1)return!0}return!1},$g=/*#__PURE__*/ _a(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`,`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]}),e_=`~effect/http/UrlParams`,t_=e=>A(e,e_),n_={...hr,[e_]:e_,[Symbol.iterator](){return this.params[Symbol.iterator]()},toJSON(){return{_id:`UrlParams`,params:Object.fromEntries(this.params)}},[yn](e){return o_(this,e)},[en](){return pn(this.params.flat())}},r_=e=>{let t=Object.create(n_);return t.params=e,t},i_=e=>{if(t_(e))return e;let t=a_(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 r_(n)},a_=e=>{let t=typeof e[Symbol.iterator]==`function`?Va(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,String(r[t])]);else if(typeof r==`object`&&r){let t=a_(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,String(r)]);return n},o_=/*#__PURE__*/ si((e,t)=>s_(e.params,t.params)),s_=/*#__PURE__*/ Zee(/*#__PURE__*/ Aa([/*#__PURE__*/ li(),/*#__PURE__*/ li()])),c_=/*#__PURE__*/ r_([]),l_=/*#__PURE__*/ O(2,(e,t)=>{let n=i_(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 r_(n)}),u_=e=>new URLSearchParams(i_(e).params).toString(),d_=e=>{let t={};for(let[n,r]of e.params)if(!Object.hasOwn(t,n))ir(t,n,r);else{let e=t[n];typeof e==`string`?ir(t,n,[e,r]):e.push(r)}return t};function f_(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function p_(e){return t=>f_(t)?.[e]}const m_=`~structural`,h_=`~identifier`,g_=`~sentinels`,__=`~constructor`,v_=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],y_=/*#__PURE__*/ p_(`identifier`),b_=/*#__PURE__*/ p_(h_),x_=/*#__PURE__*/ p_(`description`),S_=/*#__PURE__*/ At(e=>{let t=f_(e)?.identifier;return typeof t==`string`?t:e.getExpected(S_)}),C_=/*#__PURE__*/ new Set([g_,m_,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),w_=/*#__PURE__*/ Symbol(),T_=Bd,E_=/*#__PURE__*/ T_(w_),D_=/*#__PURE__*/ T_(w_),O_=e=>e===w_?Di():Oi(e),k_=e=>e._tag===`None`?E_:T_(e.value),A_=`~effect/SchemaIssue/Issue`;function j_(e){return A(e,A_)&&e[A_]===A_}function M_(e){return Object.hasOwn(e,`input`)}var N_=class{[A_]=A_;constructor(e,t){t?.reportInput===!0&&e!==w_&&(this.input=e)}};const P_=class extends N_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},F_=class extends N_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},I_=class extends N_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},L_=class extends N_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},R_=class extends N_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},z_=class extends N_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},B_=class extends N_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},V_=class extends N_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function H_(e,t,n,r,i){return new z_(e,[new I_([t],n)],r,i)}const U_=class extends N_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},W_=class extends N_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},G_=class extends N_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function K_(e,t,n){if(j_(e))return e;if(typeof e==`string`)return new V_({message:e},t,n);let r=typeof e.issue==`string`?new V_({message:e.issue},t,n):e.issue;return new I_(e.path,r)}function q_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new V_(void 0,t,n):K_(e,t,n)}function J_(e,t,n,r){return Array.isArray(t)?Ga(t)?t.length===1?K_(t[0],n,r):new z_(e,Ja(t,e=>K_(e,n,r)),n,r):void 0:q_(t,n,r)}const Y_=e=>{let t=ov(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return ev(S_(e.ast),e);case`InvalidValue`:{let t=$_(e);if(t!==void 0)return ev(t,e);let n=Q_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=Q_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=Q_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},X_=e=>ov(e.issue)??ov(e);function Z_(e){return t=>({issues:tv(t,[],e?.leafHook??Y_,e?.checkHook??X_)})}function Q_(e){return M_(e)?Rn(e.input):void 0}function $_(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function ev(e,t){let n=Q_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function tv(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 tv(e.issue,t,n,r);let a=$_(e.issue);return[{path:t,message:a===void 0?ev(nv(e.filter),e):ev(a,e.issue)}]}case`Encoding`:return tv(e.issue,t,n,r);case`Pointer`:return tv(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>tv(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:ov(e)??ev(S_(e.ast),e)}]:e.issues.flatMap(e=>tv(e,t,n,r));default:return[{path:t,message:n(e)}]}}function nv(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=>nv(e)).join(` & `)}}function rv(){return e=>av(e,``)}const iv=/*#__PURE__*/ rv();function av(e,t){let n;switch(e._tag){case`Filter`:{let r=X_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return av(e.issue,t);let r=$_(e.issue);n=r===void 0?ev(nv(e.filter),e):ev(r,e.issue)}break}case`Encoding`:return av(e.issue,t);case`Pointer`:return av(e.issue,t+Vn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>av(e,t)).join(`
|
|
16
|
+
`);n=ov(e)??ev(S_(e.ast),e);break;default:n=Y_(e)}return t?`${n}\n at ${t}`:n}function ov(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return ov(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 sv(e){let t;for(let n of e.reasons){if(!pd(n)||!j_(n.error))return;t??=n.error}return t}function cv(e,t){let n=sv(e);if(n===void 0)throw Error(t,{cause:e});return n}const lv=(e,t,n)=>{switch(e._tag){case`Passthrough`:return N(t);case`Transform`:return N(Li(t,e.transform));case`TransformOptional`:return N(e.transform(t));case`TransformEffect`:return ki(t)?xp:Jm(e.transform(t.value,n),Oi);case`TransformOptionalEffect`:return e.transform(t,n)}},uv=e=>Object.assign(Object.create(xt),e),dv=(e,t)=>xv((n,r)=>Zm(lv(e,n,r),e=>lv(t,e,r))),fv=/*#__PURE__*/ O(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 vv(n=>t.transform(e.transform(n)));case`TransformOptional`:return bv(n=>t.transform(Li(n,e.transform)));case`TransformEffect`:return yv((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return dv(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return bv(n=>Li(e.transform(n),t.transform));case`TransformOptional`:return bv(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return dv(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return yv((n,r)=>Jm(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return dv(e,t);case`TransformEffect`:return yv((n,r)=>Zm(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return dv(e,t)}});function pv(e){return xv((t,n)=>L(e(t,n)))}function mv(e){return pv((t,n)=>{let r={message:e(t)};return Ai(t)?new U_(r,t.value,n):new U_(r)})}const hv=/*#__PURE__*/ mv(()=>`Encoding is not supported`),gv=/*#__PURE__*/ uv({_tag:`Passthrough`});function _v(){return gv}function vv(e){return uv({_tag:`Transform`,transform:e})}function yv(e){return uv({_tag:`TransformEffect`,transform:e})}function bv(e){return uv({_tag:`TransformOptional`,transform:e})}function xv(e){return uv({_tag:`TransformOptionalEffect`,transform:e})}function Sv(){return bv(()=>Di())}function Cv(e){return xv(t=>{let n=Vee(t,Ut);return Ai(n)?N(n):Jm(e,Oi)})}function wv(){return vv(globalThis.String)}function Tv(){return vv(globalThis.Number)}function Ev(){return vv(globalThis.BigInt)}function Dv(){return vv(Zne)}function Ov(e){return yv((t,n)=>Op({try:()=>JSON.parse(t,e?.reviver),catch:()=>new V_({expected:`a valid JSON string`},t,n)}))}function kv(e){return yv((t,n)=>Op({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 V_({expected:`a JSON-serializable value`},t,n)}))}function Av(e){let t=e?.separator??`,`;return vv(e=>e===``?[]:e.split(t))}function jv(){return vv(qh)}function Mv(){return yv((e,t)=>Ym(Ap(Jh(e)),()=>new V_({expected:`a valid Base64 string`},e,t)))}const Nv=class extends St{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Nv(this.encode,this.decode)}},Pv=`~effect/SchemaTransformation/Transformation`,Fv=class extends St{[Pv]=Pv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Fv(this.encode,this.decode)}};function Iv(e){return A(e,Pv)&&e[Pv]===Pv}const Lv=e=>Iv(e)?e:new Fv(e.decode,e.encode);function Rv(e){return new Fv(yv(e.decode),yv(e.encode))}function zv(e){return new Fv(vv(e.decode),vv(e.encode))}function Bv(){return new Fv(Dv(),_v())}const Vv=/*#__PURE__*/ new Fv(/*#__PURE__*/ _v(),/*#__PURE__*/ _v());function Hv(){return Vv}const Uv=/*#__PURE__*/ new Fv(/*#__PURE__*/ Tv(),/*#__PURE__*/ wv()),Wv=/*#__PURE__*/ new Fv(/*#__PURE__*/ Ev(),/*#__PURE__*/ wv()),Gv=e=>Jt(e)&&typeof e.message==`string`,Kv=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Xv(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},qv=e=>{try{let t=Gn(e);return t===void 0?Rn(e):JSON.parse(t)}catch{return Rn(e)}},Jv=(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},Yv=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(Qt(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Jv(r,e,n);return t.delete(r),i}return qv(r)};return n},Xv=e=>Gv(e)?Kv(e):e,gre=e=>zv({decode:Xv,encode:Yv(e)}),Zv=/*#__PURE__*/ new Fv(/*#__PURE__*/ Mv(),/*#__PURE__*/ jv());function _re(e){return new Fv(Ov(e??{}),kv(e))}function Qv(e){return t=>t._tag===e}const $v=/*#__PURE__*/ Qv(`Declaration`),vre=/*#__PURE__*/ Qv(`Null`),yre=/*#__PURE__*/ Qv(`Undefined`),ey=/*#__PURE__*/ Qv(`Void`),bre=/*#__PURE__*/ Qv(`Never`),ty=/*#__PURE__*/ Qv(`Literal`),ny=/*#__PURE__*/ Qv(`UniqueSymbol`),xre=/*#__PURE__*/ Qv(`Enum`),ry=/*#__PURE__*/ Qv(`Arrays`),iy=/*#__PURE__*/ Qv(`Objects`),ay=/*#__PURE__*/ Qv(`Union`),oy=/*#__PURE__*/ Qv(`Suspend`),sy=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},cy={},ly=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}},uy=`~effect/Schema`;var dy=class{[uy]=uy;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 fy=class extends dy{_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===w_?E_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=xb(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new fy(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>`}},py=/*#__PURE__*/ new class extends dy{_tag=`Null`;getParser(){return jb(this,null)}getExpected(){return`null`}},Sre=class extends dy{_tag=`Undefined`;getParser(){return jb(this,void 0)}toCodecJson(){return ub(this,[my])}getExpected(){return`undefined`}},my=/*#__PURE__*/ new sy(py,/*#__PURE__*/ new Fv(/*#__PURE__*/ vv(()=>void 0),/*#__PURE__*/ vv(()=>null))),hy=/*#__PURE__*/ new Sre,Cre=/*#__PURE__*/ new class extends dy{_tag=`Void`;getParser(){let e=T_(void 0);return t=>t===w_?E_:e}toCodecJson(){return ub(this,[my])}getExpected(){return`void`}},wre=/*#__PURE__*/ new class extends dy{_tag=`Never`;getParser(){return Mb(this,Kt)}getExpected(){return`never`}},Tre=/*#__PURE__*/ new class extends dy{_tag=`Any`;getParser(){return Mb(this,qt)}getExpected(){return`any`}},gy=/*#__PURE__*/ new class extends dy{_tag=`Unknown`;getParser(){return Mb(this,qt)}getExpected(){return`unknown`}};function _y(e){return typeof e==`number`?`parts[${e}]`:e}function vy(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${_y(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=_y(t);r=!e.checks&&e.parts.every((e,t)=>vy(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=_y(t);r=!e.checks&&e.types.every((e,t)=>vy(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const Ere=class extends dy{_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(!vy(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 wy(!1,this.parts.map(Ib),[]),n=e(wb(xy,t,Dre(this)));return(e,t)=>{if(e===w_)return E_;let r=n(e,t);return r._tag===`Success`?D_:Xm(r,{onSuccess:()=>e,onFailure:n=>new z_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return Nb(this,e,t)===void 0?void 0:e}};function Dre(e){return new Fv(yv((t,n)=>{let r=Nb(e,t,n);return r?N(r):L(new V_({expected:`a string matching template literal parts`},t,n))}),vv(e=>e.join(``)))}const yy=class extends dy{_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 ${Rn(e)}`);this.literal=e}getParser(){return jb(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?by(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:by(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function by(e){let t=globalThis.String(e.literal);return ub(e,[new sy(new yy(t),new Fv(vv(()=>e.literal),vv(()=>t)))])}const xy=/*#__PURE__*/ new class extends dy{_tag=`String`;getParser(){return Mb(this,It)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Bb(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Ore=class extends dy{_tag=`Number`;getParser(){return Mb(this,Lt)}matchKey(e,t){return this._match($re,e,t)}matchPart(e,t){return this._match(Lb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Bb(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Sy(this.checks,`effect/schema/isFinite`)||Sy(this.checks,`effect/schema/isInt`))?this:ub(this,[Vre])}toCodecStringTree(){return this.toCodecJson()===this?ub(this,[tie]):ub(this,[nie])}getExpected(){return`number`}};function Sy(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Sy(e.checks,t))}const Cy=/*#__PURE__*/ new Ore,kre=/*#__PURE__*/ new class extends dy{_tag=`Boolean`;getParser(){return Mb(this,Rt)}getExpected(){return`boolean`}},Are=/*#__PURE__*/ new class extends dy{_tag=`BigInt`;getParser(){return Mb(this,mee)}matchPart(e,t){if(!zb.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Bb(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return ub(this,[iie])}getExpected(){return`bigint`}},wy=class extends dy{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Tb(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Tb(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new R_(n,t[o],i),a=new I_([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return L(new z_(n,[a],t,i))}return e.issues?L(new z_(n,e.issues,t,i)):T_(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:pu(t.concurrency),f=d===1?Mre(i,e,0,u):Nre(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Zc(f))return Zm(f,()=>c(i));let p=!0;return Sp(()=>p?(p=!1,R(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===w_)return E_;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)):L(new B_(n,e,a))}catch(e){return Dp(e)}}}_rebuild(e,t,n){let r=xb(this.elements,e),i=xb(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new wy(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 jre(e,t,n,r){if(n._tag===`Failure`)return Ey(e,e.ast,r,n);let i=n===D_?t:n[lr];if(i!==w_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Tb(t.ast))return;let n=new I_([r],new L_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Hd(new z_(e.ast,[n],e.input,e.options))}}const Ty={onItem(e,t,n){let r=n<e.len?t:w_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:jre},Mre=/*#__PURE__*/ mu()(Ty),Nre=/*#__PURE__*/ gu()(Ty),Ey=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=sv(r.cause);if(i===void 0)return Vd(bd(r.cause,r=>new z_(t,[new I_([n],r)],e.input,e.options)));let a=new I_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Hd(new z_(t,[a],e.input,e.options))},Dy=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function Oy(e,t,n=cy){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(Pb(Ob(t)))}const ky=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Ay(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Ay);default:return!1}}function jy(e){let t=fb(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(jy);default:return!1}}function Pre(e){return Ay(e)&&jy(e)}const My=class{parameter;type;constructor(e,t){if(!Pre(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Tb(t)&&!Ab(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Ny=class extends dy{_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 Mb(n,hee);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(Pb(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 Ey(t,n,i,s)??Gd;let c=s===D_?o:s[lr];if(a!==w_&&c!==w_){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Gd;ir(t.out,a,c)}return Gd},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Zc(t))return R(Pp(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Ey(e,n,r,a)??Gd;let o=a===D_?r:a[lr],s=e.input[r],l=i.parserValue(s,e.options);return Zc(l)?t(e,r,o,s,l):R(Pp(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Zc(a)?t(e,n,n,i,a):R(Pp(a),r=>t(e,n,n,i,r))},u=i?gu()({onItem:(e,[t,n])=>n.is.parameter===xy?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return $m(function*(t,d){if(t===w_)return w_;if(typeof t!=`object`||!t||Array.isArray(t))return yield*L(new B_(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:pu(d.concurrency),v=i&&g?n.indexSignatures.map(e=>Oy(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 R_(n,f[a],d),r=new I_([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*L(new z_(n,[r],t,d))}}}if(r){let e=_===1?Iy(m,a):Fre(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===xy?l:c,r=v?.[e]??(t.is.parameter===xy?Object.keys(f):Oy(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Zc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Ka();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===xy?Object.keys(f):Oy(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*L(new z_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return R(Pp(n),n=>{let i=Py(e,r,n);if(i)return i;let o=()=>T_(e.out),s=Iy(e,a.slice(t+1));return s?Zm(s,o):o()})};return(e,t)=>{if(e===w_)return E_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&pu(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return L(new B_(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=Jy(i,s),l=c?i[s]:w_,d=n.parser(l,t);if(!Zc(d))return u(o,e,d);if(d===D_){c&&ir(a,s,l);continue}let f=Py(o,n,d);if(f)return f}}catch(e){return Dp(e)}return T_(a)}}_rebuild(e,t,n,r){let i=xb(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new ky(t.name,n)}),a=xb(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new My(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Ny(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 Py(e,t,n){if(n._tag===`Failure`)return Ey(e,e.ast,t.name,n);if(n===D_)return;let r=n[lr];if(r!==w_){ir(e.out,t.name,r);return}if(delete e.out[t.name],!Tb(t.type)){let n=new I_([t.name],new L_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Hd(new z_(e.ast,[n],e.input,e.options))}}const Fy={onItem(e,t){if(!Jy(e.input,t.name))return t.parser(w_,e.options);let n=e.input[t.name];return ir(e.out,t.name,n),t.parser(n,e.options)},step:Py},Iy=/*#__PURE__*/ mu()(Fy),Fre=/*#__PURE__*/ gu()(Fy);function Ly(e,t){return e?t?[...e,...t]:e:t}function Ry(e,t,n){return new Ny(Reflect.ownKeys(e).map(t=>new ky(t,e[t].ast)),[],n,t)}function zy(e){return e.ast}function By(e,t=void 0){return new wy(!1,e.map(e=>e.ast),[],void 0,t)}function Vy(e,t,n){return new Yy(e.map(zy),t,void 0,n)}function Ire(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=Ly(i,e.checks)}return new Ny(n,r,void 0,i)}const Hy=/*#__PURE__*/ jt(e=>{for(;;){if(oy(e))return gy;let t=e.encoding;if(!t)return e.recur?.(Hy,k)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==k))return gy;e=t[t.length-1].to}});function Uy(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(Uy)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function Wy(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[g_];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Tb(t)){if(ty(t))return[{key:e.name,literal:t.literal}];if(ny(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Tb(e)){if(ty(e))return[{key:t,literal:e.literal}];if(ny(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>Wy(Hy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return Wy(e.thunk())}}const Gy=/*#__PURE__*/ new WeakMap,Ky=/*#__PURE__*/ Object.freeze([]),qy=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Jy=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Lre(e){let t=Gy.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=Hy(c);if(bre(l))continue;if(ty(l)||ny(l)){a??=/* @__PURE__ */ new Map;let e=ty(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=Wy(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=Uy(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Ky);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Ky;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(Xt(e)){let n=Jy(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Ky;if(t)return o}return Ky}}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=qy(t);if(!Xt(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Jy(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=Jy(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=Jy(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(qy(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Gy.set(e,t),t}const Yy=class extends dy{_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===w_)return E_;let i=(o??=Lre(n.types))(e,r);if(i.length===0)return L(new W_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Zc(r)?Xy(n,r.cause,e,t):Rre(n,r,e,t)}return Zy(n,a,i,e,t)}}_rebuild(e,t,n){let r=xb(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=Ob(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(ty);if(t.length>0)return`${eb(n.isMutable)}[ ${t.map(t=>e(t)+tb(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>ty(e.type));if(t.length>0)return`{ ${t.map(t=>`${eb(t.type.context?.isMutable)}${Bn(t.name)}${tb(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Xy(e,t,n,r){let i=sv(t);return i?Hd(new W_(e,[i],n,r)):Vd(t)}function Rre(e,t,n,r){return zp(t,t=>Xy(e,t,n,r))}function Zy(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=zre(a,n);if(!o)return a.out?a.out:L(new W_(e,a.issues??[],r,i));if(Zc(o))return Qy(o,a);let s=!0;return Sp(()=>s?(s=!1,Qy(o,a)):Zy(e,t,n,r,i))}function Qy(e,t){return Zm(e,e=>t.out===D_?N(t.input):t.out?t.out:L(new W_(t.ast,t.issues??[],t.input,t.options)))}const zre=/*#__PURE__*/ mu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=sv(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]),Hd(new G_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Gd}}}),$y=/*#__PURE__*/ new Yy([/*#__PURE__*/ new yy(`Infinity`),/*#__PURE__*/ new yy(`-Infinity`),/*#__PURE__*/ new yy(`NaN`)]);function eb(e){return e?``:`readonly `}function tb(e){return e?`?`:``}const nb=class extends St{_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 nb(this.run,{...this.annotations,...e},this.aborted)}abort(){return new nb(this.run,this.annotations,!0)}and(e,t){return new rb([this,e],t)}},rb=class extends St{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new rb(this.checks,{...this.annotations,...e})}and(e,t){return new rb([this,e],t)}};function ib(e,t,n=!1){return new nb((t,n,r)=>J_(n,e(t,n,r),t,r),t,n)}function Bre(e){return ib(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 ab=/*#__PURE__*/ hb(Cy,[/*#__PURE__*/ Bre()]),Vre=/*#__PURE__*/ new sy(/*#__PURE__*/ new Yy([ab,$y]),/*#__PURE__*/ new Fv(/*#__PURE__*/ Tv(),/*#__PURE__*/ vv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function ob(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return ib(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 sb=/*#__PURE__*/ new WeakMap;function cb(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&sb.set(n,lb(e)),n}function lb(e){let t=sb.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 sb.set(e,n),n}function ub(e,t){return e.encoding===t?e:cb(e,{encoding:t})}function db(e,t){if(e.context===t)return e;let n=lb(e);return n.context===t&&n.encoding===e.encoding?n:cb(e,{context:t})}function fb(e){return e.encoding?fb(e.encoding[e.encoding.length-1].to):e}function pb(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return mb(e,Ua(e.checks.slice(0,-1),n.annotate(t)))}return cb(e,{annotations:{...e.annotations,...t}})}function mb(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:cb(e,{checks:t})}function hb(e,t){return mb(e,Ly(e.checks,t))}function gb(e,t){let n=t(e.to);return n===e.to?e:new sy(n,e.transformation)}function _b(e,t){let n=e,r=n[n.length-1],i=gb(r,t);return i===r?e:Ua(e.slice(0,e.length-1),i)}function vb(e){return t=>t.encoding?ub(t,_b(t.encoding,e)):t}function yb(e,t){return vb(e=>db(e,t))(e)}function Hre(e){function t(n){return n.encoding?ub(n,_b(n.encoding,t)):e(n)}return At(t)}function bb(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:ub(r,_b(r.encoding,n))}return e(r)}return jt(n)}function Ure(e,t,n){let r=new sy(e,t);return ub(n,n.encoding?[...n.encoding,r]:[r])}function xb(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 Sb(e,t){return db(e,e.context?new ly(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new ly(!1,!1,void 0,t))}const Cb=/*#__PURE__*/ jt(e=>{let t=e.context?e.context.isOptional===!1?new ly(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new ly(!0,!1);return Wre(db(e,t))}),Wre=/*#__PURE__*/ vb(Cb),Gre=/*#__PURE__*/ At(e=>Cb(new Yy([e,hy])));function Kre(e,t){return db(e,e.context?new ly(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new ly(!1,!1,t))}function wb(e,t,n){return Ure(e,n,t)}function qre(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Bt(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 Jre(e,t){let{literals:n,parameters:r}=qre(e);return new Ny(n.map(e=>new ky(e,t)),r.map(e=>new My(e,t)))}function Tb(e){return e.context?.isOptional??!1}function Yre(e){return e.context?.isMutable??!1}function Eb(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Eb)}function Xre(e){function t(e){return Eb(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Wa(n)?n:void 0}function Zre(e){let t=!0;function n(e){return t=t&&!e.encoding&&!oy(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const Db=/*#__PURE__*/ jt(e=>{let t=lb(e);if(t!==e){let n=Db(t);return n===t&&e.encoding===void 0?e:db(n,e.context)}let n=`recur`in e?e.recur(Db):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Zre(e)?n.encodingChecks:ry(n)||iy(n)||$v(n)&&n.typeParameters.length>0?Xre(n.encodingChecks):void 0;return cb(n,{encodingChecks:void 0,checks:Ly(n.checks,t)})}return n}),Ob=/*#__PURE__*/ jt(e=>Db(kb(e)));function Qre(e,t){let n=t,r=n.length,i=n[r-1],a=[new sy(kb(ub(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new sy(kb(n[e-1].to),n[e].transformation.flip()));let o=kb(i.to);return o.encoding?ub(o,[...o.encoding,...a]):ub(o,a)}const kb=/*#__PURE__*/ At(e=>{if(e.encoding)return Qre(e,e.encoding);let t=lb(e);if(t!==e){let n=kb(t);return n===t?e:db(n,e.context)}return`flip`in e?e.flip(kb):`recur`in e?e.recur(kb):e});function Ab(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Ab);default:return!1}}function jb(e,t){let n=t===0?D_:T_(t);return(r,i)=>r===w_?E_:r===t?n:L(new B_(e,r,i))}function Mb(e,t){return(n,r)=>n===w_?E_:t(n)?D_:L(new B_(e,n,r))}function Nb(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 Pb=/*#__PURE__*/ bb(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Pb)}}),Fb=/*#__PURE__*/ bb(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Fb)}}),Ib=/*#__PURE__*/ bb(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(Ib)}}),Lb=/*#__PURE__*/ new globalThis.RegExp(`^${Dy}$`),$re=/*#__PURE__*/ new globalThis.RegExp(`^(?:${Dy}|Infinity|-Infinity|NaN)$`);function eie(e){return ob(Lb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Lb.source}),...e})}const Rb=/*#__PURE__*/ hb(xy,[/*#__PURE__*/ eie()]),tie=/*#__PURE__*/ new sy(Rb,Uv),nie=/*#__PURE__*/ new sy(/*#__PURE__*/ new Yy([Rb,$y]),Uv),zb=/*#__PURE__*/ new globalThis.RegExp(`^-?\\d+$`);function rie(e){return ob(zb,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:zb.source}),...e})}const iie=/*#__PURE__*/ new sy(/* @__PURE__ */ hb(xy,[/*#__PURE__*/ rie({expected:`a string representing a bigint`})]),Wv);function Bb(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Bb(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 P_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function aie(e){if(!$v(e))return;let t=e.annotations?.[__];return Vt(t)?t(e.typeParameters):void 0}const Vb=p_,Hb=y_,Ub=x_;function oie(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function sie(e){return e===void 0||typeof e==`string`}function Wb(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 Gb(e){return Wb(e,oie)}const Kb=/*#__PURE__*/ new fy([],()=>(e,t,n)=>Gb(e)?D_:L(new B_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Jb}),cie=/*#__PURE__*/ pb(Kb,{representation:{id:`effect/schema/MutableJson`,payload:null}}),qb=/*#__PURE__*/ new sy(Kb,/*#__PURE__*/ Hv()),lie=/*#__PURE__*/ new sy(/*#__PURE__*/ new Yy([/*#__PURE__*/ new wy(!1,[],[Kb]),/*#__PURE__*/ new Ny([],[/*#__PURE__*/ new My(xy,Kb)])]),/*#__PURE__*/ Hv());function uie(e){return Wb(e,sie)}const Jb=/*#__PURE__*/ new sy(/* @__PURE__ */ new fy([],()=>(e,t,n)=>uie(e)?D_:L(new B_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ Hv()),Yb=(e,t,n)=>e===D_?n(t):Zm(e,n);function Xb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===D_?e.decode(T_(O_(n)),r):e.decode(Jm(t,O_),r);return Zb(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===D_?T_(t):e;case`Transform`:{let e=e=>e===w_?E_:T_(t.transform(e));return(t,n)=>Yb(t,n,e)}case`TransformOptional`:{let e=e=>k_(t.transform(O_(e)));return(t,n)=>Yb(t,n,e)}case`TransformEffect`:return(e,n,r)=>Yb(e,n,e=>e===w_?E_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>Yb(e,n,e=>Zb(t.transform(O_(e),r)))}}const Zb=e=>Zm(e,k_),Qb=(e,t,n,r)=>zp(r,r=>Ep(()=>bd(r,r=>new F_(e,r,t,n))));function die(e,t){let n=Xb(e.link.transformation),r;return(i,a)=>{if(i===w_)return E_;if(e.isConstructed(i))return D_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function fie(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==w_&&r!==void 0)return t(r,i);let a=n;if(Zc(a)&&a._tag===`Success`){let e=t(a[lr],i);return e===D_?a:e}return Zm(Qb(e,r,i,a),e=>{let n=t(e,i);return n===D_?T_(e):n})}}function pie(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:fie(e,n)}function $b(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?aie(e):void 0,o=a?die(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>Xb(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(Zc(r)){if(r._tag===`Success`){let i=r===D_?t:r[lr];if(t!==w_&&i!==w_){let i=Bb(u,t,void 0,e,n);i&&(r=L(new z_(e,i,t,n)))}}}else r=R(r,r=>{if(t!==w_&&r!==w_){let r=Bb(u,t,void 0,e,n);if(r)return L(new z_(e,r,t,n))}return N(r)})}if(s&&!n.disableChecks){if(Zc(r)){if(r._tag===`Success`){let i=r===D_?t:r[lr];if(i===w_)return r;let a=Bb(s,i,void 0,e,n);a&&(r=L(new z_(e,a,i,n)))}}else r=R(r,t=>{if(t!==w_){let r=Bb(s,t,void 0,e,n);if(r)return L(new z_(e,r,t,n))}return N(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[lr],o=t(a,r)):o=Zm(o,e=>{let n=t(e,r);return n===D_?T_(e):n})}if(o._tag===`Success`){let e=o[lr],t=p(e,r);return t===D_?o:t}return o=Qb(e,n,r,o),Zm(o,e=>{let t=p(e,r);return t===D_?T_(e):t})}:p}const mie=/*#__PURE__*/ Symbol(),ex=/*#__PURE__*/ new WeakMap,hie=e=>nx(e).parser,tx=e=>nx(e).makeEffect,gie=e=>pie(e,tx);var _ie=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=$b(this.ast,hie)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=$b(this.ast,tx,gie)}};function nx(e){let t=ex.get(e);if(t!==void 0)return t;let n=new _ie(e);return ex.set(e,n),n}function rx(e){let t=e.ast,n;return(e,r)=>(n??=fx(Oie,Db(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function ix(e){let t=rx(e);return(e,n)=>{let r=zm(t(e,n));return Kd(r)?Oi(r.value):(cv(r.cause,`Option adapter can only return none for schema issues`),Di())}}function ax(e){return Eie(Db(e.ast))}function vie(e){return ox(e.ast)}function yie(e){{let t=px(dx(e));return e=>{let n=t(e,cy);return Kd(n)?!0:(cv(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function ox(e){let t=Db(e),n=e=>(n=yie(t),n(e));return e=>n(e)}function sx(e,t){let n=dx(e.ast);return t===void 0?n:(e,r)=>n(e,lx(t,r))}function bie(e,t){return Cie(sx(e,t))}function xie(e,t){return wie(sx(e,t))}function cx(e,t){let n=dx(kb(e.ast));return t===void 0?n:(e,r)=>n(e,lx(t,r))}const lx=(e,t)=>t?{...e,...t}:e,ux=e=>e===w_?L(new V_):N(e);function dx(e){return fx(Die,e)}function Sie(e,t){return e===D_?N(t):Zc(e)?e[lr]===w_?ux(w_):e:Zm(e,ux)}function fx(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??cy);return a===D_?N(r):Zc(a)?a[lr]===w_?ux(w_):a:Zm(a,ux)}}function px(e){return(t,n)=>zm(e(t,n))}function Cie(e){let t=px(e);return(e,n)=>{let r=t(e,n);return Kd(r)?Oi(r.value):(cv(r.cause,`Option adapter can only return none for schema issues`),Di())}}function wie(e){let t=px(e);return(e,n)=>{let r=t(e,n);return Kd(r)?ba(r.value):xa(cv(r.cause,`Result adapter can only return schema issues`))}}function Tie(e,t){let n=zm(e);if(Kd(n))return n.value;let r=cv(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Eie(e){let t,n;return(r,i)=>{t??=nx(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??cy,o=t.make;if(o!==void 0&&r!==w_){let e;try{e=o(r,a)}catch(e){throw cv(gd(e),`Constructor adapter can only throw schema issues`),e}if(e!==mie&&e!==w_)return e}return Tie(Sie((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const Die=e=>nx(e).parser,Oie=e=>nx(e).makeEffect,mx=`~effect/Schema/Schema`,hx=/*#__PURE__*/ Symbol(),kie={[mx]:mx,get make(){let e=ax(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=rx(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=ix(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return bt(this,arguments)},annotate(e){return this.rebuild(pb(this.ast,e))},annotateKey(e){return this.rebuild(Sb(this.ast,e))},check(...e){return this.rebuild(hb(this.ast,e))},rebuild(e){return gx(e,this[hx])}};function gx(e,t){function n(){}let r=Object.setPrototypeOf(n,kie);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[hx]=t,r.ast=e,r}function Aie(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function _x(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function vx(e){return encodeURI(Aie(e)).replace(/#/g,`%23`)}function yx(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 bx(e){let t=yx(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(_x)}function jie(e){return e.reduce((e,t)=>`${e}/${vx(t)}`,`#`)}const Mie=[`example`,`discriminator`,`xml`,`externalDocs`];function Nie(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>xx.test(e))),i=t.filter(e=>!xx.test(e)).sort().map(e=>[e,Pie(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=wx(t.$id),a=Jt(t.$defs)?t.$defs:void 0;return Sx(t,(t,o)=>{Lie(t,Mie,`OpenAPI 3.1`,`Draft 2020-12`),Cx(t,(t,s)=>{let c=t.startsWith(`#`)?bx(t):void 0;if(c===void 0||c[0]!==`$defs`||c.length<2)return t;let l=c[1];return i?(r&&!o&&Object.hasOwn(e.definitions,l)&&(a===void 0||!Object.hasOwn(a,l))&&Ex(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:jie([`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 xx=/^[a-zA-Z0-9.\-_]+$/;function Pie(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function Sx(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!Jt(e))return e;let a=r||!i&&wx(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=Iie(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 Fie(e,t){return Sx(e,e=>{Cx(e,t)})}function Cx(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 Iie(e,t){if(!Jt(e))return;let n={};for(let r of Object.keys(e))ir(n,r,t(e[r],r));return n}function wx(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const Tx=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Tx],[...Tx];function Ex(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Lie(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Ex(i,n,`it is not active in ${r} but would become active in the target`)}function Rie(e){return gx(Dx(e.ast),{schema:e})}const Dx=/*#__PURE__*/ bb(e=>{let t=Bie(e,Dx),n=e.context;return t===e||n===void 0?t:yb(t,Ox(n))});function Ox(e){return e.constructorDefault===void 0?e:new ly(e.isOptional,e.isMutable,void 0,e.annotations)}function kx(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Ax(e){return t=>{let n=[...t].sort((t,n)=>e(Ob(t))-e(Ob(n)));return n.some((e,n)=>e!==t[n])?n:t}}const zie=/*#__PURE__*/ Ax(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Bie(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Vt(n))return ub(e,[qb]);let r=n(e.typeParameters.map(e=>gx(Ob(e))));return r===void 0?e:ub(e,[gb(r,t)])}case`Unknown`:return ub(e,[qb]);case`ObjectKeyword`:return ub(e,[lie]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return kx(e),e.recur(t,Fb);case`Union`:{let n=zie(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 Vie(e){return gx(Nx(e.ast),{schema:e})}function Hie(e){return gx(Fx(e.ast))}const Uie=/*#__PURE__*/ Ax(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wie(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>gx(t(Ob(e)))),i=e.annotations?.toCodecStringTree;if(Vt(i)){let n=i(r);return n===void 0?e:ub(e,[gb(n,t)])}let a=e.annotations?.toCodecJson,o=Vt(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(Vt(s)?s(r):void 0);return c===void 0?n(e):ub(e,[gb(c,t)])}case`Null`:return ub(e,[Gie]);case`Boolean`:return ub(e,[Kie]);case`Unknown`:case`ObjectKeyword`:return ub(e,[Jb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return kx(e),e.recur(t,Fb);case`Union`:{let n=Uie(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 Gie=/*#__PURE__*/ new sy(/*#__PURE__*/ new yy(`null`),/*#__PURE__*/ new Fv(/*#__PURE__*/ vv(()=>null),/*#__PURE__*/ vv(()=>`null`))),Kie=/*#__PURE__*/ new sy(/*#__PURE__*/ new Yy([/*#__PURE__*/ new yy(`true`),/*#__PURE__*/ new yy(`false`)]),/*#__PURE__*/ new Fv(/*#__PURE__*/ vv(e=>e===`true`),/*#__PURE__*/ wv())),jx=/*#__PURE__*/ new Fv(/*#__PURE__*/ vv(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ _v()),Mx=e=>e.transformation===jx,Nx=/*#__PURE__*/ bb(e=>{let t=Wie(e,Nx,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?yb(t,Ox(e.context)):t},{stopAt:Mx}),Px=e=>Tb(e)?Cb(gy):gy,Fx=/*#__PURE__*/ bb(e=>{let t=qie(e);if(ry(t)){let n=wb(new Yy([new wy(t.isMutable,t.elements.map(Px),t.rest.map(Px)),xy],{mode:`anyOf`}),t,jx);return Tb(e)?Cb(n):n}return t},{stopAt:Mx});function qie(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur(Fx):e}globalThis.RegExp;const Jie=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Ix(e,t){return t.length>0&&(e+=`\n at ${Vn(t)}`),Error(e)}function Lx(e){return`#/$defs/${vx(e)}`}const Yie=/*#__PURE__*/ new Set([...C_,h_,...v_]);function Rx(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;Gb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&Gb(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(Gb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!Yie.has(r)&&t.includeAnnotationKey(r)&&Gb(i)&&ir(n,r,i);return Object.keys(n).length===0?void 0:n}function zx(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=zx(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 Xie(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 Bx(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function Vx(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}const Hx=`|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=Xie(e);if(i!==void 0||a){let r=zx(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:Bx(r.schema,Hx)&&Vx(o,s)?{...o,...r.schema}:Ux(o,r.schema,n)}}if(n&&Vx(e,r))return{...e,...t};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 Wx(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>Wx(e,t)))}function Zie(e){return Array.isArray(e)}function Gx(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=Ja(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!Wx(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=>bn(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Ja(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 Fie(e,e=>{let t=yx(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(_x(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,Lx(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[h_]: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=Zie(s);c&&i.push(!1);let l=c?s[0]:s,u=Rx(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`&&Bx(d,f)&&(u===void 0||Bx(u,Hx))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=_(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Rx(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:Lx(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=Rx(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&Qie(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(Kx).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=Rx(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=Rx(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);bn(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);continue}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=$ie(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 Wx(n)&&r.type===`string`&&typeof r.pattern==`string`&&Bx(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(Kx).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 Qie(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function $ie(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 Kx(e){switch(e._tag){case`Literal`:return Jie(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return Dy;case`TemplateLiteral`:return e.parts.map(Kx).join(``);case`Union`:return`(?:${e.types.map(Kx).join(`|`)})`;default:throw Ix(`Invalid schema representation document`,[])}}function eae(e,t){let n=Gx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function tae(e,t){return Gx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const nae=({identifier:e})=>e;function qx(e){return e===void 0?void 0:{annotations:e}}function rae(e,t){let{references:n,representations:r}=Jx([e],t);return{representation:r[0],references:n}}function Jx(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??nae;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:Ja(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:pb(e,{identifier:n}):b_(e)===r?e:pb(e,{[h_]: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=fb(e),n=lb(t),r=y_(t),i=r===void 0?(t===e?void 0:y_(e))??b_(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;return}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(Db(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,...qx(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...qx(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...qx(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...qx(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...qx(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=fb(e),n=t.context?.annotations;return{isOptional:Tb(t),type:m(e),...qx(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...qx(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=fb(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Tb(t),isMutable:Yre(t),...qx(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...qx(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...qx(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...qx(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:Ja(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(Db(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function Yx(e){return Kd(e)?e.value:{issues:[{message:Od(e.cause)}]}}function iae(e,t){let n=sx(e),r={errors:`all`,...t?.parseOptions},i=Z_(t),a=e=>{let t=new jo(`sync`),a=Pm(Zp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?Yx(o):new Promise(e=>{a.addObserver(t=>{e(Yx(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 aae=/*#__PURE__*/ O(2,(e,t)=>({...e,...t})),Xx=e=>e,Zx=`~effect/Schema/SchemaError`;function Qx(e){return A(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}const $x=mx;function eS(){return(e,t,n)=>mS(new fy(e.map(zy),e=>t(e.map(e=>mS(e))),n))}function tS(e,t){return eS()([],()=>(t,n,r)=>e(t)?N(t):L(new B_(n,t,r)),t)}var nS=class extends (/*#__PURE__*/ Bo(`SchemaError`)){[Zx]=Zx;constructor(e){let t=er();tr(0);try{super({issue:e})}finally{tr(t)}}get message(){return iv(this.issue)}toString(){return`SchemaError(${this.message})`}};function rS(e){return Qx(e)}function iS(e){return Zc(e)?oae(e):zp(e,e=>Ep(()=>bd(e,e=>new nS(e))))}function oae(e){return Kd(e)?e:Vd(bd(e.cause,e=>new nS(e)))}function sae(e,t){let n;for(let r of e.reasons){if(!pd(r)||!rS(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 aS(e){let t=zm(e);if(Kd(t))return t.value;throw sae(t.cause,`Sync adapter can only throw schema errors`)}function cae(e,t){return iae(e,t)}const oS=vie;function sS(e,t){let n=sx(e,t);return(e,t)=>iS(n(e,t))}const cS=sS,lae=bie;function uae(e,t){let n=xie(e,t);return(e,t)=>Ea(n(e,t),e=>new nS(e))}function lS(e,t){let n=sS(e,t);return(e,t)=>aS(n(e,t))}const dae=lS;function uS(e,t){let n=cx(e,t);return(e,t)=>iS(n(e,t))}const dS=uS;function fS(e,t){let n=uS(e,t);return(e,t)=>aS(n(e,t))}const pS=fS,mS=gx;function hS(e){return A(e,$x)&&e[$x]===$x}const gS=/*#__PURE__*/ Xx(e=>mS(Cb(e.ast),{schema:e})),_S=/*#__PURE__*/ Xx(e=>{let t=BS(e);return mS(Gre(e.ast),{schema:t})}),vS=/*#__PURE__*/ Xx(e=>mS(Db(e.ast),{schema:e})),yS=/*#__PURE__*/ Xx(e=>mS(Ob(e.ast),{schema:e}));function bS(e){let t=mS(new yy(e),{literal:e,transform(n){return t.pipe(VS(bS(n),{decode:vv(()=>n),encode:vv(()=>e)}))}});return t}function fae(e){return e.map(e=>hS(e)?e.ast:new yy(e))}function xS(e){return mS(new Ere(fae(e)),{parts:e})}const SS=/*#__PURE__*/ mS(wre),CS=/*#__PURE__*/ mS(Tre),wS=/*#__PURE__*/ mS(gy),TS=/*#__PURE__*/ mS(py),pae=/*#__PURE__*/ mS(hy),H=/*#__PURE__*/ mS(xy),ES=/*#__PURE__*/ mS(Cy),DS=/*#__PURE__*/ mS(kre),OS=/*#__PURE__*/ mS(Are),kS=/*#__PURE__*/ mS(Cre);function AS(e,t){return mS(e,{fields:t,mapFields(e,t){let n=e(this.fields);return AS(Ry(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function U(e){return AS(Ry(e,void 0),e)}function jS(e){return Xx(t=>t.mapFields(aae(e)))}function MS(e,t){return mS(Jre(e.ast,t.ast),{key:e,value:t})}function NS(e,t){return mS(Ire(e.ast,t.map(zy)),{schema:e,records:t})}function PS(e,t){return mS(e,{elements:t,mapElements(e,t){let n=e(this.elements);return PS(By(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function FS(e){return PS(By(e),e)}const W=/*#__PURE__*/ Xx(e=>mS(new wy(!1,[],[e.ast]),{value:e})),IS=/*#__PURE__*/ Xx(e=>mS(new wy(!1,[e.ast],[e.ast]),{value:e}));function LS(e,t){return mS(e,{members:t,mapMembers(e,t){let n=e(this.members);return LS(Vy(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function G(e,t){return LS(Vy(e,t,void 0),e)}function RS(e){let t=e.map(bS);return mS(Vy(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return G(e(this.members))},pick(e){return RS(e)},transform(e){return G(t.map((t,n)=>t.transform(e[n])))}})}const zS=/*#__PURE__*/ Xx(e=>G([e,TS])),BS=/*#__PURE__*/ Xx(e=>G([e,pae]));function VS(e,t){return n=>mS(wb(n.ast,e.ast,t?Lv(t):Hv()),{from:n,to:e})}function HS(){return(e,t)=>QS()(e,{decode:t,encode:hv})}const US=/*#__PURE__*/ RS([`true`,`yes`,`on`,`1`,`y`]),WS=/*#__PURE__*/ RS([`false`,`no`,`off`,`0`,`n`]),GS=/*#__PURE__*/ RS([...US.literals,...WS.literals]).pipe(/*#__PURE__*/ VS(DS,/*#__PURE__*/ zv({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function KS(e){return t=>VS(vS(t),e)(t)}function qS(e){return t=>mS(Kre(t.ast,e),{schema:t})}function JS(e){return zp(e,e=>Ep(()=>bd(e,e=>e.issue)))}function mae(e,t){let n=t?.encodingStrategy===`omit`?Sv():_v();return t=>_S(yS(t)).pipe(VS(t,{decode:Cv(JS(e)),encode:n}))}function YS(e){return bS(e).pipe(qS(N(e)))}function XS(e,t){return U({_tag:YS(e),...t})}function ZS(){return e=>e}function hae(e,t){return tS(t=>t instanceof e,t)}function QS(){return(e,t)=>new sy(e.ast,Lv(t))}const $S=ib,eC=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function tC(e){let t=new globalThis.RegExp(eC);return $S(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:eC,flags:``}]},...e})}function nC(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${Rn(n)})`:`new RegExp(${Rn(n)}, ${Rn(r)})`;return ob(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const rC=/*#__PURE__*/ mS(ab);function iC(e){let t=Ei(e.order),n=e.formatter??Rn;return(r,i)=>$S(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 aC(e){let t=Ei(e.order),n=Ti(e.order),r=Ree(e.order),i=Lee(e.order),a=e.formatter??Rn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return $S(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 oC(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${Rn(e)}`);return e}const sC=/*#__PURE__*/ iC({order:wi,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:oC(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${Rn(e)})`})})}),cC=/*#__PURE__*/ aC({order:wi,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:oC(e.minimum),maximum:oC(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${Rn(e.minimum)}, maximum: ${Rn(e.maximum)}, exclusiveMinimum: ${Rn(t)}, exclusiveMaximum: ${Rn(n)} })`})}}});function lC(e){return $S(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}const uC=/*#__PURE__*/ ES.check(/*#__PURE__*/ lC());function dC(e,t){return e=hC(e),fC(e,Math.ceil(e/2),t)}function fC(e,t,n){return $S(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})`}),[m_]:!0,arbitraryConstraint:{minLength:e},...n})}function pC(e){return fC(1,1,e)}function mC(e,t){return e=hC(e),$S(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})`}),[m_]:!0,arbitraryConstraint:{maxLength:e},...t})}function hC(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function gC(e,t){return e=hC(e),$S(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})`}),[m_]:!0,arbitraryConstraint:{minProperties:e},...t})}function _C(e){return $S(e=>Qee(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:k},...e})}const vC=/*#__PURE__*/ H.check(/*#__PURE__*/ pC()),yC=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),bC=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},xC=[];function SC(e){let t=yC(e),n=xC[t];if(n!==void 0)return n;let r=ZC.pipe(VS(wS,gre(bC(t))));return xC[t]=r,r}globalThis.RegExp,globalThis.URL;const CC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function wC(e,t){return CC.pipe(VS(e,_re(t)))}const TC=/*#__PURE__*/ wC(wS);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const EC=/*#__PURE__*/ H.check(/*#__PURE__*/ tC()),DC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ VS(EC,/*#__PURE__*/ Bv())),OC=/*#__PURE__*/ H.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),kC=/*#__PURE__*/ hae(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>QS()(OC,Zv)}),AC=/*#__PURE__*/ OC.pipe(/*#__PURE__*/ VS(kC,Zv));function jC(e,t){let n=eS()([e,t],([e,t])=>(n,r,i)=>{if(!Rne(n))return L(new B_(r,n,i));switch(n._tag){case`Fail`:return Xm(sx(e)(n.error,i),{onSuccess:_d,onFailure:e=>H_(r,`error`,e,n,i)});case`Die`:return Xm(sx(t)(n.defect,i),{onSuccess:vd,onFailure:e=>H_(r,`defect`,e,n,i)});case`Interrupt`:return N(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])=>QS()(G([U({_tag:bS(`Fail`),error:e}),U({_tag:bS(`Die`),defect:t}),U({_tag:bS(`Interrupt`),fiberId:BS(rC)})]),zv({decode:e=>{switch(e._tag){case`Fail`:return _d(e.error);case`Die`:return vd(e.defect);case`Interrupt`:return yd(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 mS(n.ast,{error:e,defect:t})}function MC(e,t){let n=eS()([e,t],([e,t])=>{let n=W(jC(e,t));return(e,t,r)=>Lne(e)?Xm(sx(n)(e.reasons,r),{onSuccess:md,onFailure:n=>H_(t,`failures`,n,e,r)}):L(new B_(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])=>QS()(W(jC(e,t)),zv({decode:md,encode:({reasons:e})=>e}))});return mS(n.ast,{error:e,defect:t})}const NC=/*#__PURE__*/ Rv({decode:(e,t)=>ji(Uh(e),{onNone:()=>L(new V_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>N(Wh(e))}),encode:e=>N(Kh(e))});function PC(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 FC(e,t){return uC.check(cC({minimum:e,maximum:t}))}const IC=/*#__PURE__*/ tS(e=>zh(e)&&Bh(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=PC(e,-864e13,864e13);return HS()(FC(t,n),vv(Hh))},toCodecJson:()=>QS()(H,NC),toFormatter:()=>e=>e.toString()}),LC=/*#__PURE__*/ H.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ VS(IC,NC)),RC=/*#__PURE__*/ tS(lo,{representation:{id:`effect/schema/Duration`,payload:null},toCode:()=>({runtime:`Schema.Duration`,Type:`Duration.Duration`,importDeclarations:[`import * as Duration from "effect/Duration"`]}),expected:`Duration`,toCodecJson:()=>QS()(G([U({_tag:bS(`Infinity`)}),U({_tag:bS(`NegativeInfinity`)}),U({_tag:bS(`Nanos`),value:OS}),U({_tag:bS(`Millis`),value:uC})]),zv({decode:e=>{switch(e._tag){case`Infinity`:return mo;case`NegativeInfinity`:return ho;case`Nanos`:return go(e.value);case`Millis`:return _o(e.value)}},encode:e=>{switch(e.value._tag){case`Infinity`:return{_tag:`Infinity`};case`NegativeInfinity`:return{_tag:`NegativeInfinity`};case`Nanos`:return{_tag:`Nanos`,value:e.value.nanos};case`Millis`:return{_tag:`Millis`,value:e.value.millis}}}}))});function zC(e,t,n){let r=eS()([e,t,n],([e,t,n])=>{let r=MC(t,n);return(t,n,i)=>{if(!zd(t))return L(new B_(n,t,i));switch(t._tag){case`Success`:return Xm(sx(e)(t.value,i),{onSuccess:Bd,onFailure:e=>H_(n,`value`,e,t,i)});case`Failure`:return Xm(sx(r)(t.cause,i),{onSuccess:Vd,onFailure:e=>H_(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])=>QS()(G([U({_tag:bS(`Success`),value:e}),U({_tag:bS(`Failure`),cause:MC(t,n)})]),zv({decode:e=>e._tag===`Success`?Bd(e.value):Vd(e.cause),encode:e=>Kd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return mS(r.ast,{value:e,error:t,defect:n})}function BC(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:sx(bS(n)),o=eS()([e],([e])=>(t,n,r)=>{if(Pg(t)){let i=a===void 0?F:Ym(a(t.label,r),e=>new I_([`label`],e));return Zm(i,()=>Xm(sx(e)(Lg(t),r),{onSuccess:e=>Fg(e,{label:t.label}),onFailure:()=>new z_(n,[new I_([`value`],new V_(void 0,t,r))],t,r)}))}return L(new B_(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}, ${Rn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>QS()(e,{decode:vv(e=>Fg(e,{label:n})),encode:r?mv(e=>`Cannot serialize Redacted`+(Ai(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):vv(Lg)}),toEquivalence:([e])=>Rg(e)});return mS(o.ast,{value:e})}const gae=/*#__PURE__*/ globalThis.Symbol.for(`immer-draftable`),VC={};function HC(e,t,n,r,i){let a=vae(n,t,r),o=UC(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===VC?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:VC,value:i}})}static[$x]=$x;get[o](){return o}static[gae]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return bt(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return ax(a(this))(e??{},t)}static makeOption(e,t){return ix(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(pb(this.ast,e))}static annotateKey(e){return this.rebuild(Sb(this.ast,e))}static check(...e){return this.rebuild(hb(this.ast,e))}static extend(e){return(t,r)=>{let a=WC(t)?t:U(t),o={...n.fields,...a.fields},s=Ry(o,n.ast.checks,{identifier:e});return HC(this,e,AS(hb(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 _ae(e){return new Fv(vv(t=>new e(t,{"~payload":{token:VC,value:t}})),_v())}function UC(e){return`~effect/Schema/Class/${e}`}function vae(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=UC(t),o=e=>e instanceof i||A(e,a),s=_ae(i);return r=VS(mS(new fy([e.ast],()=>(e,t,n)=>o(e)?N(e):L(new B_(t,e,n)),{identifier:t,[__]:([e])=>({isConstructed:o,link:new sy(e,s)}),toCodec:([e])=>new sy(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[g_]:Wy(e.ast),...n})),s)(e)}}function WC(e){return hS(e)}const GC=e=>(t,n)=>{let r=WC(t)?t:U(t);return HC(Fo,e,r,n,e=>({toString(){return`${e}(${Rn({...this})})`}}))},KC=e=>(t,n)=>{let r=WC(t)?t:U(t);return HC(Yr,e,r,n,e=>({name:e}))},qC=e=>(t,n,r)=>{let i=WC(n)?n.mapFields(e=>({_tag:YS(t),...e}),{unsafePreserveChecks:!0}):XS(t,n);return KC(e??t)(i,r)};function yae(e,t){return eae(rae(Dx(e.ast),t),t)}const JC=Rie,YC=Vie,XC=Hie,ZC=/*#__PURE__*/ mS(/*#__PURE__*/ pb(Kb,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),K=/*#__PURE__*/ MS(H,ZC),bae=/*#__PURE__*/ mS(/*#__PURE__*/ pb(cie,{toCode:()=>({runtime:`Schema.MutableJson`,Type:`Schema.MutableJson`})}));function QC(){return Object.assign(e=>e,{option:e=>Oi(e),result:e=>ba(e),is:e=>!0})}const $C=`~effect/MutableHashMap`,xae={[$C]:$C,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${Rn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:Yn(Array.from(this))}},[Jn](){return this.toJSON()},pipe(){return bt(this,arguments)}},Sae=()=>{let e=Object.create(xae);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},ew=/*#__PURE__*/ O(2,(e,t)=>{if(e.backing.has(t))return Oi(e.backing.get(t));if(tw(t))return Di();let n=tn(t),r=e.buckets.get(n);return r===void 0?Di():Cae(e,r,t)}),tw=e=>typeof e!=`object`&&typeof e!=`function`,Cae=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(bn(n,t[r])){let n=t[r];return Oi(e.backing.get(n))}return Di()},wae=/*#__PURE__*/ O(3,(e,t,n)=>{if(e.backing.has(t)||tw(t))return e.backing.set(t,n),e;let r=tn(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Tae(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Tae=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(bn(t,e[n]))return e[n]},nw=/*#__PURE__*/ O(2,(e,t)=>{if(tw(t))return e.backing.delete(t),e;let n=tn(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||bn(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Eae=e=>(e.backing.clear(),e.buckets.clear(),e),Dae=e=>e.backing.size,rw=ic,iw=ac,aw=Js,ow=Sne,sw=Ou,cw=ku,lw=`~effect/MutableRef`,uw={[lw]:lw,...hr,toJSON(){return{_id:`MutableRef`,current:Yn(this.current)}}},dw=e=>{let t=Object.create(uw);return t.current=e,t},fw=/*#__PURE__*/ O(2,(e,t)=>(e.current=t,e)),pw=/*#__PURE__*/ Symbol.for(`effect/MutableList/Empty`),mw=()=>({head:void 0,tail:void 0,length:0}),hw=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})},gw=()=>({array:[],mutable:!0,offset:0,next:void 0}),_w=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=gw(),e.tail=e.tail.next):e.head=e.tail=gw(),e.tail.array.push(t),e.length++},vw=(e,t)=>{e.head={array:[t],mutable:!0,offset:0,next:e.head},e.tail||=e.head,e.length++},yw=(e,t)=>bw(e,Va(t),!Array.isArray(t)),bw=(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},xw=e=>{e.head=e.tail=void 0,e.length=0},Sw=(e,t)=>{if(t=ya(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return xw(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?xw(e):hw(e),n;i=i.next}return xw(e),n},Cw=e=>Sw(e,e.length),ww=e=>{if(!e.head)return pw;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:xw(e):hw(e),t},Tw=(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}if(n.length===0){xw(e);return}e.head=e.tail={array:n,mutable:!0,offset:0,next:void 0},e.length=n.length},Ew=(e,t)=>Tw(e,e=>e!==t),Dw=e=>P(()=>Uw(e.atomicPubSub(),/* @__PURE__ */ new Map,gf(),sw(!1),dw(!1),e.strategy(),dw(Di()))),Ow=e=>Dw({atomicPubSub:()=>kw(e),strategy:()=>new Ww}),kw=e=>{let t=e?.replay;return new zw(t&&t>0?new qw(Math.ceil(t)):void 0)},Aw=/*#__PURE__*/ O(2,(e,t)=>Sp(()=>e.shutdownFlag.current||Ai(e.ended.current)?N(!1):e.pubsub.publish(t)?(e.strategy.completeSubscribersUnsafe(e.pubsub,e.subscribers),N(!0)):e.strategy.handleSurplus(e.pubsub,e.subscribers,[t],e.shutdownFlag,e.ended))),jw=e=>Cm(tm(t=>{let n=la(t,mf),r=xf(e.scope),i=Rw(e.pubsub,e.subscribers,e.strategy,e.ended);return yf(r,Mw(i)).pipe(jp(vf(n,e=>Sf(r,e))),Fp(i))})),Mw=e=>Cm(kp(t=>(fw(e.shutdownFlag,!0),_p(Cw(e.pollers),e=>of(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(Mp(()=>P(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),mre(e.shutdownHook.open),Ip)))),Nw=e=>Sp(()=>{if(e.shutdownFlag.current)return bm;if(e.replayWindow.remaining>0){let t=e.replayWindow.take();return N(t)}let t=e.pollers.length===0?e.subscription.poll():pw;return t===pw?Pw(e):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),N(t))}),Pw=e=>Cp(t=>{if(e.shutdownFlag.current)return t(bm);if(Ai(e.ended.current)){let n=e.pollers.length===0?e.subscription.poll():pw;return n===pw?t(N(e.ended.current.value)):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),t(N(n)))}let n=ef(),r=e.subscribers.get(e.subscription);return r||(r=/* @__PURE__ */ new Set,e.subscribers.set(e.subscription,r)),r.add(e.pollers),_w(e.pollers,n),e.strategy.completePollersUnsafe(e.pubsub,e.subscribers,e.subscription,e.pollers),n.effect?t(n.effect):(n.resumes=[t],P(()=>Ew(e.pollers,n)))}),Fw=/*#__PURE__*/ Symbol.for(`effect/PubSub/AbsentValue`),Iw=(e,t,n)=>{e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(n)},Lw=(e,t,n)=>{if(!e.has(t))return;let r=e.get(t);r.delete(n),r.size===0&&e.delete(t)},Rw=(e,t,n,r)=>new Vw(e,t,e.subscribe(),mw(),sw(!1),dw(!1),n,e.replayWindow(),r);var zw=class{publisherHead={value:Fw,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 Jw(this.replayBuffer):Yw}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=Fw,this.subscribersIndex+=1,this.replayBuffer?.slide(t,e.replayIndex)}}subscribe(){return this.publisherTail.subscribers+=1,new Bw(this,this.publisherTail,this.publisherIndex,!1)}},Bw=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===Fw?(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 pw;let e=!0,t=pw;for(;e;)if(this.subscriberHead===this.self.publisherTail)e=!1;else{let n=this.subscriberHead.next.value;n!==Fw&&(t=n,--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=Fw,this.self.subscribersIndex+=1),e=!1),this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return t}pollUpTo(e){e=ya(e);let t=[],n=0;for(;n!==e;){let r=this.poll();r===pw?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!==Fw&&(--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=Fw,this.self.subscribersIndex+=1)),this.subscriberHead=this.subscriberHead.next}},Vw=class{"~effect/PubSub/Subscription"={_A:k};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 bt(this,arguments)}},Hw=class{"~effect/PubSub"={_A:k};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 bt(this,arguments)}};const Uw=(e,t,n,r,i,a,o)=>new Hw(e,t,n,r,i,a,o);var Ww=class{get shutdown(){return F}handleSurplus(e,t,n,r){return N(!1)}onPubSubEmptySpaceUnsafe(e,t){}completePollersUnsafe(e,t,n,r){return Gw(this,e,t,n,r)}completeSubscribersUnsafe(e,t){return Kw(this,e,t)}};const Gw=(e,t,n,r,i)=>{let a=!0;for(;a&&!r.isEmpty();){let o=ww(i);if(o===pw)Lw(n,r,i),i.length===0?a=!1:Iw(n,r,i);else{let a=r.poll();a===pw?vw(i,o):(uf(o,Bd(a)),e.onPubSubEmptySpaceUnsafe(t,n))}}},Kw=(e,t,n)=>{for(let[r,i]of n)for(let a of i)e.completePollersUnsafe(t,n,r,a)};var qw=class{capacity;head={value:Fw,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:Fw,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)}},Jw=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]=Fw,this.index=(this.index+1)%this.values.length,this.remaining--,this.remaining===0&&this.close(),e}takeN(e){e=ya(e);let t=Math.min(e,this.remaining),n=Array(t);for(let e=0;e<t;e++)n[e]=this.take();return n}takeAll(){return this.takeN(this.remaining)}};const Yw={remaining:0,take:()=>void 0,takeN:()=>[],takeAll:()=>[],close:()=>void 0},Xw={_A:k,_E:k},Zw={"~effect/Queue":Xw,"~effect/Queue/Enqueue":Xw,"~effect/Queue/Dequeue":Xw,...hr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:_T(this)}}},Qw=e=>qr(t=>{let n=Object.create(Zw);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=mw(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Set,awaiters:/* @__PURE__ */ new Set},cc(n)}),$w=e=>Qw({capacity:e}),eT=e=>Qw({capacity:e,strategy:`dropping`}),tT=/*#__PURE__*/ O(2,(e,t)=>fc(()=>nT(e,t)?yT:e.state._tag===`Open`&&e.strategy===`suspend`?OT(e,t):vT)),nT=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(ww(e.messages),_w(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(_w(e.messages,t),ST(e),!0):(_w(e.messages,t),CT(e),!0):!1,rT=/*#__PURE__*/ O(2,(e,t)=>Oc(n=>{let r=iT(e,t);return r.length===0||e.strategy===`dropping`?n(Vr(r)):kT(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),iT=(e,t)=>{if(e.state._tag!==`Open`)return Va(t);if(e.capacity===1/0||e.strategy===`sliding`)return yw(e.messages,t),e.strategy===`sliding`&&Sw(e.messages,e.messages.length-e.capacity),CT(e),[];let n=e.capacity<=0?e.state.takers.size:e.capacity-e.messages.length;if(n===0)return Va(t);let r=[],i=0;for(let a of t)i<n?_w(e.messages,a):r.push(a),i++;return CT(e),r},aT=/*#__PURE__*/ O(2,(e,t)=>dc(()=>oT(e,t))),oT=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Wr(t),r=Nte(n,bT);return e.state.offers.size===0&&e.messages.length===0?(NT(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},CT(e),!0)},sT=e=>aT(e,Ar(ri())),cT=e=>oT(e,Ar(ri())),lT=e=>dc(()=>uT(e)),uT=e=>{if(e.state._tag===`Done`)return!1;xw(e.messages);let t=e.state.offers;NT(e,e.state._tag===`Open`?xT:e.state.exit);for(let e of t)AT(e);return!0},dT=e=>pT(e,1,1/0),fT=e=>fc(()=>{let t=Ka();return Rc(up(du({while:wt,body:Ct(dT(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>xc),t)}),pT=/*#__PURE__*/ O(3,(e,t,n)=>(t=ya(t),n=ya(n),TT(()=>wT(e,t,n)??Kc(DT(e,()=>ET(e,t)),pT(e,t,n))))),mT=e=>TT(()=>gT(e)??Kc(DT(e,()=>ET(e,1)),mT(e))),hT=e=>TT(()=>{let t=gT(e);return t===void 0?cc(Di()):t._tag===`Success`?cc(Oi(t.value)):cc(Di())}),gT=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=ww(e.messages);return MT(e),Vr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=jT(e.state.offers);return MT(e),Vr(t)}},_T=e=>e.state._tag===`Done`?0:e.messages.length,vT=/*#__PURE__*/ Vr(!1),yT=/*#__PURE__*/ Vr(!0),bT=/*#__PURE__*/ Gr(/*#__PURE__*/ ri()),xT=/*#__PURE__*/ $c(),ST=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(nl),e.messages.length===0))break}},CT=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,ST(e)},0))},wT=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Vr([]);if(!ET(e,t))return;let r=e.messages.length>0?Sw(e.messages,n):[jT(e.state.offers)];return MT(e),Vr(r)},TT=/*#__PURE__*/ zr({op:`QueueTake`,[ur](e){let t=this[lr]();return _r(t)?t[ur](e):t}}),ET=(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,DT=(e,t)=>Oc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(nl);let r={ready:t,resume:n};return e.state.takers.add(r),dc(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),OT=(e,t)=>Oc(n=>nT(e,t)?n(yT):kT(e,{_tag:`Single`,message:t,resume:n})),kT=(e,t)=>{if(e.state._tag!==`Open`)return AT(t);let n=e.state.offers;return n.add(t),dc(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&NT(e,e.state.exit))})},AT=e=>e._tag===`Single`?e.resume(vT):e.resume(Vr(e.remaining.slice(e.offset))),jT=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(yT),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Vr([]))),n},MT=e=>{if(e.state._tag===`Done`)return dp(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(NT(e,e.state.exit),dp(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`)_w(e.messages,t.message),e.state.offers.delete(t),t.resume(yT);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;_w(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Vr([]))}let r=e.state;if(r._tag===`Done`)return dp(r.exit.cause)}return!1},NT=(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()},PT=e=>new IT(e),FT=(e,t,n)=>Oc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),dc(()=>{e.waiters.delete(i)})});var IT=class{waiters=/*#__PURE__*/ new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=fc(()=>this.free<e?FT(this,e,t):(this.taken+=e,cc(e)));return t}takeIfAvailable(e){return fc(()=>this.free<e?cc(!1):(this.taken+=e,cc(!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 qr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),xc))}release(e){return qr(t=>cc(this.releaseUnsafe(t,e)))}get releaseAll(){return qr(e=>cc(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>lu(n=>{let r=fc(()=>{if(this.free<e){let t=FT(this,e,xc);return Xc(n(t),()=>r)}return this.taken+=e,Gl(n(t),()=>{this.releaseUnsafe(Js(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>lu(n=>this.free<e?_c:(this.taken+=e,Gl(n(Gc(t)),()=>{this.releaseUnsafe(Js(),e)},!0)))}};const LT=e=>dc(()=>new IT(e)),RT=`~effect/Channel`,zT=e=>A(e,RT),BT={[RT]:{_Env:k,_InErr:k,_InElem:k,_OutErr:k,_OutElem:k},pipe(){return bt(this,arguments)}},VT=e=>{let t=Object.create(BT);return t.transform=(t,n)=>zp(e(t,n),e=>N(Tp(e))),t},HT=(e,t)=>VT((n,r)=>R(GT(e)(n,r),e=>t(e,r))),UT=e=>VT((t,n)=>e),WT=e=>VT(B(function*(t,n){let r=xf(n),i=e=>Sf(r,mp(e)),a=yield*hm(e(t,n,r),i);return hm(a,i)})),GT=e=>e.transform,KT=(e,t,n)=>Qw({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(Mp(t=>yf(e,lT(t))),Mp(n=>_f(t(n),e).pipe(zp(e=>aT(n,e)),Mm(e)))),qT=(e,t)=>VT((n,r)=>z(KT(r,e,t),dT)),JT=e=>VT((t,n)=>Sp(()=>GT(e())(t,n))),YT=e=>UT(P(()=>{let t=e();return Sp(()=>{let e=t.next();return e.done?Md(e.value):N(e.value)})})),XT=e=>tE(N(e)),ZT=/*#__PURE__*/ UT(/*#__PURE__*/ N(/*#__PURE__*/ Md())),QT=e=>UT(N(L(e))),$T=e=>UT(Tp(e)),eE=e=>$T(gd(e)),tE=e=>UT(P(()=>{let t=!1;return Sp(()=>t?Md():(t=!0,e))})),nE=e=>UT(R(e,()=>Md())),rE=e=>UT(N(dT(e))),iE=e=>VT((t,n)=>aE({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),aE=e=>{let t=e.readable.getReader(),n=e.exit??dw(void 0),r=Sp(()=>n.current?n.current:Qp(bp({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Tp(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Md():N(qa(t))}));return Fp(yf(e.scope,e.releaseLockOnEnd?P(()=>t.releaseLock()):yp(()=>t.cancel().catch(Dt))),r)},oE=/*#__PURE__*/ O(2,(e,t)=>HT(e,e=>P(()=>{let n=0;return z(e,e=>t(e,n++))}))),sE=/*#__PURE__*/ O(2,(e,t)=>cE(e,e=>N(t(e)))),cE=/*#__PURE__*/ O(2,(e,t)=>HT(e,e=>N(up(e,e=>R(t(e),Md))))),lE=e=>e===void 0||e!==`unbounded`&&e<=1,uE=/*#__PURE__*/ O(e=>zT(e[0]),(e,t,n)=>lE(n?.concurrency)?dE(e,t):fE(e,t,n)),dE=(e,t)=>VT((n,r)=>{let i=0;return z(GT(e)(n,r),R(e=>t(e,i++)))}),fE=(e,t,n)=>WT(B(function*(r,i,a){let o=0,s=yield*GT(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*$w(0);yield*yf(a,lT(l));let u=Fm(yield*em()),d=ow(a);if(n.unordered){let e=PT(c),n=Ct(e.release(1)),r=Qp({onFailure:e=>R(aT(l,e),n),onSuccess:e=>R(tT(l,e),n)});yield*e.take(1).pipe(R(()=>s),R(e=>{let n=o++;return d(u(r(Sp(()=>t(e,n))))),F}),Tm({disableYield:!0}),zp(t=>e.withPermits(c-1)(aT(l,t))),Mm(a))}else{let e=yield*$w(c-2);yield*yf(a,lT(e)),yield*mT(e).pipe(ore,R(e=>tT(l,e)),Tm({disableYield:!0}),zp(e=>aT(l,e)),Mm(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,oT(l,e.cause))};yield*s.pipe(R(i=>{if(n)return Tp(n);let a=o++,s=u(Sp(()=>t(i,a)));return d(s),s.addObserver(r),tT(e,rw(s))}),Tm({disableYield:!0}),zp(t=>tT(e,Vd(t)).pipe(jp(aT(e,t)))),Mm(a))}return mT(l)})),Oae=/*#__PURE__*/ O(e=>zT(e[0]),(e,t,n)=>lE(n?.concurrency)?kae(e,t):Aae(e,t,n)),kae=(e,t)=>VT((n,r)=>z(GT(e)(n,r),e=>{let i,a,o=R(e,e=>(a??=xf(r),Zm(GT(t(e))(n,a),e=>(i=s(e),i)))),s=up(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Sf(a,Gd);return a=void 0,R(t,()=>o)});return Sp(()=>i??o)})),Aae=(e,t,n)=>e.pipe(oE(t),Iae(n)),jae=e=>Oae(e,k),Mae=e=>HT(e,e=>{let t,n=0,r=Sp(function r(){if(t===void 0)return R(e,e=>{switch(e.length){case 0:return r();case 1:return N(e[0]);default:return t=e,N(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),N(i)});return N(r)}),pE=/*#__PURE__*/ O(2,(e,t)=>VT((n,r)=>{let i=xf(r);return z(GT(e)(n,i),e=>{let a=e.pipe(zp(e=>{if(dp(e))return Tp(e);let o=i;return i=xf(r),Sf(o,Vd(e)).pipe(jp(GT(t(e))(n,i)),R(e=>(a=e,e)))}));return Sp(()=>a)})})),Nae=/*#__PURE__*/ O(2,(e,t)=>pE(e,e=>nE(R(t(e),t=>Tp(e))))),Pae=/*#__PURE__*/ O(3,(e,t,n)=>pE(e,e=>{let r=t(e);return wa(r)?$T(r.failure):n(r.success,e)})),mE=/*#__PURE__*/ O(2,(e,t)=>Pae(e,wd,e=>t(e))),Fae=e=>mE(e,eE),Iae=/*#__PURE__*/ O(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>WT(B(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:PT(s),l=yield*cw(!0),u=/* @__PURE__ */ new Set,d=yield*$w(t);yield*yf(o,lT(d));let f=yield*GT(e)(i,a);return yield*I(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*jm(f),yield*Xp(c.take(1),jp(rw(e),wp))));let t=e===void 0?yield*f:yield*rw(e),n=xf(o),r=yield*GT(t)(i,n);for(;u.size>=s;){let e=ja(u);u.delete(e),u.size===0&&(yield*l.open),yield*iw(e)}let a=yield*r.pipe(Mp(()=>ire),R(e=>tT(d,e)),Tm({disableYield:!0}),hm(B(function*(e){let t=mp(e),r=yield*Pp(Sf(n,t));if(!u.has(a))return;let i=Yd([t,r]);qd(i)&&(yield*aT(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),jm);l.closeUnsafe(),u.add(a)}}).pipe(zp(e=>{let t=pp(e);return Ta(t)?l.whenOpen(aT(d,e)):aT(d,e)}),Mm(o)),mT(d)}))),Lae=/*#__PURE__*/ O(e=>zT(e[0])&&zT(e[1]),(e,t,n)=>WT(B(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*$w(0);yield*yf(a,lT(s));let c=0;function l(e,t){if(c++,!dp(t))return aT(s,t);switch(o){case`both`:return c===2?aT(s,t):F;case`left`:case`right`:return e===o?aT(s,t):F;case`either`:return aT(s,t)}}let u=(e,t,n)=>GT(t)(r,n).pipe(R(e=>e.pipe(R(e=>tT(s,e)),Tm)),hm(t=>gm(mp(t),e=>Sf(n,e)).pipe(Qp({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Mm(a));return yield*u(`left`,e,xf(a)),yield*u(`right`,t,xf(a)),mT(s)}))),Rae=()=>VT((e,t)=>P(()=>{let t=``,n=!1,r=Di();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
17
|
`);for(n&&=(o===0&&(e=1,o=a.indexOf(`
|
|
18
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
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 Ga(r)?r:null}let a=Sp(()=>r._tag===`Some`?Md(r.value):ere(e,{onSuccess:o,onFailure:Tp,onDone:e=>{if(r=ki(e),t.length>0){let e=t;return t=``,n=!1,N([e])}return Md(e)}}));function o(e){let t=i(e);return t===null?a:N(t)}return a})),Rae=/*#__PURE__*/ O(2,(e,t)=>HT((n,r)=>R(KT(e)(n,r),e=>KT(t)(e,r)))),zae=/*#__PURE__*/ O(2,(e,t)=>HT((n,r)=>R(KT(e)(n,r),e=>{let n=zp(e,e=>dp(e)?Tp(e):Dp(jd(e)));return z(KT(t)(n,r),e=>Bp(e,e=>Ad(e)?Tp(e.value):Dp(e)))}))),gE=e=>HT((t,n)=>{let r;return N(Sp(()=>r||e.pipe(_f(n),R(e=>KT(e)(t,n)),R(e=>r=e))))}),Bae=/*#__PURE__*/ O(2,(e,t)=>GT((n,r,i)=>vf(i,t).pipe(jp(KT(e)(n,r))))),Vae=/*#__PURE__*/ O(2,(e,t)=>UT(e,e=>N(up(e,e=>R(t,()=>Md(e)))))),Hae=/*#__PURE__*/ O(2,(e,t)=>Bae(e,e=>t)),_E=(e,t,n)=>Sp(()=>{let r=gf(),i=KT(e)(Md(),r);return up(R(i,t),n||N).pipe(vm(e=>Sf(r,e)))}),Uae=/*#__PURE__*/ O(2,(e,t)=>HT((n,r)=>z(im(KT(e)(n,r),t),im(t)))),vE=/*#__PURE__*/ O(2,(e,t)=>_E(e,e=>Em(R(e,t),{disableYield:!0}))),Wae=e=>Sp(()=>{let t=Symbol(),n=t;return _E(e,e=>Em(R(e,e=>(n=e,F)),{disableYield:!0}),()=>n===t?xp:rre(n))}),yE=/*#__PURE__*/ O(3,(e,t,n)=>Sp(()=>{let r=t();return _E(e,e=>vp({while:wt,body:()=>e,step:e=>{r=n(r,e)}}),()=>N(r))})),bE=(e,t)=>KT(e)(Md(),t),xE=`~effect/PlatformError`;var SE=class extends (/*#__PURE__*/ Vo(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},Gae=class extends Bo{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},CE=class extends (/*#__PURE__*/ Vo(`PlatformError`)){constructor(e){`cause`in e?super({reason:e,cause:e.cause}):super({reason:e})}[xE]=xE;get message(){return this.reason.message}};const wE=e=>new CE(new Gae(e)),TE=e=>new CE(new SE(e)),Kae={_R:k,_E:k,_A:k},EE=function(e){this.channel=e};EE.prototype={"~effect/Stream":Kae,pipe(){return bt(this,arguments)}};const qae=e=>new EE(e),DE=`~effect/Sink`,OE=/*#__PURE__*/ N([void 0]),Jae={_A:k,_In:k,_L:k,_E:k,_R:k},Yae={[DE]:Jae,pipe(){return bt(this,arguments)}},kE=e=>A(e,DE),AE=e=>jE((t,n)=>KT(e)(t,n).pipe(R(Em({disableYield:!0})),up(N))),jE=e=>{let t=Object.create(Yae);return t.transform=e,t},Xae=e=>HT((t,n)=>N(R(e.transform(t,n),Md))),ME=/*#__PURE__*/ jE(e=>up(Em(e,{disableYield:!0}),()=>OE)),Zae=e=>Qae(_p(t=>e(t),{discard:!0})),Qae=e=>jE(t=>t.pipe(R(e),Em({disableYield:!0}),up(()=>OE))),$ae=e=>AE(gE(z(e,Xae))),NE=`~effect/RcMap`,eoe=e=>({[NE]:NE,lookup:e.lookup,context:e.context,scope:e.scope,idleTimeToLive:e.idleTimeToLive,capacity:e.capacity,state:{_tag:`Open`,map:xae()},pipe(){return bt(this,arguments)}}),toe=e=>kp(t=>{let n=t.context,r=da(n,mf),i=eoe({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?kt(e.idleTimeToLive,ao):Ct(ao(e.idleTimeToLive??po)),capacity:Math.max(e.capacity??1/0,0)});return Fp(vf(r,()=>{if(i.state._tag===`Closed`)return F;let e=i.state.map;return i.state={_tag:`Closed`},_p(e,([,e])=>Pp(FE(e))).pipe(Mp(()=>P(()=>{Tae(e)})))}),i)}),PE=/*#__PURE__*/ O(2,(e,t)=>Tm(n=>{if(e.state._tag===`Closed`)return xm;let r=e.state,i=ow(),a=tw(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&Eae(e.state.map)>=e.capacity)return L(new Pd(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:ef(),scope:gf(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=roe(e,t,o),Cae(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(mf.key,o.scope);let a=Qi(n);Sp(()=>e.lookup(t)).pipe(Im(a),sw(o.scope)).addObserver(n=>{Jd(n)&&noe(e,t,o,a),uf(o.deferred,n)})}let s=ua(i.context,mf);return yf(s,o.finalizer).pipe(jp(n(nf(o.deferred))))})),noe=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=tw(e.state.map,t);i._tag!==`None`&&i.value===n&&(rw(e.state.map,t),!(n.refCount>0)&&FE(n).pipe(Im(r),sw(e.scope)))},FE=e=>e.fiber?aw(e.fiber).pipe(jp(Sf(e.scope,Gd))):Sf(e.scope,Gd),roe=(e,t,n)=>kp(r=>{if(n.refCount--,n.refCount>0)return F;if(e.state._tag===`Closed`)return FE(n);let i=tw(e.state.map,t);if(i._tag===`None`||i.value!==n)return FE(n);if(fo(n.idleTimeToLive))return rw(e.state.map,t),FE(n);if(!uo(n.idleTimeToLive))return F;let a=r.getRef($f);return n.expiresAt=a.currentTimeMillisUnsafe()+bo(n.idleTimeToLive),n.fiber||=Tm(function r(i){let o=a.currentTimeMillisUnsafe(),s=n.expiresAt-o;if(s<=0){if(e.state._tag===`Closed`||n.refCount>0)return F;let r=tw(e.state.map,t);return r._tag===`None`||r.value!==n?F:(rw(e.state.map,t),Sf(n.scope,Gd))}return R(i(a.sleep(_o(s))),()=>r(i))}).pipe(hm(P(()=>{n.fiber=void 0})),Im(r.context),sw(e.scope)),F}),IE={_tag:`Empty`},ioe={_tag:`Closed`},aoe={_A:k,_E:k};var ooe=class{"~effect/RcRef"=aoe;pipe(){return bt(this,arguments)}state=IE;acquire;context;scope;idleTimeToLive;constructor(e,t,n,r){this.acquire=e,this.context=t,this.scope=n,this.idleTimeToLive=r}};const soe=e=>kp(t=>{let n=t.context,r=da(n,mf),i=new ooe(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:ao(e.idleTimeToLive));return Fp(vf(r,()=>{let e=i.state;return i.state=ioe,e._tag===`Acquired`?Sf(e.scope,Gd):e._tag===`Acquiring`?aw(e.fiber):F}),i)}),coe=(e,t)=>{switch(e.state._tag){case`Closed`:return xm;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?Fp(aw(t.fiber),t):N(t)}case`Acquiring`:{let n=e.state;return n.awaiters++,LE(e,n,t)}case`Empty`:{let n={_tag:`Acquiring`,fiber:void 0,awaiters:1,acquired:void 0};e.state=n;let r=gf(),i=im(e.acquire,aa(e.context,mf,r)).pipe(R(t=>{if(e.state!==n)return xm;let i={_tag:`Acquired`,value:t,scope:r,fiber:void 0,refCount:n.awaiters,invalidated:!1};return e.state=i,n.acquired=i,N(i)}),vm(t=>Kd(t)?F:(e.state===n&&(e.state=IE),Sf(r,t))));return n.fiber=Im(ow().context)(i),LE(e,n,t)}}},LE=(e,t,n)=>vm(n(iw(t.fiber)),n=>{let r=t.acquired;return r===void 0?--t.awaiters>0||e.state!==t?F:(e.state=IE,aw(t.fiber)):qd(n)?RE(e,r):F}),loe=e=>{let t=e;return Tm(e=>R(um,n=>R(coe(t,e),e=>Fp(vf(n,()=>RE(t,e)),e.value))))},RE=(e,t)=>{if(t.refCount--,t.refCount>0)return F;let n=e.idleTimeToLive;return n===void 0||t.invalidated?(e.state===t&&(e.state=IE),Sf(t.scope,Gd)):(uo(n)&&(t.fiber=Tm(r=>R(r(Yp(n)),()=>e.state===t&&t.refCount===0?(e.state=IE,Sf(t.scope,Gd)):F)).pipe(hm(P(()=>{t.fiber=void 0})),Im(e.context),sw(e.scope))),F)},uoe=soe,zE=loe,BE=e=>A(e,`~effect/Stream`),VE=qae,HE=e=>VE(nE(z(e,qa))),doe=e=>UE(P(()=>{let t=!0,n=N(qa(void 0)),r=fre(n,e);return Sp(()=>t?(t=!1,n):r)})),UE=e=>VE(WT(e)),WE=(e,t)=>VE(HT((n,r)=>R(bE(e.channel,r),e=>t(e,r)))),GE=e=>e.channel,foe=(e,t)=>VE(JT(e,t)),KE=/*#__PURE__*/ VE(QT),poe=e=>VE(ZT(qa(e))),qE=e=>VE(YT(()=>e().channel)),moe=e=>VE($T(e)),hoe=e=>VE(eE(e)),goe=e=>Ga(e)?VE(ZT(e)):KE,JE=e=>VE(iE(e)),YE=e=>VE(aE(e)),XE=e=>VE(gE(z(e,GE))),ZE=/*#__PURE__*/ O(2,(e,t)=>qE(()=>{let n=0;return VE(sE(e.channel,Ja(e=>t(e,n++))))})),_oe=/*#__PURE__*/ O(e=>BE(e[0]),(e,t,n)=>e.channel.pipe(jae,dE(t,n),sE(qa),VE)),voe=/*#__PURE__*/ O(2,(e,t)=>VE(dE(e.channel,t))),yoe=/*#__PURE__*/ O(2,(e,t)=>{let n=VE(Aae(XT(()=>boe(e,t))));return QE.set(n,[e,t]),n}),QE=/*#__PURE__*/ new WeakMap;function*boe(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=QE.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}const $E=/*#__PURE__*/ O(e=>BE(e[0])&&BE(e[1]),(e,t,n)=>VE(Iae(GE(e),GE(t),n))),xoe=/*#__PURE__*/ O(2,(e,t)=>e.channel.pipe(mE(e=>t(e).channel),VE)),Soe=/*#__PURE__*/ O(2,(e,t)=>e.channel.pipe(Mae(t),VE)),Coe=/*#__PURE__*/ O(2,(e,t)=>VE(hE(e.channel,e=>t(e).channel))),woe=e=>VE(Pae(e.channel)),Toe=/*#__PURE__*/ O(2,(e,t)=>{let n=xa(t);return n===0?e:WE(e,(e,t)=>P(()=>{let t=0,r=e.pipe(R(e=>t>=n?N(e):(t+=e.length,t<=n?r:N(e.slice(n-t)))));return r}))}),eD=/*#__PURE__*/ O(2,(e,t)=>WE(e,(e,n)=>P(()=>{let r,i,a=Sp(()=>{if(i!==void 0){let e=i;return i=void 0,N(e)}return e}).pipe(Lp(e=>(r=Hd(e),Md()))),o=z(Sp(()=>t.transform(a,n)),([e,t])=>(i=t,qa(e)));return Sp(()=>r||o)}))),Eoe=/*#__PURE__*/ O(2,(e,t)=>VE(zae(e.channel,t))),Doe=/*#__PURE__*/ O(e=>BE(e[0]),(e,t)=>qE(()=>{let n=new TextDecoder(t?.encoding);return ZE(e,e=>n.decode(e,{stream:!0}))})),Ooe=e=>qE(()=>{let t=new TextEncoder;return ZE(e,e=>t.encode(e))}),koe=e=>e.channel.pipe(Rae(Lae()),VE),Aoe=/*#__PURE__*/ O(2,(e,t)=>VE(Vae(e.channel,t))),joe=/*#__PURE__*/ O(2,(e,t)=>VE(Hae(e.channel,t))),tD=/*#__PURE__*/ O(2,(e,t)=>VE(Uae(e.channel,t))),nD=/*#__PURE__*/ O(2,(e,t)=>fm(n=>bE(e.channel,n).pipe(R(e=>t.transform(e,n)),z(([e])=>e)))),Moe=e=>yE(e.channel,()=>[],(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n]);return e}),Noe=e=>z(Wae(e.channel),zi(Kee)),Poe=/*#__PURE__*/ O(2,(e,t)=>vE(e.channel,e=>{let n=0;return vp({while:()=>n<e.length,body:()=>t(e[n++]),step:Dt})})),rD=/*#__PURE__*/ O(2,(e,t)=>vE(e.channel,t)),Foe=e=>yE(e.channel,()=>``,(e,t)=>e+t.join(``)),iD=/*#__PURE__*/ O(e=>BE(e[0]),(e,t,n)=>{let r,i,a=cw(!1);return new ReadableStream({start(n){i=Fm(im(rD(e,e=>a.whenOpen(P(()=>{a.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0}))),t)),i.addObserver(e=>{e._tag===`Failure`?n.error(Sd(e.cause)):n.close()})},pull(){return new Promise(e=>{r=e,a.openUnsafe()})},cancel(){if(i)return Lm(Ip(aw(i)))}},n?.strategy)}),Ioe=/*#__PURE__*/ O(e=>BE(e[0]),(e,t)=>z(tm(),n=>iD(e,n,t))),aD=`~effect/FileSystem`,oD=/*#__PURE__*/ j(`effect/FileSystem`),Loe=e=>oD.of({...e,[aD]:aD,exists:t=>Ot(e.access(t),Fp(!0),Rp(`PlatformError`,e=>e.reason._tag===`NotFound`?N(!1):L(e))),readFileString:(t,n)=>R(e.readFile(t),e=>Op({try:()=>new TextDecoder(n).decode(e),catch:e=>TE({module:`FileSystem`,method:`readFileString`,description:`invalid encoding`,cause:e})})),stream:B(function*(t,n){let r=yield*e.open(t,{flag:`r`}),i=n?.offset===void 0?void 0:Ih(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:Ih(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return UE(N(R(Sp(()=>a!==void 0&&a<=o?Md():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),Ni({onNone:()=>Md(),onSome:e=>(o+=BigInt(e.length),N(qa(e)))}))))},XE),sink:(t,n)=>Ot(e.open(t,{...n,flag:n?.flag??`w`}),z(e=>Zae(t=>e.writeAll(t))),$ae),writeFileString:(t,n,r)=>R(Op({try:()=>new TextEncoder().encode(n),catch:e=>TE({module:`FileSystem`,method:`writeFileString`,description:`could not encode string`,cause:e})}),n=>e.writeFile(t,n,r))}),sD=`~effect/FileSystem/File`;var Roe=class extends (/*#__PURE__*/ j()(`effect/FileSystem/WatchBackend`)){};const cD=`~effect/Path`,lD=/*#__PURE__*/ j(`effect/Path`);function zoe(e){return{_tag:`Value`,value:e}}function Boe(e,t){return{_tag:`Record`,keys:e,value:t}}function Voe(e,t){return{_tag:`Array`,length:e,value:t}}const Hoe=/*#__PURE__*/ ya(`effect/ConfigProvider`,{defaultValue:()=>mD()}),Uoe={...gr,toJSON(){return{_id:`ConfigProvider`}}},Woe=e=>e;function Goe(e,t){let n=Object.create(Uoe);return n.load=e,n.mapInput=t,n}function uD(e,t){return Goe(n=>e(t(n)),n=>uD(e,e=>n(t(e))))}function dD(e){return uD(e,Woe)}function fD(e,t){return e===``&&!t?void 0:e}function pD(e,t){let n=t?.preserveEmptyStrings===!0,r=hD(e);return dD(t=>N(gD(r,e,t,n)))}function mD(e){return pD(e?.env??{...globalThis.process?.env,...import.meta.env},{preserveEmptyStrings:e?.preserveEmptyStrings})}function hD(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 gD(e,t,n,r){let i=n.map(String).join(`_`),a=fD(Object.hasOwn(t,i)?t[i]:void 0,r),o=_D(e,n),s=o?.children?Object.keys(o.children):[];return s.length===0?a===void 0?void 0:zoe(a):s.every(Gee)?Voe(Math.max(...s.map(e=>parseInt(e,10)))+1,a):Boe(new Set(s),a)}function _D(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 vD=/*#__PURE__*/ Di(od),yD=`~effect/Config`;var bD=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}};const xD={.../*#__PURE__*/ si({label:`Config`,evaluate(e){return this.parse(e.getRef(Hoe))}}),[yD]:yD,toJSON(){return{_id:`Config`}}};function SD(e){let t=Object.create(xD);return t.evaluator=e,t.parse=t=>Qm(e(t,[]),Ap),t}const CD=(e,t,n)=>e.evaluator(t,n),wD=/*#__PURE__*/ O(2,(e,t)=>SD((n,r)=>Ym(CD(e,n,r),e=>Ea(e)?Sa(t):e))),TD=e=>Zt(e,`SourceError`),ED=()=>`<configuration>`,DD=e=>t=>zp(t,t=>Tp(md(t.reasons.map(e)))),OD=(e,t)=>e.load(t).pipe(DD(e=>fd(e)?vd(e.error).annotate(Ld(e)):e),Ym(n=>({provider:e,path:t,node:n,toString:ED}))),kD=(e,t)=>OD(e.provider,[...e.path,t]),AD=(e,t)=>Eb(_y,e,new Iv(bv(e=>t(e)),vv())),jD=e=>{switch(e._tag){case`Union`:return e.types.every(jD);case`Objects`:case`Arrays`:case`Suspend`:return!1;default:return!0}},MD=(e,t)=>{switch(e._tag){case`Objects`:return t?._tag===`Record`;case`Arrays`:return t?._tag===`Array`;case`Union`:return e.types.some(e=>MD(e,t));case`Suspend`:return MD(e.thunk(),t);default:return t?.value!==void 0}},ND=/*#__PURE__*/ At(e=>{let t=/* @__PURE__ */ new WeakSet,n=Bre(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>cx(e.parameter)),r=B(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*kD(n,e);t.node!==void 0&&ar(a,e,t)}return a});return AD(e.recur(n,e=>e),r)}case`Arrays`:{let t=B(function*(e){if(e.node?._tag!==`Array`)return;let t=[];for(let n=0;n<e.node.length;n++)t.push(yield*kD(e,n));return t});return AD(e.recur(n),t)}case`Union`:for(let t of e.types)n(t);if(!jD(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 AD(e,e=>N(e.node?.value))});return n(e)});function PD(e,t){let n=XC(e),r=Ab(n.ast),i=lx(gS(ND(n.ast))),a=typeof t==`string`?[t]:t??[];return SD((e,t)=>{let n=[...t,...a];return OD(e,n).pipe(Qm(e=>i(e).pipe(Ym(Sa),$m(t=>{let i=new bD(new iS(n.length>0?new L_(n,t):t));return MD(r,e.node)?L(i):N(Ca(i))}))),DD(e=>pd(e)&&TD(e.defect)?_d(new bD(e.defect)).annotate(Ld(e)):e))})}const FD=/*#__PURE__*/ dC.check(/*#__PURE__*/ lC({minimum:1,maximum:65535})),ID=e=>It(e)||globalThis.Array.isArray(e);function LD(e){return PD(H,e)}function RD(e,t,n){let r=ID(t),i=r?n:t,a=W(e),o=i?.separator??`,`;return PD(G([H.pipe(US(XC(a),{decode:jv(i),encode:pv(vv({strict:!1}),yv(e=>e.join(o)))})),a]),r?t:void 0)}function zD(e){return PD(qS,e)}function BD(e){return PD(FD,e)}function VD(e){return PD(VC(H),e)}const HD=2**48-1,UD=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,WD=(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)),HD),r=``;for(let e=45;e>=0;e-=5)r+=UD[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+=UD[i>>>a&31];i&=(1<<a)-1}return r},GD=e=>e.toString(16).padStart(2,`0`),KD=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,GD).join(``)).join(`-`),qD=()=>globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));function JD(e=qD()){return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e}const YD=e=>KD(e===void 0?JD():JD(e)),XD=2**48-1;function ZD(e,t=qD()){let n=Math.min(Math.max(0,Math.trunc(e)),XD);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 QD=(e,t)=>KD(t===void 0?ZD(e):ZD(e,t)),$D=`~effect/Crypto`,eO=/*#__PURE__*/ j(`effect/Crypto`),tO=e=>{let t=e.randomBytes,n=e=>z(nO(`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 eO.of({[$D]:$D,randomBytes:n,nextDoubleUnsafe:i,nextIntUnsafe:a,digest:e.digest,random:P(()=>i()),randomBoolean:P(()=>i()>.5),randomInt:P(()=>a()),randomBetween:(e,t)=>P(()=>Qne(e,t,i())),randomIntBetween(e,t,n){let r=n?.halfOpen===!0?0:1;return P(()=>{let n=Math.ceil(e),a=Math.floor(t);return Math.floor(i()*(a-n+r))+n})},randomShuffle:e=>P(()=>{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:P(()=>YD(t(16))),randomUUIDv7:Vm(e=>N(QD(e.currentTimeMillisUnsafe(),t(16)))),randomULID:Vm(e=>N(WD(e.currentTimeMillisUnsafe(),t(10))))})},nO=(e,t)=>Number.isSafeInteger(t)&&t>=0?N(t):L(TE({module:`Crypto`,method:e,description:`size must be a non-negative safe integer`})),rO=e=>kp(t=>(dd(t,e),F)),iO=`~effect/ErrorReporter/ignore`,aO=`~effect/Match/Matcher`,oO={[aO]:{_input:k,_filters:k,_remaining:k,_result:k,_return:k,_args:k},_tag:`TypeMatcher`,add(e){return sO(this.select,[...this.cases,e])},pipe(){return bt(this,arguments)}};function sO(e,t){let n=Object.create(oO);return n.select=e,n.cases=t,n}const cO={[aO]:{_input:k,_filters:k,_result:k,_return:k,_flavor:k},_tag:`ValueMatcher`,add(e){return Da(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?lO(this.provided,Sa(e.evaluate(this.provided))):this},pipe(){return bt(this,arguments)}};function lO(e,t){let n=Object.create(cO);return n.provided=e,n.value=t,n}const uO=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),dO=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(dO),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,dO(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},fO=()=>sO(k,[]),pO=e=>lO(e,Ca(e)),mO=(e,t)=>n=>n.add(uO(dO(e),t)),hO=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(uO(i,n))},gO=e=>t=>{let n=uO(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},_O=/*#__PURE__*/ hO(`_tag`),vO=/*#__PURE__*/ gO(`_tag`),yO=(...e)=>{let t=e.length;return n=>{for(let r=0;r<t;r++)if(n===e[r])return!0;return!1}},bO=e=>t=>{let n=xO(t);return Ta(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Da(r)?r.success:e(r.failure,...t)}},xO=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?Sa(t.evaluate(r,...n)):Ca(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 Sa(t.evaluate(r,...n))}return Ca(r)}},SO=`effect/match/Match/exhaustive: absurd`,CO=e=>{let t=xO(e);if(Ta(t)){if(Da(t))return t.success;throw Error(SO)}return(...e)=>{let n=t(...e);if(Da(n))return n.success;throw Error(SO)}},wO=fO,TO=pO,EO=mO,DO=_O,OO=vO,kO=yO,AO=It,jO=Lt,MO=Rt,NO=bO,PO=CO,FO={"~effect/Ref":{_A:k},...gr,toJSON(){return{_id:`Ref`,ref:this.ref}}},IO=e=>{let t=Object.create(FO);return t.ref=fw(e),t},LO=e=>P(()=>IO(e)),RO=e=>P(()=>e.ref.current),zO=/*#__PURE__*/ O(2,(e,t)=>P(()=>pw(e.ref,t))),BO=/*#__PURE__*/ O(2,(e,t)=>P(()=>{let n=e.ref.current;return e.ref.current=t,n})),VO=/*#__PURE__*/ O(2,(e,t)=>e===void 0?void 0:t(e)),HO=`~effect/Stdio`,UO=/*#__PURE__*/ j(HO),WO=e=>({[HO]:HO,stdinIsTerminal:N(!1),stdoutIsTerminal:N(!1),...e}),GO=`~effect/Terminal`,KO=`~effect/Terminal/QuitError`;var qO=class extends (/*#__PURE__*/ qC(`QuitError`)({_tag:/*#__PURE__*/ ZS(`QuitError`)})){[KO]=KO};const JO=/*#__PURE__*/ j(`effect/Terminal`),YO=e=>JO.of({...e,[GO]:GO}),XO=/*#__PURE__*/ $C(),ZO=/*#__PURE__*/ $C(),QO=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,$O={[QO]:QO,...Qn,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},ek=e=>Object.setPrototypeOf({...e},$O),tk=e=>{let t=(t,n)=>e(t).pipe(z(e=>Doe(n?.includeStderr===!0?e.all:e.stdout)),XE),n=(e,n)=>koe(t(e,n));return nk.of({spawn:e,exitCode:t=>dm(R(e(t),e=>e.exitCode)),streamString:t,streamLines:n,lines:(e,t)=>Moe(n(e,t)),string:(e,n)=>Foe(t(e,n))})};var nk=class extends (/*#__PURE__*/ j()(`effect/process/ChildProcessSpawner`)){};const rk=`~effect/process/ChildProcess`,ik={.../*#__PURE__*/ si({label:`Command`,evaluate(e){return ua(e.context,nk).spawn(this)}}),[rk]:rk},ak=(e,t,n)=>Object.assign(Object.create(ik),{_tag:`StandardCommand`,command:e,args:t,options:n}),ok=function(...e){if(sk(e[0])){let[t,...n]=e,r=uk(t,n);return ak(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!sk(e[0])){let t=e[0];return function(e,...n){let r=uk(e,n);return ak(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return ak(t,[],n)}let[t,n=[],r={}]=e;return ak(t,n,r)},sk=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),ck=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},lk=e=>`fd${e}`,uk=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=dk(e,t,n,i,r);return n},dk=(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}=hk(r,a),l=gk(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>fk(e)):[fk(u)];return gk(l,d,s)},fk=e=>typeof e==`string`?e:String(e),pk=/*#__PURE__*/ new Set([` `,` `,`\r`,`
|
|
21
|
-
`]),
|
|
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+=mk[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},gk=(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)],_k=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},vk=(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 wE({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})},yk=e=>AE(cE(bk(e),e=>[e])),bk=e=>HT(t=>{let n=e.evaluate();return N(xk({...e,writable:n,pull:t}))}),xk=e=>e.pull.pipe(R(t=>{let n=0;return Cp(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(F)};return a(),P(()=>{i=!0,e.writable.off(`drain`,a)})})}),Em({disableYield:!0}),e.endOnDone===!1?k:up(t=>`closed`in e.writable&&e.writable.closed?Md(t):Cp(n=>{let r=()=>n(Md(t));return e.writable.once(`finish`,r),e.writable.end(),P(()=>{e.writable.off(`finish`,r)})})),Xp(Cp(t=>{let n=n=>t(L(e.onError(n)));return e.writable.once(`error`,n),P(()=>{e.writable.off(`error`,n)})}))),Sk=e=>VE(Ck(e)),Ck=e=>HT((t,n)=>Ok({scope:n,readable:e.evaluate(),onError:e.onError??kk,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),wk=e=>HT((t,n)=>{let r=e.evaluate(),i=fw(void 0),a=cw(!1);return xk({pull:t,writable:r,onError:e.onError??kk,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(zp(e=>dp(e)?F:(i.current=Vd(e),a.openUnsafe(),F)),Nm(n),R(()=>Ok({scope:n,exit:i,latch:a,readable:r,onError:e.onError??kk,chunkSize:e.chunkSize})))}),Tk=/*#__PURE__*/ O(2,(e,t)=>Eoe(e,wk(t))),Ek=(e,t)=>{let n=Ak(t?.maxBytes),r=t?.onError??kk;return Cp(t=>{let i=e(),a=[],o=0;return i.once(`error`,e=>{`closed`in i&&!i.closed&&i.destroy(),t(L(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(N(e.buffer));t(N(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(L(r(/* @__PURE__ */ Error(`maxBytes exceeded`)))))}),P(()=>{`closed`in i&&!i.closed&&i.destroy()})})},Dk=(e,t)=>z(Ek(e,t),e=>new Uint8Array(e)),Ok=e=>{let t=e.readable,n=e.closeOnDone??!0,r=e.exit??fw(void 0),i=e.latch??cw(!1);function a(){i.openUnsafe()}function o(t){r.current=Hd(e.onError(t)),i.openUnsafe()}function s(){r.current=Hd(jd()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=Sp(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?L(jd()):(i.closeUnsafe(),R(i.await,n));let o=qa(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return N(o)});return Fp(yf(e.scope,P(()=>{t.off(`readable`,a),t.off(`error`,o),t.off(`end`,s),n&&`closed`in e.readable&&!e.readable.closed&&e.readable.destroy()})),c)},kk=e=>new Fd(e),Ak=e=>e===void 0||e===1/0?void 0:Number(Ih(e)),jk=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Mk=(e,t,n)=>{let{commands:r}=Lk(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return vk(`ChildProcess`,e)(t,[i])},Nk=1e3,Pk=(e,t)=>{if(!cf(t))return!0;if(globalThis.process.platform===`win32`)return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},Fk=(e,t=()=>{})=>nt.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t),Ik=/*#__PURE__*/ Hf(nk,/* @__PURE__ */ I(function*(){let e=yield*oD,t=yield*lD,n=B(function*(n){if(!Ht(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=>BE(e)?`pipe`:e,a=e=>kE(e)?`pipe`:e,o=e=>{let t={stream:`pipe`,encoding:`utf-8`,endOnDone:!0};return Ht(e.stdin)?t:typeof e.stdin==`string`||BE(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 Ht(n)?{stream:`pipe`}:typeof n==`string`||kE(n)?{stream:n}:{stream:n.stream}},c=e=>{if(Ht(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=ck(n);Ut(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=B(function*(e,t,n){if(n.length===0)return{getInputFd:()=>ME,getOutputFd:()=>KE};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=ME;n&&`write`in n&&(t=yk({evaluate:()=>n,onError:t=>Mk(`fromWritable(fd${o})`,jk(t),e)})),a.stream&&(yield*Pm(nD(a.stream,t))),r.set(o,t);break}case`output`:{let t=KE;if(n&&`read`in n){let r=new it;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=Sk({evaluate:()=>r,onError:t=>Mk(`fromReadable(fd${o})`,jk(t),e)})}a.sink&&(t=eD(t,a.sink)),i.set(o,t);break}}}return{getInputFd:e=>r.get(e)??ME,getOutputFd:e=>i.get(e)??KE}}),d=(e,t,n)=>Sp(()=>{let r=ME;return Wt(t.stdin)&&(r=yk({evaluate:()=>t.stdin,onError:t=>Mk(`fromWritable(stdin)`,jk(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),BE(n.stream)?Fp(Pm(nD(n.stream,r)),r):N(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new it;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),Sk({evaluate:()=>n,onError:t=>Mk(`fromReadable(stdout)`,jk(t),e)})})():KE,a=t.stderr?(()=>{let n=new it;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),Sk({evaluate:()=>n,onError:t=>Mk(`fromReadable(stderr)`,jk(t),e)})})():KE;kE(n.stream)&&(i=eD(i,n.stream)),kE(r.stream)&&(a=eD(a,r.stream));let o=$E(i,a);return{stdout:i,stderr:a,all:o}},p=(e,t)=>Cp(n=>{let r=ef(),i=nt.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(L(Mk(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{uf(r,Bd(e))}),i.on(`spawn`,()=>{n(N([i,r]))}),P(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?Cp(n=>{Fk(t,t=>{n(t?L(Mk(`kill`,jk(t),e)):F)})}):Op({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>Mk(`kill`,jk(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`){Fk(e);return}try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>Sp(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return L(Mk(`kill`,t,e))}return F}),_=(e,t,n)=>Cp(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{if(clearTimeout(a),Date.now()>=i||!Pk(e,t)){o(),r(F);return}a=setTimeout(s,10)};return e.on(`exit`,s),s(),P(o)}),v=B(function*(e,t,n,r){let i=n=>m(e,t,n).pipe(Lp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),Ht(r?.forceKillAfter)?yield*_(t,n,Nk):(yield*_(t,n,bo(r.forceKillAfter)),Pk(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,Nk))),yield*nf(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=ck(n);return Ut(t)?e.getOutputFd(t):e.stdout}}},b=B(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*pm(p(e,_k(e.options,{cwd:_,env:y,stdio:b},process.platform)),B(function*([t,n]){if(yield*sf(n)){let[r]=yield*nf(n);(r!==0&&Wt(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*Kp(v(e,t,n,e.options)));return}g&&(yield*Kp(v(e,t,n,e.options)))})),C=ZO(x.pid);x.on(`exit`,t=>{t!==0&&Wt(t)&&h(x,e.options.killSignal??`SIGTERM`)});let w=P(()=>{g||=(x.ref(),!0)}),T=P(()=>(g&&=(x.unref(),!1),w)),ee=yield*d(e,x,t),{all:te,stderr:E,stdout:ne}=f(e,x,i,a),{getInputFd:re,getOutputFd:ie}=yield*u(e,x,m),ae=z(sf(S),e=>!e),oe=R(nf(S),([t,n])=>{if(Wt(t))return N(XO(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return L(Mk(`exitCode`,r,e))});return ek({pid:C,exitCode:oe,isRunning:ae,kill:t=>v(e,x,S,t),stdin:ee,stdout:ne,stderr:E,all:te,getInputFd:re,getOutputFd:ie,unref:T})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=Lk(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=XE(N(y(a[a.length-1],r.from))),l=r.to??`stdin`;if(l===`stdin`)a.push(yield*b(ok(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=ck(l);if(Ut(e)){let n=lk(e),r=t.options.additionalFds??{};a.push(yield*b(ok(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(ok(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>_p([...a].reverse(),t=>Kp(t.kill(e)),{discard:!0}),l=I(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return _p([...e].reverse(),e=>e,{discard:!0})});return ek({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 tk(b)})),Lk=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}},Rk=`~effect/http/HttpBody`,zk=`~effect/http/HttpBody/HttpBodyError`;var Bk=class extends (/*#__PURE__*/ Vo(`HttpBodyError`)){[zk]=zk},Vk=class{[Rk];constructor(){this[Rk]=Rk}[Yn](){return this.toJSON()}toString(){return zn(this,{ignoreToString:!0})}};const Hk=/*#__PURE__*/ new class extends Vk{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var Uk=class extends Vk{_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 Wk=(e,t)=>new Uk(e,t?.contentType,t?.contentLength);var Gk=class extends Vk{_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??=Yk(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 Kk=(e,t)=>new Gk(e,t??`application/octet-stream`,e.length),qk=/*#__PURE__*/ new TextEncoder,Jk=globalThis.Buffer,Yk=Jk===void 0?e=>qk.encode(e):e=>Jk.from(e,`utf8`),Xk=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),Jk!==void 0)return new Gk(void 0,t??`text/plain`,Jk.byteLength(e,`utf8`),e);let n=qk.encode(e);return new Gk(n,t??`text/plain`,n.length,e)},Zk=(e,t)=>Xk(JSON.stringify(e),t??`application/json`),Qk=(e,t)=>Op({try:()=>Xk(JSON.stringify(e),t??`application/json`),catch:e=>new Bk({reason:{_tag:`JsonError`},cause:e})}),$k=(e,t)=>{let n=ux(YC(e));return(e,r)=>n(e,t).pipe(Hp(e=>new Bk({reason:{_tag:`SchemaError`,issue:e},cause:e})),R(e=>Qk(e,r)))};var eA=class extends Vk{_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 tA=(e,t,n)=>new eA(e,t??`application/octet-stream`,n),nA=`~effect/http/HttpClientError`;var rA=class extends (/*#__PURE__*/ Vo(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[nA]=nA;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 iA=e=>e.endsWith(`Error`)?e.slice(0,-5):e,aA=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`;var oA=class extends (/*#__PURE__*/ Vo(`TransportError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return aA(iA(this._tag),this.description,this.methodAndUrl)}},sA=class extends (/*#__PURE__*/ Vo(`InvalidUrlError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return aA(iA(this._tag),this.description,this.methodAndUrl)}},cA=class extends (/*#__PURE__*/ Vo(`StatusCodeError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return aA(iA(this._tag),this.description,e)}},lA=class extends (/*#__PURE__*/ Vo(`DecodeError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return aA(iA(this._tag),this.description,e)}},uA=class extends (/*#__PURE__*/ Vo(`EmptyBodyError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return aA(iA(this._tag),this.description,e)}};const dA=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,fA=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],pA=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?Xg(Xg(e,`content-type`),`content-length`):(e=t.contentType===void 0?Xg(e,`content-type`):qg(e,`content-type`,t.contentType),t.contentLength===void 0?Xg(e,`content-length`):qg(e,`content-length`,t.contentLength.toString())),mA=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var hA=class extends (/*#__PURE__*/ Vo(`UrlError`)){};const gA=(e,t,n)=>wa({try:()=>{let r=new URL(e,_A());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,i)}return n!==void 0&&(r.hash=n),r},catch:e=>new hA({cause:e})}),_A=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},vA=`~effect/http/HttpClientRequest`,yA={[vA]:vA,...Qn,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Pn(this.headers),body:this.body.toJSON()}},pipe(){return bt(this,arguments)}};function bA(e,t,n,r,i,a){let o=Object.create(yA);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const xA=/*#__PURE__*/ bA(`GET`,``,l_,/*#__PURE__*/ Oi(),Wg,Hk),SA=e=>(t,n)=>TA(xA,{method:e,url:t,...n??void 0}),CA=/*#__PURE__*/ SA(`GET`),wA=/*#__PURE__*/ SA(`POST`),TA=/*#__PURE__*/ O(2,(e,t)=>{let n=e;return t.method&&(n=EA(n,t.method)),t.url&&(n=jA(n,t.url)),t.headers&&(n=OA(n,t.headers)),t.urlParams&&(n=MA(n,t.urlParams)),t.hash&&(n=NA(n,t.hash)),t.body&&(n=PA(n,t.body)),t.accept&&(n=kA(n,t.accept)),t.acceptJson&&(n=AA(n)),n}),EA=/*#__PURE__*/ O(2,(e,t)=>bA(t,e.url,e.urlParams,e.hash,e.headers,e.body)),DA=/*#__PURE__*/ O(3,(e,t,n)=>bA(e.method,e.url,e.urlParams,e.hash,qg(e.headers,t,n),e.body)),OA=/*#__PURE__*/ O(2,(e,t)=>bA(e.method,e.url,e.urlParams,e.hash,Jg(e.headers,t),e.body)),kA=/*#__PURE__*/ O(2,(e,t)=>DA(e,`Accept`,t)),AA=/*#__PURE__*/ kA(`application/json`),jA=/*#__PURE__*/ O(2,(e,t)=>{if(typeof t==`string`)return bA(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=a_(n.searchParams),i=Fi(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,bA(e.method,n.toString(),r,i,e.headers,e.body)}),MA=/*#__PURE__*/ O(2,(e,t)=>bA(e.method,e.url,u_(e.urlParams,t),e.hash,e.headers,e.body)),NA=/*#__PURE__*/ O(2,(e,t)=>bA(e.method,e.url,e.urlParams,ki(t),e.headers,e.body)),PA=/*#__PURE__*/ O(2,(e,t)=>bA(e.method,e.url,e.urlParams,e.hash,pA(e.headers,t),t)),FA=/*#__PURE__*/ O(2,(e,t)=>PA(e,Zk(t)));function IA(e){let t=gA(e.url,e.urlParams,Li(e.hash));return Da(t)?ki(t.success):Oi()}const LA=`~effect/http/HttpIncomingMessage`,RA=(e,t)=>{let n=uS(YC(e)),r=t?.reviver===void 0?void 0:uS(TC(YC(e),t));return e=>r===void 0?R(e.json,e=>n(e,t)):R(e.text,i=>i===``?R(e.json,e=>n(e,t)):r(i,t))},zA=/*#__PURE__*/ ya(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),BA=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=zm(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=zm(e.text)}catch{}let i={...t,headers:Pn(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},VA=`~effect/http/HttpClientResponse`,HA=(e,t)=>new UA(e,t);var UA=class extends $n{[LA];[VA];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[LA]=LA,this[VA]=VA}toJSON(){return BA(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=IA(this.request);return ji(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Gg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=pg(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Oi()}get stream(){return this.source.body?YE({evaluate:()=>this.source.body,onError:e=>new rA({reason:new lA({request:this.request,response:this,cause:e})})}):moe(new rA({reason:new uA({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return R(this.text,e=>Op({try:()=>e===``?null:JSON.parse(e),catch:e=>new rA({reason:new lA({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=z(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return R(this.text,e=>Op({try:()=>a_(new URLSearchParams(e)),catch:e=>new rA({reason:new lA({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=bp({try:()=>this.source.formData(),catch:e=>new rA({reason:new lA({request:this.request,response:this,cause:e})})}).pipe(ym,zm)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=bp({try:()=>this.source.arrayBuffer(),catch:e=>new rA({reason:new lA({request:this.request,response:this,cause:e})})}).pipe(ym,zm),this.arrayBufferBody}pipe(){return bt(this,arguments)}};const WA=e=>Kg({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Ni(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),GA=e=>{let t=XA(e);return Mi(t)||(t=KA(e),Mi(t))?t:qA(e)},KA=e=>{if(!(`b3`in e))return Oi();let t=e.b3.split(`-`);return t.length<2?Oi():ki(Qo({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},qA=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]?Oi():ki(Qo({traceId:e[`x-b3-traceid`],spanId:e[`x-b3-spanid`],sampled:e[`x-b3-flags`]===`1`||!e[`x-b3-sampled`]||e[`x-b3-sampled`]===`1`||e[`x-b3-sampled`]===`true`})),JA=/^[0-9a-f]{32}$/i,YA=/^[0-9a-f]{16}$/i,XA=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 JA.test(r)===!1||YA.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Oi():ki(Qo({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Oi()}},ZA={"http:":80,"https:":443,"ws:":80,"wss:":443},QA=(e,t)=>{let n=t.search.slice(1);if(e.attribute(`url.full`,t.toString()),e.attribute(`url.path`,t.pathname),n!==``&&e.attribute(`url.query`,n),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===``?ZA[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},$A=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,$g(a,i)?`<redacted>`:n[a])},ej=`~effect/http/HttpClient`,tj=/*#__PURE__*/ j(`effect/HttpClient`),nj=/*#__PURE__*/ O(2,(e,t)=>ij(R(n=>t(e.postprocess(N(n)),n)),e.preprocess)),rj=/*#__PURE__*/ O(2,(e,t)=>ij(n=>t(e.postprocess(n)),e.preprocess)),ij=(e,t)=>{let n=Object.create(aj);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},aj={[ej]:ej,pipe(){return bt(this,arguments)},...Qn,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ fA.map(([e,t])=>[t,function(t,n){return this.execute(SA(e)(t,n))}]))},oj=e=>ij(t=>R(t,t=>kp(n=>{let r=hj.get(t),i=r??new AbortController,a=gA(t.url,t.urlParams,Li(t.hash));if(Ea(a))return L(new rA({reason:new sA({request:t,cause:a.failure})}));let o=a.success;if(n.getRef($o)||n.getRef(lj)(t)){let a=e(t,o,i.signal,n);return r?a:Tm(e=>$p(e(a),{onSuccess(e){return mj.register(e,i),N(new gj(e,i))},onFailure(e){return Ed(e)&&i.abort(),Tp(e)}}))}return km(n.getRef(fj)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(e_);QA(a,o);let c=n.getRef(uj);return $A(a,`request`,t.headers,c,s),t=n.getRef(dj)?OA(t,WA(a)):t,Tm(l=>l(e(t,o,i.signal,n)).pipe(jm(a,{captureStackTrace:!1}),$p({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),$A(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),sj(n,a,t,e)),r?N(e):(mj.register(e,i),N(new gj(e,i)))),onFailure(e){return!r&&Ed(e)&&i.abort(),Tp(e)}})))})})),N),sj=(e,t,n,r)=>{let i=tr();nr(0);let a;try{a=Hd(new rA({reason:new cA({request:n,response:r})}))}finally{nr(i)}t.end(e.getRef(pf)?e.getRef($f).currentTimeNanosUnsafe():BigInt(0),a)},cj=e=>nj(e,(e,t)=>{let n=new AbortController;return hj.set(t,n),jp(mm(()=>P(()=>n.abort())),e)}),lj=/*#__PURE__*/ ya(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Tt}),uj=/*#__PURE__*/ ya(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>Tt}),dj=/*#__PURE__*/ ya(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:wt}),fj=/*#__PURE__*/ ya(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),pj=e=>Hf(tj)(nm(t=>z(e,e=>rj(e,cm(e=>ga(t,e)))))),mj=/*#__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))}}})(),hj=/*#__PURE__*/ new WeakMap;var gj=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[VA]=VA;[LA]=LA;applyInterrupt(e){return Sp(()=>(mj.unregister(this.original),Cm(e,()=>P(()=>{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 qE(()=>(mj.unregister(this.original),joe(this.original.stream,P(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Yn](){return this.original[Yn]()}pipe(){return bt(this,arguments)}};const _j=/\+/g,vj=function(){};vj.prototype=/*#__PURE__*/ Object.create(null);function yj(e){let t=new vj;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(_j,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(_j,` `)),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 bj=/^https?:\/\/.*?\//,xj=/(\/:[^/()]*?)\?(\/?)/,Sj=[],Cj=/^[^:*(]*\/:[^/:*(.-]+$/,wj=e=>Cj.test(e),Tj=(e={})=>new Ej(e);var Ej=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(xj);if(r&&r.index!==void 0){Nj(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(xj,`$1$2`),a=t.replace(xj,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=Pj(t)),this.options.ignoreTrailingSlash&&(t=Fj(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(Uj,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new Aj(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new Aj(``),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=Lj(r,d),t=r.slice(d,e+1);c.push(Rj(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=zj(_))),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(wj(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(bj,`/`)),this.options.ignoreDuplicateSlashes&&(t=Pj(t));let e;try{e=Vj(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreTrailingSlash&&(t=Fj(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(Sj),searchParams:yj(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=Hj(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:yj(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:yj(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=Hj(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=Hj(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}}}},Dj=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Ij(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},Oj=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 Dj),this.isLeafNode=!0,this.handlerStorage.add(e)}},kj=class extends Oj{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 Aj(e),this.staticChildren[n]}},Aj=class e extends kj{_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 jj(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 Mj),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}},jj=class extends kj{_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)}},Mj=class extends Oj{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Nj=(e,t)=>{if(!e)throw Error(t)};function Pj(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function Fj(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Ij(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 Lj(e,t){let n=1;for(;t<e.length;){if(t++,e[t]===`\\`){t++;continue}if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function Rj(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 zj(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Bj(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 Vj(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);Bj(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 Hj(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=Bj(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 Uj=/* @__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(`.`),Wj=Tj,Gj=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var Kj=class extends (/*#__PURE__*/ j()(`effect/http/Etag/Generator`)){};const qj=e=>{let t=Ni(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},Jj=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,Yj=/*#__PURE__*/ zf(Kj)({fromFileInfo(e){return P(()=>({_tag:`Strong`,value:qj(e)}))},fromFileWeb(e){return P(()=>({_tag:`Strong`,value:Jj(e)}))}}),Xj=/*#__PURE__*/ zf(Kj)({fromFileInfo(e){return P(()=>({_tag:`Weak`,value:qj(e)}))},fromFileWeb(e){return P(()=>({_tag:`Weak`,value:Jj(e)}))}}),Zj=/*#__PURE__*/ Object.getPrototypeOf(Wg),Qj=()=>Object.create(Zj),$j=`~effect/http/HttpServerResponse`,eM=e=>A(e,$j),tM=e=>SM({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?Gg(e.headers):void 0,cookies:e?.cookies}),nM=(e,t)=>{let n=Kg({location:e.toString()});return SM({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?Yg(n,Gg(t.headers)):n,cookies:t?.cookies??hg})},rM=(e,t)=>{let n=t?.headers?Gg(t.headers):Wg;return SM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??hg,body:Kk(e,iM(t,n))})},iM=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},aM=(e,t)=>{let n=t?.headers?Gg(t.headers):Wg;return SM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??hg,body:Xk(e,iM(t,n))})},oM=(e,t)=>{let n=$k(e,t);return(e,t)=>{let r=t?.headers?Gg(t.headers):Wg;return z(n(e,iM(t,r)),e=>SM({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},sM=(e,t)=>{let n=t?.headers?Gg(t.headers):Wg;return SM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Zk(e,iM(t,n))})},cM=(e,t)=>{let n=t?.headers?Gg(t.headers):Wg;return SM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Xk(d_(a_(e)),iM(t,n)??`application/x-www-form-urlencoded`)})},lM=(e,t)=>SM({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&Gg(t.headers),cookies:t?.cookies,body:Wk(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),uM=(e,t)=>{let n=t?.headers?Gg(t.headers):Wg;return SM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:tA(e,iM(t,n),t?.contentLength)})},dM=/*#__PURE__*/ O(3,(e,t,n)=>SM(e,qg(e.headers,t,n))),fM=/*#__PURE__*/ O(2,(e,t)=>SM({...e,headers:Xg(e.headers,t)})),pM=/*#__PURE__*/ O(2,(e,t)=>SM(e,Jg(e.headers,t))),mM=/*#__PURE__*/ O(e=>eM(e[0]),(e,t,n,r)=>z(Ap(Tg(e.cookies,t,n,r)),t=>SM({...e,cookies:t}))),hM=/*#__PURE__*/ O(2,(e,t)=>SM({...e,cookies:wg(e.cookies,t)})),gM=/*#__PURE__*/ O(2,(e,t)=>SM({...e,body:t},pA(e.headers,t))),_M=/*#__PURE__*/ O(e=>eM(e[0]),(e,t,n)=>SM({...e,status:t,statusText:n??e.statusText})),vM=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,yM=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!gg(e.cookies)){let t=kg(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=vM(e),a=i||t?.withoutBody===!0;if(r._tag===`Raw`&&r.body instanceof Response){let t=r.body;for(let[e,r]of n)e===`set-cookie`?t.headers.append(e,r):t.headers.set(e,r);if(!a)return t;let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:t.headers})}if(a)return r._tag===`Raw`&&bM(r.body)&&r.body.cancel().catch(Dt),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(iD(r.stream,t?.context??na()),{status:e.status,statusText:e.statusText,headers:n})}},bM=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,xM={...gr,[$j]:$j,[iO]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Pn(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},SM=(e,t)=>{let n=Object.create(xM);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??hg,n.body=e.body??Hk,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===Wg?Qj():Kg({...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??Wg;return n},CM=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=tM({status:e.status,statusText:e.statusText,headers:t,cookies:pg(n)});if(e.body){let t=e.headers.get(`content-type`);r=gM(r,tA(YE({evaluate:()=>e.body,onError:e=>e}),t??void 0,mA(e.headers.get(`content-length`))))}return r},wM=(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}`},TM=e=>({algorithms:e.algorithms,compressResponse(t,n,r){return z(e.compressResponse(t,n,r),e=>{if(e===t)return t;let r={"content-encoding":n,vary:wM(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),pM(e,r)})}}),EM={"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(EM);let DM;const OM=()=>{if(DM!==void 0)return DM;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(EM)){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 DM={extensionToType:e,typeToExtension:t,typeToExtensions:n},DM},kM=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(OM().extensionToType.get(n))};var AM=class extends (/*#__PURE__*/ j()(`effect/http/HttpPlatform`)){};const jM=/*#__PURE__*/ B(function*(e){let t=yield*oD,n=yield*Kj;return AM.of({platform:e.platform,compression:TM(e.compression),fileResponse:B(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?jh:yield*NM(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*NM(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*PM(c,`offset`),m=f===void 0?void 0:yield*PM(f,`end`),h=qg(MM(i),`etag`,Gj(o));return Mi(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 z(n.fromFileWeb(t),n=>{let i=Yg(MM(r),Kg({etag:Gj(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),MM=e=>{let t=e?.headers?Gg(e.headers):Wg;return e?.contentType?qg(t,`content-type`,e.contentType):t},NM=(e,t)=>{let n=Lh(e);return Mi(n)?N(n.value):L(TE({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},PM=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)?N(n):L(TE({module:`HttpPlatform`,method:`fileResponse`,description:`${t} exceeds the safe integer range: ${e}`}))},FM=`~effect/http/HttpServerRespondable`,IM=e=>A(e,FM),LM=/*#__PURE__*/ tM({status:400}),RM=/*#__PURE__*/ tM({status:404}),zM=(e,t)=>eM(e)?N(e):IM(e)?zp(e[FM](),()=>N(t)):eS(e)?N(LM):kd(e)?N(RM):N(t),BM=(e,t)=>eM(e)?N(e):IM(e)?zp(e[FM](),()=>N(t)):N(t),VM=`~effect/http/HttpServerError`;var HM=class extends (/*#__PURE__*/ Vo(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[VM]=VM;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[FM](){return this.reason[FM]()}get[iO](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},UM=class extends (/*#__PURE__*/ Vo(`RequestParseError`)){[FM](){return N(tM({status:400}))}get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return JM(this._tag,this.description,this.methodAndUrl)}},WM=class extends (/*#__PURE__*/ Vo(`RouteNotFound`)){[FM](){return N(tM({status:404}))}[iO]=!0;get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return JM(this._tag,this.description,this.methodAndUrl)}};const GM=e=>A(e,VM);var KM=class extends (/*#__PURE__*/ Vo(`ResponseError`)){[FM](){return N(tM({status:500}))}get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},qM=class extends (/*#__PURE__*/ j()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ aa(Rd,{name:`ClientAbort`,stack:Et,parent:void 0}))};const JM=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},YM=e=>{let t,n=QM,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=zM(s.error,ZM),r.push(s);break;case`Die`:eM(s.defect)?t=s.defect:(n=BM(s.defect,ZM),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(qM.key),r.length>0)break;i.push(s)}}return t?N([t,md(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?$M:eN),Ym(n,e=>(r.push(vd(e)),[e,md(r)])))},XM=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&eM(e.defect)?(t=e.defect,!1):!0);return[t??ZM,n.length>0?ki(md(n)):Oi()]},ZM=/*#__PURE__*/ tM({status:500}),QM=/*#__PURE__*/ N(ZM),$M=/*#__PURE__*/ N(/*#__PURE__*/ tM({status:499})),eN=/*#__PURE__*/ N(/*#__PURE__*/ tM({status:503})),tN=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,nN=/\\([\v\u0020-\u{10ffff}])/gu,rN=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,iN=/^[!#$%&'*+.^\w|~-]+$/u,aN={value:``,parameters:/*#__PURE__*/ Object.create(null)};function oN(e,t=!1){if(typeof e!=`string`)return aN;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?iN:rN).test(r)===!1)return aN;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(tN.lastIndex=n;o=tN.exec(e);){if(o.index!==n)return aN;n+=o[0].length,a=o[1].toLowerCase(),s=o[2],s[0]===`"`&&(s=s.slice(1,s.length-1),!t&&nN.test(s)&&(s=s.replace(nN,`$1`))),i.parameters[a]=s}return n===e.length?i:aN}const sN=16384,cN={key:0,whitespace:1,value:2},lN={_tag:`Continue`},uN=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")uN[/*#__PURE__*/ e.charCodeAt(0)]=1;const dN=/*#__PURE__*/ new Uint8Array(256);dN[9]=1;for(let e=32;e<=126;e++)dN[e]=1;for(let e=128;e<=255;e++)dN[e]=1;function Koe(){let e=new TextDecoder,t={state:cN.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=cN.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===cN.key){let n=o;for(;n<l;n++){if(t.size++>sN)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=cN.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=cN.value):(o=n+1,t.state=cN.whitespace);break}if(uN[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),lN}if(t.state===cN.whitespace){for(;o<l;o++){if(t.size++>sN)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=cN.value;break}}if(o===l)return lN}if(t.state===cN.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>sN)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),lN;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=cN.key;continue outer}}else if(dN[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)),lN}}return o>l&&(t.size+=l-o),lN}}function qoe(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 Joe(e,t,n,r){let i=qoe(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;continue}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 fN={headers:0,body:1},Yoe={_tag:`InvalidDisposition`},Xoe={_tag:`EndNotReached`},Zoe={_tag:`ReachedLimit`,limit:`MaxParts`},Qoe={_tag:`ReachedLimit`,limit:`MaxTotalSize`},$oe={_tag:`ReachedLimit`,limit:`MaxPartSize`},pN={_tag:`ReachedLimit`,limit:`MaxFieldSize`},ese=/*#__PURE__*/ new TextEncoder().encode(`\r
|
|
23
|
-
`);function mN(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function tse(e){return oN(e[`content-type`]).parameters.boundary}function hN(e){}const gN=e=>e===1/0?1/0:Number(Ih(e));function nse({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=mN,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=gN(s),d=gN(c),f=gN(l),p=tse(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:hN,end(){}};let m={state:fN.headers,index:0,parts:0,onChunk:hN,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=fN.body,m.isFile=!0,m.onChunk=hN}function g(e){m.stopped=!0,m.state===fN.body&&m.isFile&&m.onChunk(null),r(e)}let _=Koe(),v=Joe(`\r\n--${p}`,function(e,s){if(!m.stopped){if(e===0){h();return}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=fN.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(Zoe)}if((m.partSize+=s.length)>d)return g($oe);if(m.state===fN.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=oN(e.headers[`content-type`]),i=oN(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(Yoe);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=fN.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(pN);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(pN);m.fieldChunks.push(s)}}},ese,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(Qoe):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(Xoe),m.state=fN.headers,m.index=0,m.parts=0,m.onChunk=hN,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const _N=/*#__PURE__*/ new TextDecoder(`utf-8`);function rse(e){if(e===`utf-8`||e===`utf8`||e===``)return _N;try{return new TextDecoder(e)}catch{return _N}}function ise(e,t){return rse(e.contentTypeParameters.charset??`utf-8`).decode(t)}const ase=nse,ose=mN,sse=ise,vN=`~effect/http/Multipart`,yN=`~effect/http/Multipart/MultipartError`,cse=e=>dse(e)?e:bN.fromReason(`InternalError`,e);var lse=class extends Bo{};const use={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var bN=class e extends (/*#__PURE__*/ Vo(`MultipartError`)){static fromReason(t,n){return new e({reason:new lse({_tag:t,cause:n})})}[yN]=yN;[iO]=!0;[FM](){return N(tM({status:use[this.reason._tag]}))}get message(){return this.reason._tag}};const dse=e=>A(e,yN),fse=e=>kp(t=>{let n=da(t.context,TN);return N({headers:e,maxParts:t.getRef(SN),maxFieldSize:t.getRef(CN),maxPartSize:t.getRef(wN),maxTotalSize:t.getRef(zA),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&ose(e)})});var pse=class extends $n{[vN];constructor(){super(),this[vN]=vN}};const mse=(e,t)=>R(oD,n=>Hp(nD(t.content,n.sink(e)),cse)),hse=(e,t=mse)=>I(function*(){let n=yield*oD,r=yield*lD,i=yield*n.makeTempDirectoryScoped(),a=Object.create(null),o=/* @__PURE__ */ new Set,s=0;return yield*Poe(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,F;if(e.name===``)return F;let n=e,c=r.basename(n.name).slice(-128),l=r.join(i,c);for(;o.has(l);)l=r.join(i,`${s++}-${c}`);o.add(l);let u=new gse(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(Rp(`PlatformError`,e=>L(bN.fromReason(`InternalError`,e))));var gse=class extends pse{_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 xN=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(SN.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(CN.key,Ih(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(wN.key,Ih(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(zA.key,Ih(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(TN.key,e.fieldMimeTypes),Qi(t)},SN=/*#__PURE__*/ ya(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),CN=/*#__PURE__*/ ya(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ Ct(/*#__PURE__*/ zh(10))}),wN=/*#__PURE__*/ ya(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),TN=/*#__PURE__*/ ya(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ Ct([`application/json`])}),EN=`~effect/http/HttpServerRequest`,DN=/*#__PURE__*/ j(`effect/http/HttpServerRequest`);var ON=class extends (/*#__PURE__*/ j()(`effect/http/ParsedSearchParams`)){};const _se=(e,t)=>{let n=lS(e);return R(DN,e=>n(e.cookies,t))},vse=(e,t)=>{let n=lS(e);return R(DN,e=>n(e.headers,t))},yse=(e,t)=>{let n=lS(e);return R(ON,e=>n(e,t))},bse=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()}},kN=/*#__PURE__*/ new WeakMap,xse=(e,t)=>{let n=kN.get(e.source),r=n?(e,r)=>R(n(e,r),n=>t(e,n)):t;kN.set(e.source,r)},Sse=e=>e,Cse=/*#__PURE__*/ new WeakSet,wse=e=>kp(t=>{let n=ua(t.context,DN);return Cse.add(n.source),e}),Tse=/*#__PURE__*/ ya(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>Tt}),Ese=/*#__PURE__*/ ya(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Dse=/*#__PURE__*/ ya(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>Tt}),AN=(e,t)=>!e.cache.tracerEnabled||e.getRef(Tse)(t),jN=(e,t)=>{if(!(t.status>=500&&t.status<600))return Bd(t);let n=tr();nr(0);try{return Hd(new HM({reason:new KM({request:e,response:t})}))}finally{nr(n)}},MN=/*#__PURE__*/ Sse(e=>kp(t=>{let n=ua(t.context,DN);if(AN(t,n))return e;let r=t.getRef(Ese),i=Pu(t,r(n),{parent:Li(GA(n.headers)),kind:`server`}),a=t.context;return t.setContext(aa(t.context,Xo,i)),Gl(t,e=>{t.setContext(a);let r=t.getRef($f).currentTimeNanosUnsafe();if(Kd(e)&&(!i.sampled||t.getRef(rs)===is)){i.end(r,jN(n,e.value));return}let o=t.getRef(e_),s=t.getRef(Dse);t.currentDispatcher.scheduleTask(()=>{let t,a;if(qd(e)){let[r,i]=XM(e.cause);t=r,a=Mi(i)&&(t.status>=500||Ed(i.value))?Vd(i.value):jN(n,t)}else t=e.value,a=jN(n,t);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=bse(n);Mi(e)&&(!n.url.startsWith(`/`)&&(e.value.username!==``||e.value.password!==``)&&(e.value.username=`REDACTED`,e.value.password=`REDACTED`),QA(i,e.value)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),$A(i,`request`,n.headers,s,o),Mi(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,t.status),$A(i,`response`,t.headers,s,o)}i.end(r,a)},0)}),e})),Ose=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return Qm(YM(n),([e,n])=>{let i=ow();dd(i,n);let a=kN.get(r.source),o=n.reasons.length===0?N(e):Tp(n);return a===void 0?(r[NN]=!0,Qm(t(r,e),()=>o)):Qm(Qm(a(r,e),e=>(r[NN]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=kN.get(e.source);return r===void 0?(e[NN]=!0,Ym(t(e,n),e=>eM(e)?e:n)):Qm(r(e,n),r=>(e[NN]=!0,Ym(t(e,r),e=>eM(e)?e:n)))},a=a=>{let o=a.request,s=$p(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:$p(MN(n(s)),{onFailure(e){return dd(ow(),e),NN in o?F:Qp(YM(e),{onFailure(e){return t(o,tM({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return NN in o?F:t(o,e)}})},o=e=>MN(a(e)),s=(e,t,n)=>_m(n,n=>{if(t.setContext(e.prev),!(PN in e.scope))return Cf(e.scope,e.cause===void 0?n:Vd(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(Zc(n)&&n._tag===`Success`){if(t.setContext(this.prev),PN in this.scope)return n;let e=Cf(this.scope,n);return e===void 0?n:R(e,()=>n)}return s(this,t,n)}[pr](e,t){return s(this,t,r(this,e))}}return kp(t=>{au(t);let r=gf(),i=new c(r,t.context,ua(t.context,DN));t.setContext(aa(i.prev,mf,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===is||AN(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},NN=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),PN=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),kse=e=>DN.use(t=>(FN(t,e),F)),FN=xse,Ase=/*#__PURE__*/ O(2,(e,t)=>DN.use(n=>(FN(n,t),e))),IN=`~effect/http/HttpRouter`,LN=/*#__PURE__*/ j(`effect/http/HttpRouter`),jse=/*#__PURE__*/ I(function*(){let e=Wj(yield*Nse),t=/* @__PURE__ */ new Set,n=t=>nm(n=>{let r=XN(n),i=e=>{for(let t=0;t<r.length;t++)e=r[t](e);return e};for(let n=0;n<t.length;n++){let a=r.length===0?t[n]:HN({...t[n],handler:i(t[n].handler)});a.method===`*`?a.path.endsWith(`/*`)?(e.all(a.path,a),e.all(a.path.slice(0,-2),a)):e.all(a.path,a):a.path.endsWith(`/*`)?(e.on(a.method,a.path,a),e.on(a.method,a.path.slice(0,-2),a)):e.on(a.method,a.path,a)}return F});return LN.of({[IN]:IN,prefixed(e){return e=WN(e),LN.of({...this,prefixed:t=>this.prefixed(GN(t,e)),addAll:t=>n(t.map(Ise(e))),add:(t,r,i,a)=>n([HN({method:t,path:GN(r,e),handler:eM(i)?N(i):hp(i)?i:R(DN,i),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:n,add:(e,t,r,i)=>n([UN(e,t,r,i)]),addGlobalMiddleware:e=>P(()=>{t.add(e)}),asHttpEffect(){let n=kp(t=>{let n=t.context,r=ua(n,DN),i=e.find(r.method,r.url);if(i===void 0&&r.method===`HEAD`&&(i=e.find(`GET`,r.url)),i===void 0)return L(new HM({reason:new WM({request:r})}));let a=i.handler;if(Mi(a.prefix)&&(n=aa(n,DN,Mse(r,a.prefix.value))),n=aa(n,ON,i.searchParams),n=aa(n,RN,{route:a,params:i.params}),t.getRef(rs)!==is){let e=ca(n,Xo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,a.path)}if(t.setContext(n),!a.uninterruptible){let e=ou(t);if(e!==void 0)return e}return a.handler});if(t.size===0)return n;for(let e of Yee(t))n=e(n);return n}})});function Mse(e,t){let n=t.length;return e.modify({url:e.url.length<=n?`/`:e.url.slice(n)})}const Nse=/*#__PURE__*/ ya(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var RN=class extends (/*#__PURE__*/ j()(`effect/http/HttpRouter/RouteContext`)){};const zN=e=>Gf(R(LN,e)),BN=(e,t,n,r)=>zN(i=>i.add(e,t,n,r)),Pse=/*#__PURE__*/ Hf(LN)(jse),Fse=e=>nm(t=>{let n=da(t,mf),r=Ff.forkOrCreate(t);return z(If(Qf(e,Pse),r,n),e=>da(e,LN).asHttpEffect())}),VN=`~effect/http/HttpRouter/Route`,HN=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?ki(e.prefix):e.prefix??Oi(),[VN]:VN}),UN=(e,t,n,r)=>HN({...r,method:e,path:t,handler:eM(n)?N(n):hp(n)?n:R(DN,n),uninterruptible:r?.uninterruptible??!1}),WN=e=>e.endsWith(`/`)?e.slice(0,-1):e,GN=/*#__PURE__*/ O(2,(e,t)=>(t=WN(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),Ise=/*#__PURE__*/ O(2,(e,t)=>HN({...e,path:GN(e.path,t),prefix:Ni(e.prefix,{onNone:()=>WN(t),onSome:e=>GN(e,t)})})),KN=function(){return arguments.length===0?qN:qN(arguments[0],arguments[1])},qN=(e,t)=>t?.global?Gf(I(function*(){let t=yield*LN,n=hp(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new Rse(hp(e)?Wf(z(e,e=>Qi(/* @__PURE__ */ new Map([[JN,e]])))):Bf(Qi(/* @__PURE__ */ new Map([[JN,e]]))));let Lse=0;const JN=`effect/http/HttpRouter/MiddlewareFn`;var Rse=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++Lse}`;this.layer=Wf(I({self:this},function*(){let e=yield*tm(),t=[la(e,JN)];if(this.dependencies){let n=yield*Ff,r=da(e,mf),i=yield*If(this.dependencies,n,r);t.push(...XN(i))}return Qi(/* @__PURE__ */ new Map([[n,t]]))})).pipe(Zf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?Qf(this.dependencies,t.layer):t.layer)}};const YN=/*#__PURE__*/ new WeakMap,XN=e=>{let t=YN.get(e);if(t)return t;let n=Ka(),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=Va(e).reverse()}return YN.set(e,t),t};(/*#__PURE__*/ KN(wse)).layer;var ZN=class extends (/*#__PURE__*/ j()(`effect/workers/Transferable/Collector`)){};const QN=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ZN.of({addAllUnsafe:t,addAll:e=>P(()=>t(e)),readUnsafe:n,read:P(n),clearUnsafe:r,clear:P(r)})},$N=(e,t)=>e===void 0?t:`${e}.${t}`,eP=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),tP=`~effect/rpc/RpcSchema/StreamSchema`;function nP(e){return A(e,tP)}function rP(e){return nP(e)?ki({success:e.success,error:e.error}):Oi()}const zse=/*#__PURE__*/ rS(BE);function Bse(e,t){return gS(zse.ast,{[tP]:tP,success:e,error:t})}var Vse=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ aa(Rd,{name:`ClientAbort`,stack:Et,parent:void 0}))};const iP=`~effect/rpc/Rpc`;var aP=class{id;annotations;constructor(e){this.id=e,this.annotations=na()}annotate(e,t){return this.annotations=aa(this.annotations,e,t),this}};const Hse={[iP]:iP,pipe(){return bt(this,arguments)},setSuccess(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return oP({_tag:this._tag,payloadSchema:_S(e)?e:U(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return oP({_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 oP({_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 oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:aa(this.annotations,e,t)})},annotateMerge(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ga(this.annotations,e)})}},oP=e=>{function t(){}return Object.setPrototypeOf(t,Hse),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},sP=(e,t)=>{let n=t?.success??jS,r=t?.error??wS,i=t?.defect??CC(),a;return a=t?.primaryKey?class extends KC(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:_S(t?.payload)?t?.payload:t?.payload?U(t?.payload):jS,oP({_tag:e,payloadSchema:a,successSchema:t?.stream?Bse(n,r):n,errorSchema:t?.stream?wS:r,defectSchema:i,annotations:na(),middlewares:/* @__PURE__ */ new Set})},cP=/*#__PURE__*/ new WeakMap,lP=e=>{if(cP.has(e))return cP.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=rP(t.successSchema);Mi(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=BC(Mi(r)?jS:t.successSchema,G([...n]),t.defectSchema);return cP.set(e,i),i},uP=e=>`~effect/rpc/Rpc/Wrapper`in e,dP=e=>e,Use={_tag:`Eof`},fP=e=>({_tag:`Defect`,defect:e}),Wse={_tag:`Pong`},Gse=YC;let Kse;const qse=e=>(Kse??=new TextDecoder).decode(e);var pP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcSerialization`)){};const mP=e=>pP.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:Gse,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>Jse(JSON.parse(typeof t==`string`?t:qse(t)),e),encode:t=>{let n=Yse(t,e);return n&&JSON.stringify(n)}}}});function Jse(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(!Jt(a))continue;let o=hP(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return Jt(e)?[hP(e)]:[]}function hP(e){if(Object.hasOwn(e,`method`)){let t=e;if(Gt(t.id)&&It(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??[],...A(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 gP(e,t){if(!(`requestId`in e))return _P(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(),_P):void 0):_P(e)}function Yse(e,t){if(Array.isArray(e)===!1)return gP(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=gP(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 _P(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&&A(n,`code`)?Number(n.code):0,message:n&&A(n,`message`)?n.message:JSON.stringify(e.exit.cause),data:e.exit.cause}:void 0}}case`Defect`:return{jsonrpc:`2.0`,id:Xse,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const Xse=-32603,Zse=e=>zf(pP)(mP(e)),Qse=()=>e=>Sp(()=>{let t=FT(1),n=[],r=(...e)=>nm(t=>(n.push([e,t]),F));return z(e((...e)=>r(...e)),e=>({...e,run(e){return t.withPermits(1)(I(function*(){let t=r;for(let[t,r]of n)yield*im(Sp(()=>e(...t)),r);return n=[],r=e,yield*vm(wp,()=>(r=t,F))}))}}))}),$se=e=>Sp(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>nm(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),F});return z(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return I(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*im(Sp(()=>i(e)),t)}return yield*vm(wp,()=>(t.delete(e),r.delete(e),F))})}}))});let ece=0;const vP=/*#__PURE__*/ B(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>ece++),o=yield*tm(),s=da(o,mf),c=/* @__PURE__ */ new Map,l=!1;yield*yf(s,kp(e=>(l=!0,u(Wd(e.id)))));let u=B(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?cT(n.queue):oT(n.queue,e.cause):n.resume(e)}),d=e=>{let r=nP(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?Gg(s.headers):Wg,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):km($N(n,e._tag),{kind:`client`,attributes:eP(e._tag,t.spanAttributes)},r)}let u=p(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:XE(z(u,JE))}},f=(e,n,r,i,o,s,u)=>kp(d=>{if(l)return xm;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:Yg(d.getRef(yP),o)});if(u)return p;let m;return Cm(Cp(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?jm(r,{captureStackTrace:!1}):k,Im(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),jp(aw(m),h(f,Array.from(e),s))))}),p=B(function*(e,r,o,s,u,d){if(l)return yield*xm;let f=i?void 0:yield*Om($N(n,e._tag),{kind:`client`,attributes:eP(e._tag,t.spanAttributes)}),p=ow(),m=a(),g=ua(p.context,mf),_=yield*eT(u);return yield*vf(g,e=>(dT(_),c.has(m)?(c.delete(m),h(m,qd(e)?Array.from(Dd(e.cause)):[],d)):F)),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:Yg(p.getRef(yP),s)}).pipe(f?jm(f,{captureStackTrace:!1}):k,gm(e=>oT(_,e)),Sm,Nm(g,{startImmediately:!0})),_}),m=e=>{let t=[];for(let n of e.middlewares.values()){let e=la(o,`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},h=(e,n,r)=>Cp(i=>{let a=ow();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(dre(1e3),Im(a.context)).addObserver(()=>{i(F)})}),g=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?F:iT(i.queue,e.values).pipe(r?R(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):k,zp(e=>oT(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),F):e.exit._tag===`Success`?cT(n.queue):oT(n.queue,e.exit.cause)):F}case`Defect`:return u(Ud(e.defect));case`ClientEnd`:return F}},_;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=>{ar(_,e._tag,d(e))});return{client:_,write:g}});let tce=0;const nce=/*#__PURE__*/ B(function*(e,t){let n=tce++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*bP,c=rce(r),l=lae(r(CC())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):F,{client:f,write:p}=yield*vP(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?QN():void 0,o=ow(),l={rpc:r,context:i?aa(o.context,ZN,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(im(l.context),Up,R(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}):F;case`Interrupt`:return d(t.requestId);case`Eof`:return F}}});return yield*i(n,e=>{switch(e._tag){case`Chunk`:{let t=dP(e.requestId),n=u.get(t);if(!n||ji(n.schemas.decodeChunk))return F;let r=n.schemas.decodeChunk.value;return Tm(i=>i(r(e.values).pipe(im(n.context),Up,R(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(gm(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Vd(e)}).pipe(jp(Ed(e)?F:Kp(d(t))))),lre(e=>!Ed(e),()=>F)))}case`Exit`:{let t=dP(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(im(n.context),Up,$p({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Vd(e)})}))):F}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=Hd(e.error);return _p(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return F}}).pipe(zp(Wm),Sm,Pm),f}),rce=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=rP(n.successSchema);return r={decodeChunk:zi(i,t=>lS(e(RS(t.success)))),encodePayload:pS(e(n.payloadSchema)),decodeExit:lS(e(lP(n)))},t.set(n,r),r}},yP=/*#__PURE__*/ ya(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Wg});var bP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcClient/Protocol`)){static make=$se};const ice=/*#__PURE__*/ B(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*tm(),l=da(c,mf),u=sw(xf(l,`parallel`)),d=o===`unbounded`?void 0:yield*RT(o),f=/* @__PURE__ */ new Map,p=!1,m=cw(!1);yield*yf(l,kp(e=>{p=!0;for(let t of f.values()){if(t.ended=!0,t.fibers.size===0){u(Im(c)(_(t)));continue}for(let n of t.fibers.values())n.interruptUnsafe(e.id)}return f.size===0?F:m.await}));let h=e=>kp(t=>{let n=f.get(e);if(!n)return F;for(let e of n.fibers.values())e.interruptUnsafe(t.id);return f.delete(e),F}),g=(e,n,r)=>Bp(kp(i=>{if(p)return xm;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new aP(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`||!a.fibers.has(n.requestId)))return xm;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?e.open:F}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,Vse.annotation),F):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:Wd()})}case`Eof`:return a.ended=!0,a.fibers.size>0?F:_(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?jp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return xm;let p=e.requests.get(l.tag),m=la(c,p?.key);if(!p||!m){let e=Bp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Ud(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:hm(e,_(o))}let h=nP(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=uP(v),S=x&&v.fork,C=x&&v.uninterruptible,w=x?v.value:v,T=h?y(o,l,w):w,ee=p.middlewares.size>0?oce(c,T,g):T,te=!1,E=gf(),ne,re=vm(ee,e=>{te=!0;let n;e._tag===`Success`?Zd(e.value)?(ne=e.value,n=F):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}):n=!s&&Td(e.cause)&&!Ed(e.cause)?b(o,Sd(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=Cf(E,e);return e._tag===`Failure`&&dd(ow(),e.cause),r?hm(n,r):n});if(f?.onRequest&&(re=f.onRequest(re)),n){let e=ca(i.context,Xo);re=Am(re,$N(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:eP(l.tag,t.spanAttributes),parent:r&&l.spanId?Qo({traceId:l.traceId,spanId:l.spanId,sampled:l.sampled}):void 0,links:r&&e?[{span:e,attributes:{}}]:void 0})}!S&&d&&(re=d.withPermit(re));let ie=Im(aa(ace(m,i.context),mf,E));return u(ie(kp(e=>(o.fibers.set(l.id,e),re)),C?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ne){let n=u(ie(vm(nf(ne),e=>t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}))));o.fibers.set(l.id,n),ne=void 0,n.addObserver(e);return}!te&&n._tag===`Failure`&&u(ie(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Wd()}))),o.fibers.delete(l.id),o.latches?.delete(l.id),o.ended&&o.fibers.size===0&&u(ie(_(o)))}),F},y=(e,n,r)=>{let a;return i&&(e.latches??=/* @__PURE__ */ new Map,a=e.latches.get(n.id),a||(a=cw(!1),e.latches.set(n.id,a))),hp(r)?r.pipe(R(r=>vp({while:wt,body:Ct(R(fT(r),r=>{let i=t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r});return a?(a.closeUnsafe(),R(i,()=>a.await)):i})),step:Dt})),up(()=>F),dm):rD(r,r=>{let i=t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r});return a?(a.closeUnsafe(),jp(i,a.await)):i})},b=(e,n)=>Sp(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?jp(i,_(e)):i});return k({write:g,disconnect:h})}),xP=/*#__PURE__*/ new WeakMap,ace=(e,t)=>{let n=xP.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,xP.set(e,n));let r=n.get(t);return r===void 0&&(r=ga(e.context,t),n.set(t,r)),r},oce=(e,t,n)=>{for(let r of n.rpc.middlewares)t=ua(e,r)(t,n);return t},sce=/*#__PURE__*/ B(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*SP,u=hS(n(CC())),d=fS(n(BC(wS,wS,CC()))),f=yield*tm(),p=yield*hf(),m=yield*ice(e,{...t,disableClientAcks:!s,disableSpanPropagation:!c,onFromServer(e){let t=_.get(e.clientId);if(!t)return F;switch(e._tag){case`Chunk`:{let n=t.schemas.get(e.requestId);return n?y(t,e.requestId,n,n.encodeChunk(e.values),`Chunk`):F}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`)):F}case`Defect`:return x(t,e.defect);case`ClientEnd`:return _.delete(e.clientId),i(e.clientId)}}}).pipe(_f(p));yield*Mm(vp({while:wt,body:Ct(R(hT(r),e=>(_.delete(e),m.disconnect(e)))),step:Dt}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=la(f,e.key),i=rP(e.successSchema);t={decode:lS(n(e.payloadSchema)),encodeChunk:fS(n(RS(Mi(i)?i.value.success:TS))),encodeExit:fS(n(lP(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=zd(r)&&Kd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):R(im(a?lm(r,ZN,a):r,n.context),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return zp(s,r=>{e.schemas.delete(t);let i=Sd(bd(r,e=>av(e.issue)));return jp(b(e,t,n.encodeExit,i),m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))})},b=(e,t,n,r)=>zp(R(n(Ud(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,Sd(t))),x=(e,t)=>zp(o(e.id,fP(u(t))),e=>qm(Km(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:QN()}:n);let a=r;return a.id=t,a.payload=i,a.headers=Gg(r.headers),m.write(e.id,a)};return yield*a((t,n)=>{let r=_.get(t);switch(r||(r={id:t,schemas:/* @__PURE__ */ new Map},_.set(t,r)),n._tag){case`Request`:{let t=Object.hasOwn(n,`tag`)?n.tag:``,i;switch(typeof n.id){case`number`:case`string`:i=dP(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 zd(s)&&Kd(s)?S(r,i,o,n,s.value):em(im(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,av(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return zp(o(r.id,Wse),e=>x(r,Sd(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:dP(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(Gp(e=>Hm(`BUG: RpcServer protocol crashed`,e)),vm(e=>Sf(p,e)))});var SP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ Qse()};const cce=/*#__PURE__*/ B(function*(e={}){let t=yield*pP,n=hS(t.codecFor(CC())),r=t.includesFraming,i=!t.contentType.includes(`json`),a=yield*$w(),o,s=0,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=new TextEncoder,d=I(function*(){let d=ow(),f=ua(d.context,DN),p=ua(d.context,mf),m=Object.entries(f.headers),h=yield*Up(i?z(f.arrayBuffer,e=>new Uint8Array(e)):f.text),g=s++,_=yield*$w({capacity:r&&e.streamBufferSize!==`unbounded`?e.streamBufferSize??16:void 0}),v=t.makeUnsafe(),y=[],b=e=>typeof e==`string`?nT(_,u.encode(e)):nT(_,e),x={write:r?e=>{try{let t=v.encode(e);return t===void 0?F:b(t)}catch(e){return b(v.encode(fP(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?F:nT(_,e),end:cT(_)};yield*vf(p,()=>(c.delete(g),l.delete(g),rT(a,g),_.state._tag===`Done`?F:jp(uT(_),_p(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(dP(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(fP(n(e)))}if(yield*o(g,Use),!r){let e=yield*pT(_),n=v.encode(e);return aM(n===void 0?``:n,{contentType:t.contentType})}let S=yield*up(fT(_),()=>N([]));return _.state._tag===`Done`?rM(lce(S),{contentType:t.contentType}):uM(goe(S).pipe(yoe(JE(_))),{contentType:t.contentType})});return{protocol:yield*SP.make(e=>(o=e,N({disconnects:a,send(e,t){let n=c.get(e);return n?n.write(t):F},end(e){let t=c.get(e);return t?t.end:F},clientIds:P(()=>l),initialMessage:xp,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),lce=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},uce={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return CP({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 CP({requests:t,annotations:Qi(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return CP({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 CP({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return I(function*(){let n=yield*tm(),r=hp(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})}),Qi(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 CP({requests:t,annotations:this.annotations})},toLayer(e){return Wf(this.toHandlers(e))},of:k,toLayerHandler(e,t){let n=this;return Wf(I(function*(){let r=yield*tm(),i=hp(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),Qi(a)}))},accessHandler(e){return nm(t=>{let n=this.requests.get(e),{handler:r,context:i}=la(t,n.key);return N((e,t)=>{t.rpc=n;let a=r(e,t),o=uP(a)?a.value:a;return hp(o)?rm(o,i):tD(o,i)})})},annotate(e,t){return CP({requests:this.requests,annotations:aa(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(ia(e,t))},annotateMerge(e){return CP({requests:this.requests,annotations:ga(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(ga(e,r.annotations)));return CP({requests:t,annotations:this.annotations})}},CP=e=>Object.assign(function(){},uce,{requests:e.requests,annotations:e.annotations}),wP=(...e)=>CP({requests:new Map(e.map(e=>[e._tag,e])),annotations:na()}),dce=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},fce=/* @__PURE__ */ zf(eO,/* @__PURE__ */ tO({randomBytes:Je.randomBytes,digest:(e,t)=>Op({try:()=>Uint8Array.from(Je.createHash(dce(e)).update(t).digest()),catch:e=>wE({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),TP=e=>t=>TE({module:`FileSystem`,method:e,description:t.message??String(t)}),EP=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},DP=e=>Bi(Fi(e),bh),OP=(e,t)=>Op({try:()=>EP(e,`position`),catch:TP(t)}),pce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.access,/*#__PURE__*/ vk(`FileSystem`,`access`),/*#__PURE__*/ TP(`access`));return(t,n)=>{let r=ut.constants.F_OK;return n?.readable&&(r|=ut.constants.R_OK),n?.writable&&(r|=ut.constants.W_OK),e(t,r)}})(),mce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.cp,/*#__PURE__*/ vk(`FileSystem`,`copy`),/*#__PURE__*/ TP(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),hce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.copyFile,/*#__PURE__*/ vk(`FileSystem`,`copyFile`),/*#__PURE__*/ TP(`copyFile`));return(t,n)=>e(t,n)})(),gce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.chmod,/*#__PURE__*/ vk(`FileSystem`,`chmod`),/*#__PURE__*/ TP(`chmod`));return(t,n)=>e(t,n)})(),_ce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.chown,/*#__PURE__*/ vk(`FileSystem`,`chown`),/*#__PURE__*/ TP(`chown`));return(t,n,r)=>e(t,n,r)})(),vce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.glob,/*#__PURE__*/ vk(`FileSystem`,`glob`),/*#__PURE__*/ TP(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),yce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.link,/*#__PURE__*/ vk(`FileSystem`,`link`),/*#__PURE__*/ TP(`link`));return(t,n)=>e(t,n)})(),bce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.mkdir,/*#__PURE__*/ vk(`FileSystem`,`makeDirectory`),/*#__PURE__*/ TP(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),kP=e=>{let t=Jm(ut.mkdtemp,vk(`FileSystem`,e),TP(e));return e=>Sp(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?Xe.join(e.directory,`.`):pt.tmpdir();return t(n?Xe.join(r,n):r+`/`)})},xce=/*#__PURE__*/ kP(`makeTempDirectory`),AP=e=>{let t=Jm(ut.rm,vk(`FileSystem`,e),TP(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},Sce=/*#__PURE__*/ AP(`remove`),Cce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ kP(`makeTempDirectoryScoped`),t=/*#__PURE__*/ AP(`makeTempDirectoryScoped`);return n=>pm(e(n),e=>Up(t(e,{recursive:!0})))})(),wce=/*#__PURE__*/ (e=>{let t=Jm(ut.open,vk(`FileSystem`,e),TP(e)),n=Jm(ut.close,vk(`FileSystem`,e),TP(e));return(e,r)=>Ot(pm(t(e,r?.flag??`r`,r?.mode),e=>Up(n(e))),z(e=>Tce(e,r?.flag?.startsWith(`a`)??!1)))})(`open`),Tce=/*#__PURE__*/ (()=>{let e=e=>Jm(ut.read,vk(`FileSystem`,e),TP(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ Jm(ut.fstat,/*#__PURE__*/ vk(`FileSystem`,`stat`),/*#__PURE__*/ TP(`stat`)),i=/*#__PURE__*/ Jm(ut.ftruncate,/*#__PURE__*/ vk(`FileSystem`,`truncate`),/*#__PURE__*/ TP(`truncate`)),a=/*#__PURE__*/ Jm(ut.fsync,/*#__PURE__*/ vk(`FileSystem`,`sync`),/*#__PURE__*/ TP(`sync`)),o=e=>Jm(ut.write,vk(`FileSystem`,e),TP(e)),s=/*#__PURE__*/ o(`write`),c=/*#__PURE__*/ o(`writeAll`);class l{[sD];fd;append;position=/*#__PURE__*/ BigInt(0);constructor(e,t){this[sD]=sD,this.fd=e,this.append=t}get stat(){return R(r(this.fd,{bigint:!0}),MP)}get sync(){return a(this.fd)}seek(e,t){return Sp(()=>{let n=t===`start`?e:this.position+e;return n<BigInt(0)?L(TE({module:`FileSystem`,method:`seek`,description:`Cannot seek before the start of the file`})):(this.position=n,N(n))})}read(e){return Sp(()=>{let n=this.position;return z(t(this.fd,{buffer:e,position:n}),e=>(this.position=n+BigInt(e),e))})}readAlloc(e){return Sp(()=>{try{if(!Number.isInteger(e)||e<0)throw RangeError(`size must be a non-negative integer`);let t=Buffer.allocUnsafeSlow(e),r=this.position;return z(n(this.fd,{buffer:t,position:r}),n=>{if(n===0)return Oi();if(this.position=r+BigInt(n),n===e)return ki(t);let i=Buffer.allocUnsafeSlow(n);return t.copy(i,0,0,n),ki(i)})}catch(e){return L(TP(`readAlloc`)(e))}})}truncate(e){return z(i(this.fd,e||void 0),()=>{if(!this.append){let t=BigInt(e??0);this.position>t&&(this.position=t)}})}write(e){return Sp(()=>{let t=this.position;return R(this.append?N(void 0):OP(t,`write`),n=>z(s(this.fd,e,void 0,void 0,n),e=>(this.append||(this.position=t+BigInt(e)),e)))})}writeAllChunk(e){return Sp(()=>{let t=this.position;return R(this.append?N(void 0):OP(t,`writeAll`),n=>R(c(this.fd,e,void 0,void 0,n),n=>n===0?L(wE({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)):F)))})}writeAll(e){return e.length===0?F:this.writeAllChunk(e)}}return(e,t)=>new l(e,t)})(),jP=e=>{let t=kP(e);return B(function*(e){let n=yield*t(e),r=Je.randomBytes(6).toString(`hex`),i=Xe.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*PP(i,/* @__PURE__ */ new Uint8Array),i})},Ece=/*#__PURE__*/ jP(`makeTempFile`),Dce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ jP(`makeTempFileScoped`),t=/*#__PURE__*/ AP(`makeTempFileScoped`);return n=>pm(e(n),e=>Up(t(Xe.dirname(e),{recursive:!0})))})(),Oce=(e,t)=>bp({try:()=>ut.promises.readdir(e,t),catch:t=>vk(`FileSystem`,`readDirectory`)(t,[e])}),kce=e=>Cp((t,n)=>{try{ut.readFile(e,{signal:n},(n,r)=>{t(n?L(vk(`FileSystem`,`readFile`)(n,[e])):N(r))})}catch(e){t(L(TP(`readFile`)(e)))}}),Ace=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.readlink,/*#__PURE__*/ vk(`FileSystem`,`readLink`),/*#__PURE__*/ TP(`readLink`));return t=>e(t)})(),jce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.realpath,/*#__PURE__*/ vk(`FileSystem`,`realPath`),/*#__PURE__*/ TP(`realPath`));return t=>e(t)})(),Mce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.rename,/*#__PURE__*/ vk(`FileSystem`,`rename`),/*#__PURE__*/ TP(`rename`));return(t,n)=>e(t,n)})(),MP=e=>Op({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:EP(e.dev,`dev`),rdev:DP(e.rdev),ino:DP(e.ino),mode:EP(e.mode,`mode`),nlink:DP(e.nlink),uid:DP(e.uid),gid:DP(e.gid),size:Rh(e.size),blksize:e.blksize===void 0?Oi():ki(Rh(e.blksize)),blocks:DP(e.blocks)}),catch:TP(`stat`)}),NP=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.stat,/*#__PURE__*/ vk(`FileSystem`,`stat`),/*#__PURE__*/ TP(`stat`));return t=>R(e(t,{bigint:!0}),MP)})(),Nce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.symlink,/*#__PURE__*/ vk(`FileSystem`,`symlink`),/*#__PURE__*/ TP(`symlink`));return(t,n)=>e(t,n)})(),Pce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.truncate,/*#__PURE__*/ vk(`FileSystem`,`truncate`),/*#__PURE__*/ TP(`truncate`));return(t,n)=>e(t,n)})(),Fce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Jm(ut.utimes,/*#__PURE__*/ vk(`FileSystem`,`utime`),/*#__PURE__*/ TP(`utime`));return(t,n,r)=>e(t,n,r)})(),Ice=(e,t,n)=>foe(r=>pm(P(()=>{let i=t.type===`Directory`?e:Xe.dirname(e),a=ut.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:Fm(em(NP(Xe.resolve(i,t)),{onSuccess:e=>nT(r,{_tag:`Create`,path:t}),onFailure:e=>nT(r,{_tag:`Remove`,path:t})}));return;case`change`:rT(r,{_tag:`Update`,path:t});return}});return a.on(`error`,t=>{sT(r,hd(wE({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{lT(r)}),a}),e=>P(()=>e.close()))),Lce=(e,t,n)=>NP(t).pipe(z(r=>e.pipe(Bi(e=>e.register(t,r,n)),Pi(()=>Ice(t,r,n)))),XE),PP=(e,t,n)=>Cp((r,i)=>{try{ut.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?L(vk(`FileSystem`,`writeFile`)(t,[e])):F)})}catch(e){r(L(TP(`writeFile`)(e)))}}),Rce=/*#__PURE__*/ z(/*#__PURE__*/ sm(Roe),e=>Loe({access:pce,chmod:gce,chown:_ce,copy:mce,copyFile:hce,glob:vce,link:yce,makeDirectory:bce,makeTempDirectory:xce,makeTempDirectoryScoped:Cce,makeTempFile:Ece,makeTempFileScoped:Dce,open:wce,readDirectory:Oce,readFile:kce,readLink:Ace,realPath:jce,remove:Sce,rename:Mce,stat:NP,symlink:Nce,truncate:Pce,utimes:Fce,watch(t,n){return Lce(e,t,n)},writeFile:PP})),FP=/* @__PURE__ */ Hf(oD)(Rce);var zce=class extends $n{[LA];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[LA]=LA,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return Gg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??Fi(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=z(this.arrayBuffer,e=>Buffer.from(e).toString(`utf8`)),this.textEffect}get textUnsafe(){return zm(this.text)}get json(){return R(this.text,e=>Op({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return zm(this.json)}get urlParamsBody(){return R(this.text,e=>Op({try:()=>a_(new URLSearchParams(e)),catch:this.onError}))}get stream(){return Sk({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect?this.arrayBufferEffect:(this.arrayBufferEffect=kp(e=>Ek(()=>this.source,{onError:this.onError,maxBytes:e.getRef(zA)})).pipe(ym,zm),this.textEffect=z(this.arrayBufferEffect,e=>new TextDecoder().decode(e)),this.arrayBufferEffect)}};const IP=/*#__PURE__*/ ya(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var LP=class extends (/*#__PURE__*/ j()(`effect/http/FetchHttpClient/RequestInit`)){};const RP=/*#__PURE__*/ pj(/*#__PURE__*/ N(/* @__PURE__ */ oj((e,t,n,r)=>{let i=r.getRef(IP),a=ca(r.context,LP)??{},o=a.headers?Yg(Gg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=Xg(o,`content-length`));let s=r=>z(bp({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 rA({reason:new oA({request:e,cause:t})})}),t=>HA(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 R(Ioe(e.body.stream),s)}return s(void 0)}))),Bce=/*#__PURE__*/ new Set(typeof ht.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),zP=(e,t)=>{let n={};return e!==void 0&&(n[ht.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[ht.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},BP=e=>e===void 0||e===3?void 0:{params:{[ht.constants.ZSTD_c_compressionLevel]:e}},Vce=(e,t,n)=>Cp(r=>{let i=(e,t)=>r(e===null?N(t):Dp(e));switch(t){case`gzip`:ht.gzip(e,{level:n?.level},i);break;case`deflate`:ht.deflate(e,{level:n?.level},i);break;case`br`:ht.brotliCompress(e,zP(n?.level,e.byteLength),i);break;case`zstd`:{let t=BP(n?.level);t===void 0?ht.zstdCompress(e,i):ht.zstdCompress(e,t,i);break}}}),Hce=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?z(Vce(i.body,n,r),e=>dM(gM(t,Kk(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),VP=(e,t)=>{switch(e){case`gzip`:return ht.createGzip({level:t?.level,flush:ht.constants.Z_SYNC_FLUSH});case`deflate`:return ht.createDeflate({level:t?.level,flush:ht.constants.Z_SYNC_FLUSH});case`br`:return ht.createBrotliCompress({...zP(t?.level),flush:ht.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return ht.createZstdCompress({...BP(t?.level),flush:ht.constants.ZSTD_e_flush})}},HP=(e,t)=>{let n;return new at({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)}})},UP=(e,t)=>fM(gM(e,t),`content-length`),Uce=/*#__PURE__*/ jM({platform:`node`,compression:/* @__PURE__ */ Hce({algorithms:Bce,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return N(UP(e,tA(Tk(r.stream,{evaluate:()=>VP(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof at?r.body:void 0,a=HP(()=>{let e=VP(t,n);return i??=at.fromWeb(new Response(r.body).body),ot(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return N(UP(e,Wk(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return N(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=HP(()=>o===BigInt(0)?at.from([]):ut.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return lM(s,{headers:{...r,"content-type":r[`content-type`]??Pi(kM(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return lM(HP(()=>at.fromWeb(e.stream())),{headers:Yg(r,Kg({"content-type":r[`content-type`]??(e.type===``?Pi(kM(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),Wce=/*#__PURE__*/ Ot(/*#__PURE__*/ Hf(AM)(Uce),/*#__PURE__*/ Zf(FP),/*#__PURE__*/ Zf(Yj));var Gce=class extends rt{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=ase({...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 qce(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 Kce=e=>new Gce(e);var qce=class extends at{_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 WP=(e,t)=>fse(t).pipe(z(t=>Sk({evaluate(){let n=Kce(t);return e.pipe(n),n},onError:e=>Qce(e)})),XE,ZE(Yce)),Jce=(e,t)=>hse(WP(e,t),(e,t)=>bp({try:n=>dee.pipeline(t.file,ut.createWriteStream(e),{signal:n}),catch:e=>bN.fromReason(`InternalError`,e)})),Yce=e=>e._tag===`Field`?new Xce(e.info,e.value):new Zce(e);var GP=class extends $n{[vN];constructor(){super(),this[vN]=vN}},Xce=class extends GP{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=sse(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Zce=class extends GP{_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=Sk({evaluate:()=>e,onError:e=>bN.fromReason(`InternalError`,e)}),this.contentEffect=Dk(()=>e,{onError:e=>bN.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Qce(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return bN.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return bN.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return bN.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return bN.fromReason(`BodyTooLarge`,e)}default:return bN.fromReason(`Parse`,e)}}const KP=e=>({fromFileUrl:t=>Op({try:()=>et.fileURLToPath(t,{windows:e}),catch:e=>new SE({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>Op({try:()=>et.pathToFileURL(t,{windows:e}),catch:e=>new SE({module:`Path`,method:`toFileUrl`,cause:e})})});({...Xe.posix,.../*#__PURE__*/ KP(!1)}),{...Xe.win32,.../*#__PURE__*/ KP(!0)};const $ce=/* @__PURE__ */ zf(lD)({[cD]:cD,...Xe,.../*#__PURE__*/ KP(void 0)}),ele=/* @__PURE__ */ zf(UO,/*#__PURE__*/ WO({args:/*#__PURE__*/ P(()=>process.argv.slice(2)),stdinIsTerminal:/*#__PURE__*/ P(()=>process.stdin.isTTY===!0),stdoutIsTerminal:/*#__PURE__*/ P(()=>process.stdout.isTTY===!0),stdout:e=>yk({evaluate:()=>process.stdout,onError:e=>wE({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>yk({evaluate:()=>process.stderr,onError:e=>wE({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ Sk({evaluate:()=>process.stdin,onError:e=>wE({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),tle=/*#__PURE__*/ Hf(JO,/*#__PURE__*/ (/* @__PURE__ */ B(function*(e=qP){let t=process.stdin,n=process.stdout,r=yield*$w(),i=t.readableEnded,a=!1,o=()=>{i=!0,a||lT(r)};t.once(`end`,o),yield*mm(()=>P(()=>t.off(`end`,o)));let s=yield*uoe({acquire:pm(P(()=>{let e=gt.createInterface({input:t,escapeCodeTimeout:50}),n=e=>rT(r,e),i=()=>{a=!1,lT(r)};return a=!0,gt.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})=>P(()=>{a=!1,e.off(`line`,o),e.off(`close`,n),t.isTTY&&t.setRawMode(!1),e.close(),i&&lT(r)})),idleTimeToLive:`10 millis`}),c=P(()=>n.columns??0),l=P(()=>n.rows??0),u=I(function*(){let n=yield*$w(),r=(t,r)=>{let i={input:Ii(t),key:{name:r.name??``,ctrl:!!r.ctrl,meta:!!r.meta,shift:!!r.shift}};rT(n,i),e(i)&&lT(n)},a=setInterval(()=>{},2147483647),o=()=>{clearInterval(a),lT(n)};return yield*mm(()=>P(()=>{clearInterval(a),t.off(`keypress`,r),t.off(`end`,o)})),t.on(`keypress`,r),i?o():(yield*zE(s),t.once(`end`,o)),n}),d=Sp(()=>gT(r).pipe(R(Ni({onNone:()=>dm(jp(zE(s),hT(r))),onSome:N})),Hp(()=>new qO({}))));return YO({columns:c,rows:l,readInput:u,readLine:d,display:e=>wm(Cp(t=>{n.write(e,e=>Gt(e)?t(F):t(L(TE({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(qP));function qP(e){return e.key.ctrl&&(e.key.name===`c`||e.key.name===`d`)}const nle=/*#__PURE__*/ Qf(Ik,/*#__PURE__*/ Yf(FP,fce,$ce,ele,tle)),rle=(e,t)=>{let n=Ose(e,sle,t.middleware);return kp(e=>{let r=e.context;return N(function(i,a){let o=aa(r,DN,new ile(i,a)),s=sw(Im(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,qM.annotation)})})})};var ile=class e extends zce{[EN];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new HM({reason:new UM({request:this,cause:e})}),a),this[EN]=EN,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Ag(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||=zm(ym(Jce(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return WP(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??L(new HM({reason:new UM({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${this.url})`}toJSON(){return BA(this,{_id:`HttpServerRequest`,method:this.method,url:this.originalUrl})}};const ale=/*#__PURE__*/ Yf(Wce,Xj,nle),ole=/*#__PURE__*/ tM({status:101}),sle=(e,t)=>{if(e.upgraded)return N(ole);let n=e.resolvedResponse;if(n.writableEnded)return F;let r=t.headers;if(!gg(t.cookies)){r={...r};let e=kg(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),jp(cle(t.body),Cp(e=>{let t=!1,r=()=>{t||(t=!0,n.off(`close`,r),e(F))};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(),F;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`?bp({try:e=>fee(i.body,n,{signal:e,end:!0}),catch:n=>new HM({reason:new KM({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(Sm,Gp(JP(n,t))):Cp(e=>{n.end(i.body,()=>e(F))});case`Uint8Array`:return n.writeHead(t.status,t.statusText,r),i.contentLength<1048576?(n.end(i.text??i.body),F):Cp(e=>{n.end(i.text??i.body,()=>e(F))});case`FormData`:return Sp(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),Cp((r,i)=>{at.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(L(new HM({reason:new KM({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(F)})}).pipe(Sm,Gp(JP(n,t)))});case`Stream`:{n.writeHead(t.status,t.statusText,r);let e=cw();return n.on(`drain`,()=>e.openUnsafe()),i.stream.pipe(woe,rD(t=>{let r=t.length>1?Buffer.concat(t):t[0];return n.write(r)?F:(e.closeUnsafe(),e.await)}),Sm,$p({onSuccess:()=>P(()=>n.end()),onFailure:JP(n,t)}))}}},cle=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof at?P(()=>t.destroy()):F},JP=(e,t)=>n=>R(YM(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),Tp(a?xd(n,gd(t)):i)}),lle={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},ule=e=>lle[e];function YP(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const q=YP({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`});function XP(){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`)}const ZP={name:`HMAC`,hash:`SHA-256`},QP=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await XP().importKey(`raw`,t,ZP,!1,[`sign`,`verify`])},dle=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 XP().verify(ZP,n,i,new TextEncoder().encode(t))}catch{return!1}},fle=async(e,t)=>{let n=await QP(t),r=await XP().sign(ZP.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},ple=async(e,t)=>{let n=await fle(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},mle=/^application\/([a-z0-9.+-]*\+)?json/i;async function hle(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 d(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new d(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(mle.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new d(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 $P(e){return e instanceof d||e?.name===`APIError`}function gle(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function _le(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function eF(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const tF=(e,t)=>{let n=e;if(t){if(t===`secure`)n=`__Secure-`+e;else if(t===`host`)n=`__Host-`+e;else return}return n};function vle(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,gle(n))}n=i+1}return t}const nF=(e,t,n={})=>{let r;if(r=n?.prefix===`secure`?`${`__Secure-${e}`}=${t}`:n?.prefix===`host`?`${`__Host-${e}`}=${t}`:`${e}=${t}`,e.startsWith(`__Secure-`)&&!n.secure&&(n.secure=!0),e.startsWith(`__Host-`)&&(n.secure||=!0,n.path!==`/`&&(n.path=`/`),n.domain&&=void 0),n&&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&&n.prefix!==`host`&&(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&&(n.secure||=!0,r+=`; Partitioned`),r},rF=(e,t,n)=>(t=encodeURIComponent(t),nF(e,t,n)),iF=async(e,t,n,r)=>(t=await ple(t,n),nF(e,t,r));async function yle(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:aF(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:aF(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 aF(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 oF=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:s}=await yle(t,e);if(s)throw new o(s.message,s.issues);let c=`headers`in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):`request`in e&&eF(e.request)?e.request.headers:null,l=c?.get(`cookie`),u=l?vle(l):void 0,f={...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=>c?c.get(e):null,getCookie:(e,t)=>{let n=tF(e,t);return n&&u?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=tF(e,n);if(!r)return null;let i=u?.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 dle(s,o,await QP(t))?o:!1},setCookie:(e,t,n)=>{let i=rF(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await iF(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new d(`FOUND`,void 0,r)),error:(e,t,n)=>new d(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({...f,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(f.context,t.response),t.headers&&t.headers.forEach((e,t)=>{f.responseHeaders.set(t,e)})}return f};function ble(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 xle(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 Sle(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const Cle=/* @__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 sF(e){for(let t of Cle)e.delete(t)}function cF(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 lF(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);sF(n),cF(e.headers,n)}return e}if(Sle(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(cF(i,r?.headers),cF(i,e.headers),t?.headers){let e=new Headers(t.headers);sF(e),cF(i,e)}return i.set(`Content-Type`,`application/json`),new Response(JSON.stringify(n),{...r,headers:i,status:e.status??t?.status??r?.status,statusText:t?.statusText??r?.statusText})}if($P(e))return lF(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 sF(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`)):ble(e)&&(n=xle(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 uF(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,s=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new a(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new a(`Path cannot contain consecutive slashes`);let c=async(...e)=>{let t=e[0]||{},{data:n,error:a}=await _le(oF(t,{options:i,path:r}));if(a)throw a instanceof o?(i.onValidationError&&await i.onValidationError({message:a.message,issues:a.issues}),new d(400,{message:a.message,code:`VALIDATION_ERROR`})):a;let c=await s(n).catch(async e=>{if($P(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),l=n.responseHeaders,u=n.responseStatus;return t.asResponse?lF(c,{headers:l,status:u}):t.returnHeaders?t.returnStatus?{headers:l,response:c,status:u}:{headers:l,response:c}:t.returnStatus?{response:c,status:u}:c};return c.options=i,c.path=r,c}function dF(e,t){return[...e??[],...t??[]]}uF.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return uF(n,{...r,use:dF(r.use,e?.use)},i)}let[n,r]=t;return uF({...n,use:dF(n.use,e?.use)},r)}return t};function fF(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await oF(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 $P(e)&&Object.defineProperty(e,s,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}fF.create=e=>{function t(t,n){if(typeof t==`function`)return fF({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return fF({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};function pF(e){return u(h,e)}function mF(e){return r(te,e)}function hF(e){return i(ae,e)}const gF={};function _F(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 vF(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof re&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof re&&t.push({name:e,in:`query`,schema:{type:_F(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function wle(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof re||e.body instanceof S)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof re&&(n[e]={type:_F(t),description:t.description},t instanceof S||r.push(e))}),{required:e.body instanceof S?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function yF(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 Tle(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(gF[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:vF(n),responses:yF(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=wle(n);gF[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:vF(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:yF(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:gF}}const Ele=(e,t)=>`<!doctype html>
|
|
20
|
+
`,e)));t+=a.substring(e)}}return Ga(r)?r:null}let a=Sp(()=>r._tag===`Some`?Md(r.value):ere(e,{onSuccess:o,onFailure:Tp,onDone:e=>{if(r=Oi(e),t.length>0){let e=t;return t=``,n=!1,N([e])}return Md(e)}}));function o(e){let t=i(e);return t===null?a:N(t)}return a})),zae=/*#__PURE__*/ O(2,(e,t)=>VT((n,r)=>R(GT(e)(n,r),e=>GT(t)(e,r)))),Bae=/*#__PURE__*/ O(2,(e,t)=>VT((n,r)=>R(GT(e)(n,r),e=>{let n=zp(e,e=>dp(e)?Tp(e):Dp(jd(e)));return z(GT(t)(n,r),e=>Bp(e,e=>Ad(e)?Tp(e.value):Dp(e)))}))),hE=e=>VT((t,n)=>{let r;return N(Sp(()=>r||e.pipe(_f(n),R(e=>GT(e)(t,n)),R(e=>r=e))))}),Vae=/*#__PURE__*/ O(2,(e,t)=>WT((n,r,i)=>vf(i,t).pipe(jp(GT(e)(n,r))))),Hae=/*#__PURE__*/ O(2,(e,t)=>HT(e,e=>N(up(e,e=>R(t,()=>Md(e)))))),Uae=/*#__PURE__*/ O(2,(e,t)=>Vae(e,e=>t)),gE=(e,t,n)=>Sp(()=>{let r=gf(),i=GT(e)(Md(),r);return up(R(i,t),n||N).pipe(_m(e=>Sf(r,e)))}),Wae=/*#__PURE__*/ O(2,(e,t)=>VT((n,r)=>z(rm(GT(e)(n,r),t),rm(t)))),_E=/*#__PURE__*/ O(2,(e,t)=>gE(e,e=>Tm(R(e,t),{disableYield:!0}))),Gae=e=>Sp(()=>{let t=Symbol(),n=t;return gE(e,e=>Tm(R(e,e=>(n=e,F)),{disableYield:!0}),()=>n===t?xp:rre(n))}),vE=/*#__PURE__*/ O(3,(e,t,n)=>Sp(()=>{let r=t();return gE(e,e=>vp({while:wt,body:()=>e,step:e=>{r=n(r,e)}}),()=>N(r))})),yE=(e,t)=>GT(e)(Md(),t),bE=`~effect/PlatformError`;var xE=class extends (/*#__PURE__*/ Bo(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},Kae=class extends zo{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},SE=class extends (/*#__PURE__*/ Bo(`PlatformError`)){constructor(e){`cause`in e?super({reason:e,cause:e.cause}):super({reason:e})}[bE]=bE;get message(){return this.reason.message}};const CE=e=>new SE(new Kae(e)),wE=e=>new SE(new xE(e)),qae={_R:k,_E:k,_A:k},TE=function(e){this.channel=e};TE.prototype={"~effect/Stream":qae,pipe(){return bt(this,arguments)}};const Jae=e=>new TE(e),EE=`~effect/Sink`,DE=/*#__PURE__*/ N([void 0]),Yae={_A:k,_In:k,_L:k,_E:k,_R:k},Xae={[EE]:Yae,pipe(){return bt(this,arguments)}},OE=e=>A(e,EE),kE=e=>AE((t,n)=>GT(e)(t,n).pipe(R(Tm({disableYield:!0})),up(N))),AE=e=>{let t=Object.create(Xae);return t.transform=e,t},Zae=e=>VT((t,n)=>N(R(e.transform(t,n),Md))),jE=/*#__PURE__*/ AE(e=>up(Tm(e,{disableYield:!0}),()=>DE)),Qae=e=>$ae(_p(t=>e(t),{discard:!0})),$ae=e=>AE(t=>t.pipe(R(e),Tm({disableYield:!0}),up(()=>DE))),eoe=e=>kE(hE(z(e,Zae))),ME=`~effect/RcMap`,toe=e=>({[ME]:ME,lookup:e.lookup,context:e.context,scope:e.scope,idleTimeToLive:e.idleTimeToLive,capacity:e.capacity,state:{_tag:`Open`,map:Sae()},pipe(){return bt(this,arguments)}}),noe=e=>kp(t=>{let n=t.context,r=la(n,mf),i=toe({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?kt(e.idleTimeToLive,ao):Ct(ao(e.idleTimeToLive??po)),capacity:Math.max(e.capacity??1/0,0)});return Fp(vf(r,()=>{if(i.state._tag===`Closed`)return F;let e=i.state.map;return i.state={_tag:`Closed`},_p(e,([,e])=>Pp(PE(e))).pipe(Mp(()=>P(()=>{Eae(e)})))}),i)}),NE=/*#__PURE__*/ O(2,(e,t)=>wm(n=>{if(e.state._tag===`Closed`)return bm;let r=e.state,i=aw(),a=ew(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&Dae(e.state.map)>=e.capacity)return L(new Pd(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:ef(),scope:gf(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=ioe(e,t,o),wae(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(mf.key,o.scope);let a=Xi(n);Sp(()=>e.lookup(t)).pipe(Fm(a),ow(o.scope)).addObserver(n=>{Jd(n)&&roe(e,t,o,a),uf(o.deferred,n)})}let s=ca(i.context,mf);return yf(s,o.finalizer).pipe(jp(n(nf(o.deferred))))})),roe=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=ew(e.state.map,t);i._tag!==`None`&&i.value===n&&(nw(e.state.map,t),!(n.refCount>0)&&PE(n).pipe(Fm(r),ow(e.scope)))},PE=e=>e.fiber?iw(e.fiber).pipe(jp(Sf(e.scope,Gd))):Sf(e.scope,Gd),ioe=(e,t,n)=>kp(r=>{if(n.refCount--,n.refCount>0)return F;if(e.state._tag===`Closed`)return PE(n);let i=ew(e.state.map,t);if(i._tag===`None`||i.value!==n)return PE(n);if(fo(n.idleTimeToLive))return nw(e.state.map,t),PE(n);if(!uo(n.idleTimeToLive))return F;let a=r.getRef($f);return n.expiresAt=a.currentTimeMillisUnsafe()+bo(n.idleTimeToLive),n.fiber||=wm(function r(i){let o=a.currentTimeMillisUnsafe(),s=n.expiresAt-o;if(s<=0){if(e.state._tag===`Closed`||n.refCount>0)return F;let r=ew(e.state.map,t);return r._tag===`None`||r.value!==n?F:(nw(e.state.map,t),Sf(n.scope,Gd))}return R(i(a.sleep(_o(s))),()=>r(i))}).pipe(mm(P(()=>{n.fiber=void 0})),Fm(r.context),ow(e.scope)),F}),FE={_tag:`Empty`},aoe={_tag:`Closed`},ooe={_A:k,_E:k};var soe=class{"~effect/RcRef"=ooe;pipe(){return bt(this,arguments)}state=FE;acquire;context;scope;idleTimeToLive;constructor(e,t,n,r){this.acquire=e,this.context=t,this.scope=n,this.idleTimeToLive=r}};const coe=e=>kp(t=>{let n=t.context,r=la(n,mf),i=new soe(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:ao(e.idleTimeToLive));return Fp(vf(r,()=>{let e=i.state;return i.state=aoe,e._tag===`Acquired`?Sf(e.scope,Gd):e._tag===`Acquiring`?iw(e.fiber):F}),i)}),loe=(e,t)=>{switch(e.state._tag){case`Closed`:return bm;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?Fp(iw(t.fiber),t):N(t)}case`Acquiring`:{let n=e.state;return n.awaiters++,IE(e,n,t)}case`Empty`:{let n={_tag:`Acquiring`,fiber:void 0,awaiters:1,acquired:void 0};e.state=n;let r=gf(),i=rm(e.acquire,ra(e.context,mf,r)).pipe(R(t=>{if(e.state!==n)return bm;let i={_tag:`Acquired`,value:t,scope:r,fiber:void 0,refCount:n.awaiters,invalidated:!1};return e.state=i,n.acquired=i,N(i)}),_m(t=>Kd(t)?F:(e.state===n&&(e.state=FE),Sf(r,t))));return n.fiber=Fm(aw().context)(i),IE(e,n,t)}}},IE=(e,t,n)=>_m(n(rw(t.fiber)),n=>{let r=t.acquired;return r===void 0?--t.awaiters>0||e.state!==t?F:(e.state=FE,iw(t.fiber)):qd(n)?LE(e,r):F}),uoe=e=>{let t=e;return wm(e=>R(lm,n=>R(loe(t,e),e=>Fp(vf(n,()=>LE(t,e)),e.value))))},LE=(e,t)=>{if(t.refCount--,t.refCount>0)return F;let n=e.idleTimeToLive;return n===void 0||t.invalidated?(e.state===t&&(e.state=FE),Sf(t.scope,Gd)):(uo(n)&&(t.fiber=wm(r=>R(r(Yp(n)),()=>e.state===t&&t.refCount===0?(e.state=FE,Sf(t.scope,Gd)):F)).pipe(mm(P(()=>{t.fiber=void 0})),Fm(e.context),ow(e.scope))),F)},doe=coe,RE=uoe,zE=e=>A(e,`~effect/Stream`),BE=Jae,VE=e=>BE(tE(z(e,qa))),foe=e=>HE(P(()=>{let t=!0,n=N(qa(void 0)),r=fre(n,e);return Sp(()=>t?(t=!1,n):r)})),HE=e=>BE(UT(e)),UE=(e,t)=>BE(VT((n,r)=>R(yE(e.channel,r),e=>t(e,r)))),WE=e=>e.channel,poe=(e,t)=>BE(qT(e,t)),GE=/*#__PURE__*/ BE(ZT),moe=e=>BE(XT(qa(e))),KE=e=>BE(JT(()=>e().channel)),hoe=e=>BE(QT(e)),goe=e=>BE($T(e)),_oe=e=>Ga(e)?BE(XT(e)):GE,qE=e=>BE(rE(e)),JE=e=>BE(iE(e)),YE=e=>BE(hE(z(e,WE))),XE=/*#__PURE__*/ O(2,(e,t)=>KE(()=>{let n=0;return BE(oE(e.channel,Ja(e=>t(e,n++))))})),voe=/*#__PURE__*/ O(e=>zE(e[0]),(e,t,n)=>e.channel.pipe(Mae,uE(t,n),oE(qa),BE)),yoe=/*#__PURE__*/ O(2,(e,t)=>BE(uE(e.channel,t))),boe=/*#__PURE__*/ O(2,(e,t)=>{let n=BE(jae(YT(()=>xoe(e,t))));return ZE.set(n,[e,t]),n}),ZE=/*#__PURE__*/ new WeakMap;function*xoe(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=ZE.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}const QE=/*#__PURE__*/ O(e=>zE(e[0])&&zE(e[1]),(e,t,n)=>BE(Lae(WE(e),WE(t),n))),Soe=/*#__PURE__*/ O(2,(e,t)=>e.channel.pipe(pE(e=>t(e).channel),BE)),Coe=/*#__PURE__*/ O(2,(e,t)=>e.channel.pipe(Nae(t),BE)),woe=/*#__PURE__*/ O(2,(e,t)=>BE(mE(e.channel,e=>t(e).channel))),Toe=e=>BE(Fae(e.channel)),Eoe=/*#__PURE__*/ O(2,(e,t)=>{let n=ya(t);return n===0?e:UE(e,(e,t)=>P(()=>{let t=0,r=e.pipe(R(e=>t>=n?N(e):(t+=e.length,t<=n?r:N(e.slice(n-t)))));return r}))}),$E=/*#__PURE__*/ O(2,(e,t)=>UE(e,(e,n)=>P(()=>{let r,i,a=Sp(()=>{if(i!==void 0){let e=i;return i=void 0,N(e)}return e}).pipe(Lp(e=>(r=Hd(e),Md()))),o=z(Sp(()=>t.transform(a,n)),([e,t])=>(i=t,qa(e)));return Sp(()=>r||o)}))),Doe=/*#__PURE__*/ O(2,(e,t)=>BE(Bae(e.channel,t))),Ooe=/*#__PURE__*/ O(e=>zE(e[0]),(e,t)=>KE(()=>{let n=new TextDecoder(t?.encoding);return XE(e,e=>n.decode(e,{stream:!0}))})),koe=e=>KE(()=>{let t=new TextEncoder;return XE(e,e=>t.encode(e))}),Aoe=e=>e.channel.pipe(zae(Rae()),BE),joe=/*#__PURE__*/ O(2,(e,t)=>BE(Hae(e.channel,t))),Moe=/*#__PURE__*/ O(2,(e,t)=>BE(Uae(e.channel,t))),eD=/*#__PURE__*/ O(2,(e,t)=>BE(Wae(e.channel,t))),tD=/*#__PURE__*/ O(2,(e,t)=>dm(n=>yE(e.channel,n).pipe(R(e=>t.transform(e,n)),z(([e])=>e)))),Noe=e=>vE(e.channel,()=>[],(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n]);return e}),Poe=e=>z(Gae(e.channel),Li(Kee)),Foe=/*#__PURE__*/ O(2,(e,t)=>_E(e.channel,e=>{let n=0;return vp({while:()=>n<e.length,body:()=>t(e[n++]),step:Dt})})),nD=/*#__PURE__*/ O(2,(e,t)=>_E(e.channel,t)),Ioe=e=>vE(e.channel,()=>``,(e,t)=>e+t.join(``)),rD=/*#__PURE__*/ O(e=>zE(e[0]),(e,t,n)=>{let r,i,a=sw(!1);return new ReadableStream({start(n){i=Pm(rm(nD(e,e=>a.whenOpen(P(()=>{a.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0}))),t)),i.addObserver(e=>{e._tag===`Failure`?n.error(Sd(e.cause)):n.close()})},pull(){return new Promise(e=>{r=e,a.openUnsafe()})},cancel(){if(i)return Im(Ip(iw(i)))}},n?.strategy)}),Loe=/*#__PURE__*/ O(e=>zE(e[0]),(e,t)=>z(em(),n=>rD(e,n,t))),iD=`~effect/FileSystem`,aD=/*#__PURE__*/ j(`effect/FileSystem`),Roe=e=>aD.of({...e,[iD]:iD,exists:t=>Ot(e.access(t),Fp(!0),Rp(`PlatformError`,e=>e.reason._tag===`NotFound`?N(!1):L(e))),readFileString:(t,n)=>R(e.readFile(t),e=>Op({try:()=>new TextDecoder(n).decode(e),catch:e=>wE({module:`FileSystem`,method:`readFileString`,description:`invalid encoding`,cause:e})})),stream:B(function*(t,n){let r=yield*e.open(t,{flag:`r`}),i=n?.offset===void 0?void 0:Fh(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:Fh(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return HE(N(R(Sp(()=>a!==void 0&&a<=o?Md():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),ji({onNone:()=>Md(),onSome:e=>(o+=BigInt(e.length),N(qa(e)))}))))},YE),sink:(t,n)=>Ot(e.open(t,{...n,flag:n?.flag??`w`}),z(e=>Qae(t=>e.writeAll(t))),eoe),writeFileString:(t,n,r)=>R(Op({try:()=>new TextEncoder().encode(n),catch:e=>wE({module:`FileSystem`,method:`writeFileString`,description:`could not encode string`,cause:e})}),n=>e.writeFile(t,n,r))}),oD=`~effect/FileSystem/File`;var zoe=class extends (/*#__PURE__*/ j()(`effect/FileSystem/WatchBackend`)){};const sD=`~effect/Path`,cD=/*#__PURE__*/ j(`effect/Path`);function Boe(e){return{_tag:`Value`,value:e}}function Voe(e,t){return{_tag:`Record`,keys:e,value:t}}function Hoe(e,t){return{_tag:`Array`,length:e,value:t}}const Uoe=/*#__PURE__*/ _a(`effect/ConfigProvider`,{defaultValue:()=>pD()}),Woe={...hr,toJSON(){return{_id:`ConfigProvider`}}},Goe=e=>e;function Koe(e,t){let n=Object.create(Woe);return n.load=e,n.mapInput=t,n}function lD(e,t){return Koe(n=>e(t(n)),n=>lD(e,e=>n(t(e))))}function uD(e){return lD(e,Goe)}function dD(e,t){return e===``&&!t?void 0:e}function fD(e,t){let n=t?.preserveEmptyStrings===!0,r=mD(e);return uD(t=>N(hD(r,e,t,n)))}function pD(e){return fD(e?.env??{...globalThis.process?.env,...import.meta.env},{preserveEmptyStrings:e?.preserveEmptyStrings})}function mD(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 hD(e,t,n,r){let i=n.map(String).join(`_`),a=dD(Object.hasOwn(t,i)?t[i]:void 0,r),o=gD(e,n),s=o?.children?Object.keys(o.children):[];return s.length===0?a===void 0?void 0:Boe(a):s.every(Gee)?Hoe(Math.max(...s.map(e=>parseInt(e,10)))+1,a):Voe(new Set(s),a)}function gD(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 _D=/*#__PURE__*/ Ei(sd),vD=`~effect/Config`;var yD=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}};const bD={.../*#__PURE__*/ oi({label:`Config`,evaluate(e){return this.parse(e.getRef(Uoe))}}),[vD]:vD,toJSON(){return{_id:`Config`}}};function xD(e){let t=Object.create(bD);return t.evaluator=e,t.parse=t=>Zm(e(t,[]),Ap),t}const SD=(e,t,n)=>e.evaluator(t,n),CD=/*#__PURE__*/ O(2,(e,t)=>xD((n,r)=>Jm(SD(e,n,r),e=>wa(e)?ba(t):e))),wD=e=>Zt(e,`SourceError`),TD=()=>`<configuration>`,ED=e=>t=>zp(t,t=>Tp(md(t.reasons.map(e)))),DD=(e,t)=>e.load(t).pipe(ED(e=>pd(e)?vd(e.error).annotate(Ld(e)):e),Jm(n=>({provider:e,path:t,node:n,toString:TD}))),OD=(e,t)=>DD(e.provider,[...e.path,t]),kD=(e,t)=>wb(gy,e,new Fv(yv(e=>t(e)),_v())),AD=e=>{switch(e._tag){case`Union`:return e.types.every(AD);case`Objects`:case`Arrays`:case`Suspend`:return!1;default:return!0}},jD=(e,t)=>{switch(e._tag){case`Objects`:return t?._tag===`Record`;case`Arrays`:return t?._tag===`Array`;case`Union`:return e.types.some(e=>jD(e,t));case`Suspend`:return jD(e.thunk(),t);default:return t?.value!==void 0}},MD=/*#__PURE__*/ At(e=>{let t=/* @__PURE__ */ new WeakSet,n=Hre(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>ox(e.parameter)),r=B(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*OD(n,e);t.node!==void 0&&ir(a,e,t)}return a});return kD(e.recur(n,e=>e),r)}case`Arrays`:{let t=B(function*(e){if(e.node?._tag!==`Array`)return;let t=[];for(let n=0;n<e.node.length;n++)t.push(yield*OD(e,n));return t});return kD(e.recur(n),t)}case`Union`:for(let t of e.types)n(t);if(!AD(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 kD(e,e=>N(e.node?.value))});return n(e)});function ND(e,t){let n=YC(e),r=Ob(n.ast),i=sx(mS(MD(n.ast))),a=typeof t==`string`?[t]:t??[];return xD((e,t)=>{let n=[...t,...a];return DD(e,n).pipe(Zm(e=>i(e).pipe(Jm(ba),Qm(t=>{let i=new yD(new nS(n.length>0?new I_(n,t):t));return jD(r,e.node)?L(i):N(xa(i))}))),ED(e=>zne(e)&&wD(e.defect)?_d(new yD(e.defect)).annotate(Ld(e)):e))})}const PD=/*#__PURE__*/ uC.check(/*#__PURE__*/ cC({minimum:1,maximum:65535})),FD=e=>It(e)||globalThis.Array.isArray(e);function ID(e){return ND(H,e)}function LD(e,t,n){let r=FD(t),i=r?n:t,a=W(e),o=i?.separator??`,`;return ND(G([H.pipe(VS(YC(a),{decode:Av(i),encode:fv(_v({strict:!1}),vv(e=>e.join(o)))})),a]),r?t:void 0)}function RD(e){return ND(GS,e)}function zD(e){return ND(PD,e)}function BD(e){return ND(BC(H),e)}const VD=2**48-1,HD=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,UD=(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)),VD),r=``;for(let e=45;e>=0;e-=5)r+=HD[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+=HD[i>>>a&31];i&=(1<<a)-1}return r},WD=e=>e.toString(16).padStart(2,`0`),GD=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,WD).join(``)).join(`-`),KD=()=>globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));function qD(e=KD()){return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e}const JD=e=>GD(e===void 0?qD():qD(e)),YD=2**48-1;function XD(e,t=KD()){let n=Math.min(Math.max(0,Math.trunc(e)),YD);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 ZD=(e,t)=>GD(t===void 0?XD(e):XD(e,t)),QD=`~effect/Crypto`,$D=/*#__PURE__*/ j(`effect/Crypto`),eO=e=>{let t=e.randomBytes,n=e=>z(tO(`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 $D.of({[QD]:QD,randomBytes:n,nextDoubleUnsafe:i,nextIntUnsafe:a,digest:e.digest,random:P(()=>i()),randomBoolean:P(()=>i()>.5),randomInt:P(()=>a()),randomBetween:(e,t)=>P(()=>Qne(e,t,i())),randomIntBetween(e,t,n){let r=n?.halfOpen===!0?0:1;return P(()=>{let n=Math.ceil(e),a=Math.floor(t);return Math.floor(i()*(a-n+r))+n})},randomShuffle:e=>P(()=>{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:P(()=>JD(t(16))),randomUUIDv7:Bm(e=>N(ZD(e.currentTimeMillisUnsafe(),t(16)))),randomULID:Bm(e=>N(UD(e.currentTimeMillisUnsafe(),t(10))))})},tO=(e,t)=>Number.isSafeInteger(t)&&t>=0?N(t):L(wE({module:`Crypto`,method:e,description:`size must be a non-negative safe integer`})),nO=e=>kp(t=>(fd(t,e),F)),rO=`~effect/ErrorReporter/ignore`,iO=`~effect/Match/Matcher`,aO={[iO]:{_input:k,_filters:k,_remaining:k,_result:k,_return:k,_args:k},_tag:`TypeMatcher`,add(e){return oO(this.select,[...this.cases,e])},pipe(){return bt(this,arguments)}};function oO(e,t){let n=Object.create(aO);return n.select=e,n.cases=t,n}const sO={[iO]:{_input:k,_filters:k,_result:k,_return:k,_flavor:k},_tag:`ValueMatcher`,add(e){return Ta(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?cO(this.provided,ba(e.evaluate(this.provided))):this},pipe(){return bt(this,arguments)}};function cO(e,t){let n=Object.create(sO);return n.provided=e,n.value=t,n}const lO=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),uO=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(uO),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,uO(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},dO=()=>oO(k,[]),fO=e=>cO(e,xa(e)),pO=(e,t)=>n=>n.add(lO(uO(e),t)),mO=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(lO(i,n))},hO=e=>t=>{let n=lO(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},gO=/*#__PURE__*/ mO(`_tag`),_O=/*#__PURE__*/ hO(`_tag`),vO=(...e)=>{let t=e.length;return n=>{for(let r=0;r<t;r++)if(n===e[r])return!0;return!1}},yO=e=>t=>{let n=bO(t);return Ca(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Ta(r)?r.success:e(r.failure,...t)}},bO=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?ba(t.evaluate(r,...n)):xa(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return ba(t.evaluate(r,...n))}return xa(r)}},xO=`effect/match/Match/exhaustive: absurd`,SO=e=>{let t=bO(e);if(Ca(t)){if(Ta(t))return t.success;throw Error(xO)}return(...e)=>{let n=t(...e);if(Ta(n))return n.success;throw Error(xO)}},CO=dO,wO=fO,TO=pO,EO=gO,DO=_O,OO=vO,kO=It,AO=Lt,jO=Rt,MO=yO,NO=SO,PO={"~effect/Ref":{_A:k},...hr,toJSON(){return{_id:`Ref`,ref:this.ref}}},FO=e=>{let t=Object.create(PO);return t.ref=dw(e),t},IO=e=>P(()=>FO(e)),LO=e=>P(()=>e.ref.current),RO=/*#__PURE__*/ O(2,(e,t)=>P(()=>fw(e.ref,t))),zO=/*#__PURE__*/ O(2,(e,t)=>P(()=>{let n=e.ref.current;return e.ref.current=t,n})),BO=/*#__PURE__*/ O(2,(e,t)=>e===void 0?void 0:t(e)),VO=`~effect/Stdio`,HO=/*#__PURE__*/ j(VO),UO=e=>({[VO]:VO,stdinIsTerminal:N(!1),stdoutIsTerminal:N(!1),...e}),WO=`~effect/Terminal`,GO=`~effect/Terminal/QuitError`;var KO=class extends (/*#__PURE__*/ KC(`QuitError`)({_tag:/*#__PURE__*/ YS(`QuitError`)})){[GO]=GO};const qO=/*#__PURE__*/ j(`effect/Terminal`),JO=e=>qO.of({...e,[WO]:WO}),YO=/*#__PURE__*/ QC(),XO=/*#__PURE__*/ QC(),ZO=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,QO={[ZO]:ZO,...Zn,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},$O=e=>Object.setPrototypeOf({...e},QO),ek=e=>{let t=(t,n)=>e(t).pipe(z(e=>Ooe(n?.includeStderr===!0?e.all:e.stdout)),YE),n=(e,n)=>Aoe(t(e,n));return tk.of({spawn:e,exitCode:t=>um(R(e(t),e=>e.exitCode)),streamString:t,streamLines:n,lines:(e,t)=>Noe(n(e,t)),string:(e,n)=>Ioe(t(e,n))})};var tk=class extends (/*#__PURE__*/ j()(`effect/process/ChildProcessSpawner`)){};const nk=`~effect/process/ChildProcess`,rk={.../*#__PURE__*/ oi({label:`Command`,evaluate(e){return ca(e.context,tk).spawn(this)}}),[nk]:nk},ik=(e,t,n)=>Object.assign(Object.create(rk),{_tag:`StandardCommand`,command:e,args:t,options:n}),ak=function(...e){if(ok(e[0])){let[t,...n]=e,r=lk(t,n);return ik(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!ok(e[0])){let t=e[0];return function(e,...n){let r=lk(e,n);return ik(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return ik(t,[],n)}let[t,n=[],r={}]=e;return ik(t,n,r)},ok=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),sk=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},ck=e=>`fd${e}`,lk=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=uk(e,t,n,i,r);return n},uk=(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}=mk(r,a),l=hk(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>dk(e)):[dk(u)];return hk(l,d,s)},dk=e=>typeof e==`string`?e:String(e),fk=/*#__PURE__*/ new Set([` `,` `,`\r`,`
|
|
21
|
+
`]),pk={x:3,u:5},mk=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let n=fk.has(t[0]),r=[],i=0;for(let n=0,a=0;n<e.length;n+=1,a+=1){let o=t[a];if(fk.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+=pk[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},hk=(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)],gk=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},_k=(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 CE({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})},vk=e=>kE(sE(yk(e),e=>[e])),yk=e=>VT(t=>{let n=e.evaluate();return N(bk({...e,writable:n,pull:t}))}),bk=e=>e.pull.pipe(R(t=>{let n=0;return Cp(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(F)};return a(),P(()=>{i=!0,e.writable.off(`drain`,a)})})}),Tm({disableYield:!0}),e.endOnDone===!1?k:up(t=>`closed`in e.writable&&e.writable.closed?Md(t):Cp(n=>{let r=()=>n(Md(t));return e.writable.once(`finish`,r),e.writable.end(),P(()=>{e.writable.off(`finish`,r)})})),Xp(Cp(t=>{let n=n=>t(L(e.onError(n)));return e.writable.once(`error`,n),P(()=>{e.writable.off(`error`,n)})}))),xk=e=>BE(Sk(e)),Sk=e=>VT((t,n)=>Dk({scope:n,readable:e.evaluate(),onError:e.onError??Ok,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),Ck=e=>VT((t,n)=>{let r=e.evaluate(),i=dw(void 0),a=sw(!1);return bk({pull:t,writable:r,onError:e.onError??Ok,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(zp(e=>dp(e)?F:(i.current=Vd(e),a.openUnsafe(),F)),Mm(n),R(()=>Dk({scope:n,exit:i,latch:a,readable:r,onError:e.onError??Ok,chunkSize:e.chunkSize})))}),wk=/*#__PURE__*/ O(2,(e,t)=>Doe(e,Ck(t))),Tk=(e,t)=>{let n=kk(t?.maxBytes),r=t?.onError??Ok;return Cp(t=>{let i=e(),a=[],o=0;return i.once(`error`,e=>{`closed`in i&&!i.closed&&i.destroy(),t(L(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(N(e.buffer));t(N(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(L(r(/* @__PURE__ */ Error(`maxBytes exceeded`)))))}),P(()=>{`closed`in i&&!i.closed&&i.destroy()})})},Ek=(e,t)=>z(Tk(e,t),e=>new Uint8Array(e)),Dk=e=>{let t=e.readable,n=e.closeOnDone??!0,r=e.exit??dw(void 0),i=e.latch??sw(!1);function a(){i.openUnsafe()}function o(t){r.current=Hd(e.onError(t)),i.openUnsafe()}function s(){r.current=Hd(jd()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=Sp(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?L(jd()):(i.closeUnsafe(),R(i.await,n));let o=qa(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return N(o)});return Fp(yf(e.scope,P(()=>{t.off(`readable`,a),t.off(`error`,o),t.off(`end`,s),n&&`closed`in e.readable&&!e.readable.closed&&e.readable.destroy()})),c)},Ok=e=>new Fd(e),kk=e=>e===void 0||e===1/0?void 0:Number(Fh(e)),Ak=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),jk=(e,t,n)=>{let{commands:r}=Ik(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return _k(`ChildProcess`,e)(t,[i])},Mk=1e3,Nk=(e,t)=>{if(!cf(t))return!0;if(globalThis.process.platform===`win32`)return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},Pk=(e,t=()=>{})=>nt.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t),Fk=/*#__PURE__*/ Hf(tk,/* @__PURE__ */ I(function*(){let e=yield*aD,t=yield*cD,n=B(function*(n){if(!Ht(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=>zE(e)?`pipe`:e,a=e=>OE(e)?`pipe`:e,o=e=>{let t={stream:`pipe`,encoding:`utf-8`,endOnDone:!0};return Ht(e.stdin)?t:typeof e.stdin==`string`||zE(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 Ht(n)?{stream:`pipe`}:typeof n==`string`||OE(n)?{stream:n}:{stream:n.stream}},c=e=>{if(Ht(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=sk(n);Ut(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=B(function*(e,t,n){if(n.length===0)return{getInputFd:()=>jE,getOutputFd:()=>GE};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=jE;n&&`write`in n&&(t=vk({evaluate:()=>n,onError:t=>jk(`fromWritable(fd${o})`,Ak(t),e)})),a.stream&&(yield*Nm(tD(a.stream,t))),r.set(o,t);break}case`output`:{let t=GE;if(n&&`read`in n){let r=new it;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=xk({evaluate:()=>r,onError:t=>jk(`fromReadable(fd${o})`,Ak(t),e)})}a.sink&&(t=$E(t,a.sink)),i.set(o,t);break}}}return{getInputFd:e=>r.get(e)??jE,getOutputFd:e=>i.get(e)??GE}}),d=(e,t,n)=>Sp(()=>{let r=jE;return Wt(t.stdin)&&(r=vk({evaluate:()=>t.stdin,onError:t=>jk(`fromWritable(stdin)`,Ak(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),zE(n.stream)?Fp(Nm(tD(n.stream,r)),r):N(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new it;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),xk({evaluate:()=>n,onError:t=>jk(`fromReadable(stdout)`,Ak(t),e)})})():GE,a=t.stderr?(()=>{let n=new it;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),xk({evaluate:()=>n,onError:t=>jk(`fromReadable(stderr)`,Ak(t),e)})})():GE;OE(n.stream)&&(i=$E(i,n.stream)),OE(r.stream)&&(a=$E(a,r.stream));let o=QE(i,a);return{stdout:i,stderr:a,all:o}},p=(e,t)=>Cp(n=>{let r=ef(),i=nt.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(L(jk(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{uf(r,Bd(e))}),i.on(`spawn`,()=>{n(N([i,r]))}),P(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?Cp(n=>{Pk(t,t=>{n(t?L(jk(`kill`,Ak(t),e)):F)})}):Op({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>jk(`kill`,Ak(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`){Pk(e);return}try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>Sp(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return L(jk(`kill`,t,e))}return F}),_=(e,t,n)=>Cp(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{if(clearTimeout(a),Date.now()>=i||!Nk(e,t)){o(),r(F);return}a=setTimeout(s,10)};return e.on(`exit`,s),s(),P(o)}),v=B(function*(e,t,n,r){let i=n=>m(e,t,n).pipe(Lp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),Ht(r?.forceKillAfter)?yield*_(t,n,Mk):(yield*_(t,n,bo(r.forceKillAfter)),Nk(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,Mk))),yield*nf(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=sk(n);return Ut(t)?e.getOutputFd(t):e.stdout}}},b=B(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*fm(p(e,gk(e.options,{cwd:_,env:y,stdio:b},process.platform)),B(function*([t,n]){if(yield*sf(n)){let[r]=yield*nf(n);(r!==0&&Wt(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*Kp(v(e,t,n,e.options)));return}g&&(yield*Kp(v(e,t,n,e.options)))})),C=XO(x.pid);x.on(`exit`,t=>{t!==0&&Wt(t)&&h(x,e.options.killSignal??`SIGTERM`)});let w=P(()=>{g||=(x.ref(),!0)}),T=P(()=>(g&&=(x.unref(),!1),w)),ee=yield*d(e,x,t),{all:te,stderr:E,stdout:ne}=f(e,x,i,a),{getInputFd:re,getOutputFd:ie}=yield*u(e,x,m),ae=z(sf(S),e=>!e),oe=R(nf(S),([t,n])=>{if(Wt(t))return N(YO(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return L(jk(`exitCode`,r,e))});return $O({pid:C,exitCode:oe,isRunning:ae,kill:t=>v(e,x,S,t),stdin:ee,stdout:ne,stderr:E,all:te,getInputFd:re,getOutputFd:ie,unref:T})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=Ik(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=YE(N(y(a[a.length-1],r.from))),l=r.to??`stdin`;if(l===`stdin`)a.push(yield*b(ak(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=sk(l);if(Ut(e)){let n=ck(e),r=t.options.additionalFds??{};a.push(yield*b(ak(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(ak(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>_p([...a].reverse(),t=>Kp(t.kill(e)),{discard:!0}),l=I(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return _p([...e].reverse(),e=>e,{discard:!0})});return $O({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 ek(b)})),Ik=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}},Lk=`~effect/http/HttpBody`,Rk=`~effect/http/HttpBody/HttpBodyError`;var zk=class extends (/*#__PURE__*/ Bo(`HttpBodyError`)){[Rk]=Rk},Bk=class{[Lk];constructor(){this[Lk]=Lk}[Jn](){return this.toJSON()}toString(){return Rn(this,{ignoreToString:!0})}};const Vk=/*#__PURE__*/ new class extends Bk{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var Hk=class extends Bk{_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 Uk=(e,t)=>new Hk(e,t?.contentType,t?.contentLength);var Wk=class extends Bk{_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??=Jk(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 Gk=(e,t)=>new Wk(e,t??`application/octet-stream`,e.length),Kk=/*#__PURE__*/ new TextEncoder,qk=globalThis.Buffer,Jk=qk===void 0?e=>Kk.encode(e):e=>qk.from(e,`utf8`),Yk=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),qk!==void 0)return new Wk(void 0,t??`text/plain`,qk.byteLength(e,`utf8`),e);let n=Kk.encode(e);return new Wk(n,t??`text/plain`,n.length,e)},Xk=(e,t)=>Yk(JSON.stringify(e),t??`application/json`),Zk=(e,t)=>Op({try:()=>Yk(JSON.stringify(e),t??`application/json`),catch:e=>new zk({reason:{_tag:`JsonError`},cause:e})}),Qk=(e,t)=>{let n=cx(JC(e));return(e,r)=>n(e,t).pipe(Hp(e=>new zk({reason:{_tag:`SchemaError`,issue:e},cause:e})),R(e=>Zk(e,r)))};var $k=class extends Bk{_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 eA=(e,t,n)=>new $k(e,t??`application/octet-stream`,n),tA=`~effect/http/HttpClientError`;var nA=class extends (/*#__PURE__*/ Bo(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[tA]=tA;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 rA=e=>e.endsWith(`Error`)?e.slice(0,-5):e,iA=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`;var aA=class extends (/*#__PURE__*/ Bo(`TransportError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return iA(rA(this._tag),this.description,this.methodAndUrl)}},oA=class extends (/*#__PURE__*/ Bo(`InvalidUrlError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return iA(rA(this._tag),this.description,this.methodAndUrl)}},sA=class extends (/*#__PURE__*/ Bo(`StatusCodeError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return iA(rA(this._tag),this.description,e)}},cA=class extends (/*#__PURE__*/ Bo(`DecodeError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return iA(rA(this._tag),this.description,e)}},lA=class extends (/*#__PURE__*/ Bo(`EmptyBodyError`)){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return iA(rA(this._tag),this.description,e)}};const uA=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,dA=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],fA=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?Yg(Yg(e,`content-type`),`content-length`):(e=t.contentType===void 0?Yg(e,`content-type`):Kg(e,`content-type`,t.contentType),t.contentLength===void 0?Yg(e,`content-length`):Kg(e,`content-length`,t.contentLength.toString())),pA=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var mA=class extends (/*#__PURE__*/ Bo(`UrlError`)){};const hA=(e,t,n)=>Sa({try:()=>{let r=new URL(e,gA());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,i)}return n!==void 0&&(r.hash=n),r},catch:e=>new mA({cause:e})}),gA=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},_A=`~effect/http/HttpClientRequest`,vA={[_A]:_A,...Zn,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Nn(this.headers),body:this.body.toJSON()}},pipe(){return bt(this,arguments)}};function yA(e,t,n,r,i,a){let o=Object.create(vA);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const bA=/*#__PURE__*/ yA(`GET`,``,c_,/*#__PURE__*/ Di(),Ug,Vk),xA=e=>(t,n)=>wA(bA,{method:e,url:t,...n??void 0}),SA=/*#__PURE__*/ xA(`GET`),CA=/*#__PURE__*/ xA(`POST`),wA=/*#__PURE__*/ O(2,(e,t)=>{let n=e;return t.method&&(n=TA(n,t.method)),t.url&&(n=AA(n,t.url)),t.headers&&(n=DA(n,t.headers)),t.urlParams&&(n=jA(n,t.urlParams)),t.hash&&(n=MA(n,t.hash)),t.body&&(n=NA(n,t.body)),t.accept&&(n=OA(n,t.accept)),t.acceptJson&&(n=kA(n)),n}),TA=/*#__PURE__*/ O(2,(e,t)=>yA(t,e.url,e.urlParams,e.hash,e.headers,e.body)),EA=/*#__PURE__*/ O(3,(e,t,n)=>yA(e.method,e.url,e.urlParams,e.hash,Kg(e.headers,t,n),e.body)),DA=/*#__PURE__*/ O(2,(e,t)=>yA(e.method,e.url,e.urlParams,e.hash,qg(e.headers,t),e.body)),OA=/*#__PURE__*/ O(2,(e,t)=>EA(e,`Accept`,t)),kA=/*#__PURE__*/ OA(`application/json`),AA=/*#__PURE__*/ O(2,(e,t)=>{if(typeof t==`string`)return yA(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=i_(n.searchParams),i=Ni(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,yA(e.method,n.toString(),r,i,e.headers,e.body)}),jA=/*#__PURE__*/ O(2,(e,t)=>yA(e.method,e.url,l_(e.urlParams,t),e.hash,e.headers,e.body)),MA=/*#__PURE__*/ O(2,(e,t)=>yA(e.method,e.url,e.urlParams,Oi(t),e.headers,e.body)),NA=/*#__PURE__*/ O(2,(e,t)=>yA(e.method,e.url,e.urlParams,e.hash,fA(e.headers,t),t)),PA=/*#__PURE__*/ O(2,(e,t)=>NA(e,Xk(t)));function FA(e){let t=hA(e.url,e.urlParams,Fi(e.hash));return Ta(t)?Oi(t.success):Di()}const IA=`~effect/http/HttpIncomingMessage`,LA=(e,t)=>{let n=cS(JC(e)),r=t?.reviver===void 0?void 0:cS(wC(JC(e),t));return e=>r===void 0?R(e.json,e=>n(e,t)):R(e.text,i=>i===``?R(e.json,e=>n(e,t)):r(i,t))},RA=/*#__PURE__*/ _a(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),zA=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=Rm(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=Rm(e.text)}catch{}let i={...t,headers:Nn(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},BA=`~effect/http/HttpClientResponse`,VA=(e,t)=>new HA(e,t);var HA=class extends Qn{[IA];[BA];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[IA]=IA,this[BA]=BA}toJSON(){return zA(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=FA(this.request);return ki(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Wg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=fg(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Di()}get stream(){return this.source.body?JE({evaluate:()=>this.source.body,onError:e=>new nA({reason:new cA({request:this.request,response:this,cause:e})})}):hoe(new nA({reason:new lA({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return R(this.text,e=>Op({try:()=>e===``?null:JSON.parse(e),catch:e=>new nA({reason:new cA({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=z(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return R(this.text,e=>Op({try:()=>i_(new URLSearchParams(e)),catch:e=>new nA({reason:new cA({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=bp({try:()=>this.source.formData(),catch:e=>new nA({reason:new cA({request:this.request,response:this,cause:e})})}).pipe(vm,Rm)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=bp({try:()=>this.source.arrayBuffer(),catch:e=>new nA({reason:new cA({request:this.request,response:this,cause:e})})}).pipe(vm,Rm),this.arrayBufferBody}pipe(){return bt(this,arguments)}};const UA=e=>Gg({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${ji(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),WA=e=>{let t=YA(e);return Ai(t)||(t=GA(e),Ai(t))?t:KA(e)},GA=e=>{if(!(`b3`in e))return Di();let t=e.b3.split(`-`);return t.length<2?Di():Oi(Zo({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},KA=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]?Di():Oi(Zo({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`})),qA=/^[0-9a-f]{32}$/i,JA=/^[0-9a-f]{16}$/i,YA=e=>{if(!e.traceparent)return Di();let t=e.traceparent.split(`-`);if(t.length!==4)return Di();let[n,r,i,a]=t;switch(n){case`00`:return qA.test(r)===!1||JA.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Di():Oi(Zo({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Di()}},XA={"http:":80,"https:":443,"ws:":80,"wss:":443},ZA=(e,t)=>{let n=t.search.slice(1);if(e.attribute(`url.full`,t.toString()),e.attribute(`url.path`,t.pathname),n!==``&&e.attribute(`url.query`,n),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===``?XA[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},QA=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Qg(a,i)?`<redacted>`:n[a])},$A=`~effect/http/HttpClient`,ej=/*#__PURE__*/ j(`effect/HttpClient`),tj=/*#__PURE__*/ O(2,(e,t)=>rj(R(n=>t(e.postprocess(N(n)),n)),e.preprocess)),nj=/*#__PURE__*/ O(2,(e,t)=>rj(n=>t(e.postprocess(n)),e.preprocess)),rj=(e,t)=>{let n=Object.create(ij);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},ij={[$A]:$A,pipe(){return bt(this,arguments)},...Zn,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ dA.map(([e,t])=>[t,function(t,n){return this.execute(xA(e)(t,n))}]))},aj=e=>rj(t=>R(t,t=>kp(n=>{let r=mj.get(t),i=r??new AbortController,a=hA(t.url,t.urlParams,Fi(t.hash));if(wa(a))return L(new nA({reason:new oA({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Qo)||n.getRef(cj)(t)){let a=e(t,o,i.signal,n);return r?a:wm(e=>Qp(e(a),{onSuccess(e){return pj.register(e,i),N(new hj(e,i))},onFailure(e){return Ed(e)&&i.abort(),Tp(e)}}))}return Om(n.getRef(dj)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef($g);ZA(a,o);let c=n.getRef(lj);return QA(a,`request`,t.headers,c,s),t=n.getRef(uj)?DA(t,UA(a)):t,wm(l=>l(e(t,o,i.signal,n)).pipe(Am(a,{captureStackTrace:!1}),Qp({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),QA(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),oj(n,a,t,e)),r?N(e):(pj.register(e,i),N(new hj(e,i)))),onFailure(e){return!r&&Ed(e)&&i.abort(),Tp(e)}})))})})),N),oj=(e,t,n,r)=>{let i=er();tr(0);let a;try{a=Hd(new nA({reason:new sA({request:n,response:r})}))}finally{tr(i)}t.end(e.getRef(pf)?e.getRef($f).currentTimeNanosUnsafe():BigInt(0),a)},sj=e=>tj(e,(e,t)=>{let n=new AbortController;return mj.set(t,n),jp(pm(()=>P(()=>n.abort())),e)}),cj=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Tt}),lj=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>Tt}),uj=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:wt}),dj=/*#__PURE__*/ _a(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),fj=e=>Hf(ej)(tm(t=>z(e,e=>nj(e,sm(e=>ma(t,e)))))),pj=/*#__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))}}})(),mj=/*#__PURE__*/ new WeakMap;var hj=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[BA]=BA;[IA]=IA;applyInterrupt(e){return Sp(()=>(pj.unregister(this.original),Sm(e,()=>P(()=>{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 KE(()=>(pj.unregister(this.original),Moe(this.original.stream,P(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Jn](){return this.original[Jn]()}pipe(){return bt(this,arguments)}};const gj=/\+/g,_j=function(){};_j.prototype=/*#__PURE__*/ Object.create(null);function vj(e){let t=new _j;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(gj,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(gj,` `)),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 yj=/^https?:\/\/.*?\//,bj=/(\/:[^/()]*?)\?(\/?)/,xj=[],Sj=/^[^:*(]*\/:[^/:*(.-]+$/,Cj=e=>Sj.test(e),wj=(e={})=>new Tj(e);var Tj=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(bj);if(r&&r.index!==void 0){Mj(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(bj,`$1$2`),a=t.replace(bj,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=Nj(t)),this.options.ignoreTrailingSlash&&(t=Pj(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(Hj,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new kj(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new kj(``),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=Ij(r,d),t=r.slice(d,e+1);c.push(Lj(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=Rj(_))),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(Cj(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(yj,`/`)),this.options.ignoreDuplicateSlashes&&(t=Nj(t));let e;try{e=Bj(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreTrailingSlash&&(t=Pj(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(xj),searchParams:vj(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=Vj(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:vj(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:vj(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=Vj(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=Vj(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}}}},Ej=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Fj(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},Dj=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 Ej),this.isLeafNode=!0,this.handlerStorage.add(e)}},Oj=class extends Dj{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 kj(e),this.staticChildren[n]}},kj=class e extends Oj{_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 Aj(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 jj),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}},Aj=class extends Oj{_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)}},jj=class extends Dj{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Mj=(e,t)=>{if(!e)throw Error(t)};function Nj(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function Pj(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Fj(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 Ij(e,t){let n=1;for(;t<e.length;){if(t++,e[t]===`\\`){t++;continue}if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function Lj(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 Rj(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function zj(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 Bj(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);zj(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 Vj(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=zj(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 Hj=/* @__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(`.`),Uj=wj,Wj=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var Gj=class extends (/*#__PURE__*/ j()(`effect/http/Etag/Generator`)){};const Kj=e=>{let t=ji(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},qj=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,Jj=/*#__PURE__*/ zf(Gj)({fromFileInfo(e){return P(()=>({_tag:`Strong`,value:Kj(e)}))},fromFileWeb(e){return P(()=>({_tag:`Strong`,value:qj(e)}))}}),Yj=/*#__PURE__*/ zf(Gj)({fromFileInfo(e){return P(()=>({_tag:`Weak`,value:Kj(e)}))},fromFileWeb(e){return P(()=>({_tag:`Weak`,value:qj(e)}))}}),Xj=/*#__PURE__*/ Object.getPrototypeOf(Ug),Zj=()=>Object.create(Xj),Qj=`~effect/http/HttpServerResponse`,$j=e=>A(e,Qj),eM=e=>xM({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?Wg(e.headers):void 0,cookies:e?.cookies}),tM=(e,t)=>{let n=Gg({location:e.toString()});return xM({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?Jg(n,Wg(t.headers)):n,cookies:t?.cookies??mg})},nM=(e,t)=>{let n=t?.headers?Wg(t.headers):Ug;return xM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??mg,body:Gk(e,rM(t,n))})},rM=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},iM=(e,t)=>{let n=t?.headers?Wg(t.headers):Ug;return xM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??mg,body:Yk(e,rM(t,n))})},aM=(e,t)=>{let n=Qk(e,t);return(e,t)=>{let r=t?.headers?Wg(t.headers):Ug;return z(n(e,rM(t,r)),e=>xM({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},oM=(e,t)=>{let n=t?.headers?Wg(t.headers):Ug;return xM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Xk(e,rM(t,n))})},sM=(e,t)=>{let n=t?.headers?Wg(t.headers):Ug;return xM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:Yk(u_(i_(e)),rM(t,n)??`application/x-www-form-urlencoded`)})},cM=(e,t)=>xM({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&Wg(t.headers),cookies:t?.cookies,body:Uk(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),lM=(e,t)=>{let n=t?.headers?Wg(t.headers):Ug;return xM({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:eA(e,rM(t,n),t?.contentLength)})},uM=/*#__PURE__*/ O(3,(e,t,n)=>xM(e,Kg(e.headers,t,n))),dM=/*#__PURE__*/ O(2,(e,t)=>xM({...e,headers:Yg(e.headers,t)})),fM=/*#__PURE__*/ O(2,(e,t)=>xM(e,qg(e.headers,t))),pM=/*#__PURE__*/ O(e=>$j(e[0]),(e,t,n,r)=>z(Ap(wg(e.cookies,t,n,r)),t=>xM({...e,cookies:t}))),mM=/*#__PURE__*/ O(2,(e,t)=>xM({...e,cookies:Cg(e.cookies,t)})),hM=/*#__PURE__*/ O(2,(e,t)=>xM({...e,body:t},fA(e.headers,t))),gM=/*#__PURE__*/ O(e=>$j(e[0]),(e,t,n)=>xM({...e,status:t,statusText:n??e.statusText})),_M=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,vM=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!hg(e.cookies)){let t=Og(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=_M(e),a=i||t?.withoutBody===!0;if(r._tag===`Raw`&&r.body instanceof Response){let t=r.body;for(let[e,r]of n)e===`set-cookie`?t.headers.append(e,r):t.headers.set(e,r);if(!a)return t;let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:t.headers})}if(a)return r._tag===`Raw`&&yM(r.body)&&r.body.cancel().catch(Dt),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(rD(r.stream,t?.context??ea()),{status:e.status,statusText:e.statusText,headers:n})}},yM=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,bM={...hr,[Qj]:Qj,[rO]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Nn(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},xM=(e,t)=>{let n=Object.create(bM);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??mg,n.body=e.body??Vk,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===Ug?Zj():Gg({...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??Ug;return n},SM=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=eM({status:e.status,statusText:e.statusText,headers:t,cookies:fg(n)});if(e.body){let t=e.headers.get(`content-type`);r=hM(r,eA(JE({evaluate:()=>e.body,onError:e=>e}),t??void 0,pA(e.headers.get(`content-length`))))}return r},CM=(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}`},wM=e=>({algorithms:e.algorithms,compressResponse(t,n,r){return z(e.compressResponse(t,n,r),e=>{if(e===t)return t;let r={"content-encoding":n,vary:CM(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),fM(e,r)})}}),TM={"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(TM);let EM;const DM=()=>{if(EM!==void 0)return EM;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(TM)){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 EM={extensionToType:e,typeToExtension:t,typeToExtensions:n},EM},OM=e=>{if(typeof e!=`string`)return Di();let t=e.replace(/^.*[/\\]/s,``).toLowerCase(),n=t.replace(/^.*\./s,``).toLowerCase(),r=t.length<e.length;return!(n.length<t.length-1)&&r?Di():Pi(DM().extensionToType.get(n))};var kM=class extends (/*#__PURE__*/ j()(`effect/http/HttpPlatform`)){};const AM=/*#__PURE__*/ B(function*(e){let t=yield*aD,n=yield*Gj;return kM.of({platform:e.platform,compression:wM(e.compression),fileResponse:B(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?Ah:yield*MM(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*MM(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*NM(c,`offset`),m=f===void 0?void 0:yield*NM(f,`end`),h=Kg(jM(i),`etag`,Wj(o));return Ai(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 z(n.fromFileWeb(t),n=>{let i=Jg(jM(r),Gg({etag:Wj(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),jM=e=>{let t=e?.headers?Wg(e.headers):Ug;return e?.contentType?Kg(t,`content-type`,e.contentType):t},MM=(e,t)=>{let n=Ih(e);return Ai(n)?N(n.value):L(wE({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},NM=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)?N(n):L(wE({module:`HttpPlatform`,method:`fileResponse`,description:`${t} exceeds the safe integer range: ${e}`}))},PM=`~effect/http/HttpServerRespondable`,FM=e=>A(e,PM),IM=/*#__PURE__*/ eM({status:400}),LM=/*#__PURE__*/ eM({status:404}),RM=(e,t)=>$j(e)?N(e):FM(e)?zp(e[PM](),()=>N(t)):Qx(e)?N(IM):kd(e)?N(LM):N(t),zM=(e,t)=>$j(e)?N(e):FM(e)?zp(e[PM](),()=>N(t)):N(t),BM=`~effect/http/HttpServerError`;var VM=class extends (/*#__PURE__*/ Bo(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[BM]=BM;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[PM](){return this.reason[PM]()}get[rO](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},HM=class extends (/*#__PURE__*/ Bo(`RequestParseError`)){[PM](){return N(eM({status:400}))}get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return qM(this._tag,this.description,this.methodAndUrl)}},UM=class extends (/*#__PURE__*/ Bo(`RouteNotFound`)){[PM](){return N(eM({status:404}))}[rO]=!0;get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return qM(this._tag,this.description,this.methodAndUrl)}};const WM=e=>A(e,BM);var GM=class extends (/*#__PURE__*/ Bo(`ResponseError`)){[PM](){return N(eM({status:500}))}get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},KM=class extends (/*#__PURE__*/ j()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ ra(Rd,{name:`ClientAbort`,stack:Et,parent:void 0}))};const qM=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},JM=e=>{let t,n=ZM,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=RM(s.error,XM),r.push(s);break;case`Die`:$j(s.defect)?t=s.defect:(n=zM(s.defect,XM),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(KM.key),r.length>0)break;i.push(s)}}return t?N([t,md(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?QM:$M),Jm(n,e=>(r.push(vd(e)),[e,md(r)])))},YM=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&$j(e.defect)?(t=e.defect,!1):!0);return[t??XM,n.length>0?Oi(md(n)):Di()]},XM=/*#__PURE__*/ eM({status:500}),ZM=/*#__PURE__*/ N(XM),QM=/*#__PURE__*/ N(/*#__PURE__*/ eM({status:499})),$M=/*#__PURE__*/ N(/*#__PURE__*/ eM({status:503})),eN=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,tN=/\\([\v\u0020-\u{10ffff}])/gu,nN=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,rN=/^[!#$%&'*+.^\w|~-]+$/u,iN={value:``,parameters:/*#__PURE__*/ Object.create(null)};function aN(e,t=!1){if(typeof e!=`string`)return iN;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?rN:nN).test(r)===!1)return iN;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(eN.lastIndex=n;o=eN.exec(e);){if(o.index!==n)return iN;n+=o[0].length,a=o[1].toLowerCase(),s=o[2],s[0]===`"`&&(s=s.slice(1,s.length-1),!t&&tN.test(s)&&(s=s.replace(tN,`$1`))),i.parameters[a]=s}return n===e.length?i:iN}const oN=16384,sN={key:0,whitespace:1,value:2},cN={_tag:`Continue`},lN=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")lN[/*#__PURE__*/ e.charCodeAt(0)]=1;const uN=/*#__PURE__*/ new Uint8Array(256);uN[9]=1;for(let e=32;e<=126;e++)uN[e]=1;for(let e=128;e<=255;e++)uN[e]=1;function dN(){let e=new TextDecoder,t={state:sN.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=sN.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===sN.key){let n=o;for(;n<l;n++){if(t.size++>oN)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=sN.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=sN.value):(o=n+1,t.state=sN.whitespace);break}if(lN[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),cN}if(t.state===sN.whitespace){for(;o<l;o++){if(t.size++>oN)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=sN.value;break}}if(o===l)return cN}if(t.state===sN.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>oN)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),cN;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=sN.key;continue outer}}else if(uN[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)),cN}}return o>l&&(t.size+=l-o),cN}}function qoe(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 Joe(e,t,n,r){let i=qoe(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;continue}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 fN={headers:0,body:1},Yoe={_tag:`InvalidDisposition`},Xoe={_tag:`EndNotReached`},Zoe={_tag:`ReachedLimit`,limit:`MaxParts`},Qoe={_tag:`ReachedLimit`,limit:`MaxTotalSize`},$oe={_tag:`ReachedLimit`,limit:`MaxPartSize`},pN={_tag:`ReachedLimit`,limit:`MaxFieldSize`},ese=/*#__PURE__*/ new TextEncoder().encode(`\r
|
|
23
|
+
`);function mN(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function tse(e){return aN(e[`content-type`]).parameters.boundary}function hN(e){}const gN=e=>e===1/0?1/0:Number(Fh(e));function nse({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=mN,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=gN(s),d=gN(c),f=gN(l),p=tse(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:hN,end(){}};let m={state:fN.headers,index:0,parts:0,onChunk:hN,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=fN.body,m.isFile=!0,m.onChunk=hN}function g(e){m.stopped=!0,m.state===fN.body&&m.isFile&&m.onChunk(null),r(e)}let _=dN(),v=Joe(`\r\n--${p}`,function(e,s){if(!m.stopped){if(e===0){h();return}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=fN.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(Zoe)}if((m.partSize+=s.length)>d)return g($oe);if(m.state===fN.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=aN(e.headers[`content-type`]),i=aN(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(Yoe);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=fN.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(pN);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(pN);m.fieldChunks.push(s)}}},ese,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(Qoe):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(Xoe),m.state=fN.headers,m.index=0,m.parts=0,m.onChunk=hN,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const _N=/*#__PURE__*/ new TextDecoder(`utf-8`);function rse(e){if(e===`utf-8`||e===`utf8`||e===``)return _N;try{return new TextDecoder(e)}catch{return _N}}function ise(e,t){return rse(e.contentTypeParameters.charset??`utf-8`).decode(t)}const ase=nse,ose=mN,sse=ise,vN=`~effect/http/Multipart`,yN=`~effect/http/Multipart/MultipartError`,cse=e=>dse(e)?e:bN.fromReason(`InternalError`,e);var lse=class extends zo{};const use={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var bN=class e extends (/*#__PURE__*/ Bo(`MultipartError`)){static fromReason(t,n){return new e({reason:new lse({_tag:t,cause:n})})}[yN]=yN;[rO]=!0;[PM](){return N(eM({status:use[this.reason._tag]}))}get message(){return this.reason._tag}};const dse=e=>A(e,yN),fse=e=>kp(t=>{let n=la(t.context,TN);return N({headers:e,maxParts:t.getRef(SN),maxFieldSize:t.getRef(CN),maxPartSize:t.getRef(wN),maxTotalSize:t.getRef(RA),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&ose(e)})});var pse=class extends Qn{[vN];constructor(){super(),this[vN]=vN}};const mse=(e,t)=>R(aD,n=>Hp(tD(t.content,n.sink(e)),cse)),hse=(e,t=mse)=>I(function*(){let n=yield*aD,r=yield*cD,i=yield*n.makeTempDirectoryScoped(),a=Object.create(null),o=/* @__PURE__ */ new Set,s=0;return yield*Foe(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,F;if(e.name===``)return F;let n=e,c=r.basename(n.name).slice(-128),l=r.join(i,c);for(;o.has(l);)l=r.join(i,`${s++}-${c}`);o.add(l);let u=new gse(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(Rp(`PlatformError`,e=>L(bN.fromReason(`InternalError`,e))));var gse=class extends pse{_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 xN=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(SN.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(CN.key,Fh(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(wN.key,Fh(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(RA.key,Fh(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(TN.key,e.fieldMimeTypes),Xi(t)},SN=/*#__PURE__*/ _a(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),CN=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ Ct(/*#__PURE__*/ Rh(10))}),wN=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),TN=/*#__PURE__*/ _a(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ Ct([`application/json`])}),EN=`~effect/http/HttpServerRequest`,DN=/*#__PURE__*/ j(`effect/http/HttpServerRequest`);var ON=class extends (/*#__PURE__*/ j()(`effect/http/ParsedSearchParams`)){};const _se=(e,t)=>{let n=sS(e);return R(DN,e=>n(e.cookies,t))},vse=(e,t)=>{let n=sS(e);return R(DN,e=>n(e.headers,t))},yse=(e,t)=>{let n=sS(e);return R(ON,e=>n(e,t))},bse=e=>{let t=e.headers.host??`localhost`,n=e.headers[`x-forwarded-proto`]===`https`?`https`:`http`;try{return Oi(new URL(e.url,`${n}://${t}`))}catch{return Di()}},kN=/*#__PURE__*/ new WeakMap,xse=(e,t)=>{let n=kN.get(e.source),r=n?(e,r)=>R(n(e,r),n=>t(e,n)):t;kN.set(e.source,r)},Sse=e=>e,Cse=/*#__PURE__*/ new WeakSet,wse=e=>kp(t=>{let n=ca(t.context,DN);return Cse.add(n.source),e}),Tse=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>Tt}),Ese=/*#__PURE__*/ _a(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Dse=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>Tt}),AN=(e,t)=>!e.cache.tracerEnabled||e.getRef(Tse)(t),jN=(e,t)=>{if(!(t.status>=500&&t.status<600))return Bd(t);let n=er();tr(0);try{return Hd(new VM({reason:new GM({request:e,response:t})}))}finally{tr(n)}},MN=/*#__PURE__*/ Sse(e=>kp(t=>{let n=ca(t.context,DN);if(AN(t,n))return e;let r=t.getRef(Ese),i=Pu(t,r(n),{parent:Fi(WA(n.headers)),kind:`server`}),a=t.context;return t.setContext(ra(t.context,Yo,i)),Kl(t,e=>{t.setContext(a);let r=t.getRef($f).currentTimeNanosUnsafe();if(Kd(e)&&(!i.sampled||t.getRef(ns)===rs)){i.end(r,jN(n,e.value));return}let o=t.getRef($g),s=t.getRef(Dse);t.currentDispatcher.scheduleTask(()=>{let t,a;if(qd(e)){let[r,i]=YM(e.cause);t=r,a=Ai(i)&&(t.status>=500||Ed(i.value))?Vd(i.value):jN(n,t)}else t=e.value,a=jN(n,t);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=bse(n);Ai(e)&&(!n.url.startsWith(`/`)&&(e.value.username!==``||e.value.password!==``)&&(e.value.username=`REDACTED`,e.value.password=`REDACTED`),ZA(i,e.value)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),QA(i,`request`,n.headers,s,o),Ai(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,t.status),QA(i,`response`,t.headers,s,o)}i.end(r,a)},0)}),e})),Ose=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return Zm(JM(n),([e,n])=>{let i=aw();fd(i,n);let a=kN.get(r.source),o=n.reasons.length===0?N(e):Tp(n);return a===void 0?(r[NN]=!0,Zm(t(r,e),()=>o)):Zm(Zm(a(r,e),e=>(r[NN]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=kN.get(e.source);return r===void 0?(e[NN]=!0,Jm(t(e,n),e=>$j(e)?e:n)):Zm(r(e,n),r=>(e[NN]=!0,Jm(t(e,r),e=>$j(e)?e:n)))},a=a=>{let o=a.request,s=Qp(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:Qp(MN(n(s)),{onFailure(e){return fd(aw(),e),NN in o?F:hre(JM(e),{onFailure(e){return t(o,eM({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return NN in o?F:t(o,e)}})},o=e=>MN(a(e)),s=(e,t,n)=>gm(n,n=>{if(t.setContext(e.prev),!(PN in e.scope))return Cf(e.scope,e.cause===void 0?n:Vd(e.cause))},!0);class c{scope;prev;request;cause;constructor(e,t,n){this.scope=e,this.prev=t,this.request=n}[dr](e,t){let n=i(this.request,e);if(Zc(n)&&n._tag===`Success`){if(t.setContext(this.prev),PN in this.scope)return n;let e=Cf(this.scope,n);return e===void 0?n:R(e,()=>n)}return s(this,t,n)}[fr](e,t){return s(this,t,r(this,e))}}return kp(t=>{ou(t);let r=gf(),i=new c(r,t.context,ca(t.context,DN));t.setContext(ra(i.prev,mf,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===rs||AN(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},NN=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),PN=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),kse=e=>DN.use(t=>(FN(t,e),F)),FN=xse,Ase=/*#__PURE__*/ O(2,(e,t)=>DN.use(n=>(FN(n,t),e))),IN=`~effect/http/HttpRouter`,LN=/*#__PURE__*/ j(`effect/http/HttpRouter`),jse=/*#__PURE__*/ I(function*(){let e=Uj(yield*Nse),t=/* @__PURE__ */ new Set,n=t=>tm(n=>{let r=XN(n),i=e=>{for(let t=0;t<r.length;t++)e=r[t](e);return e};for(let n=0;n<t.length;n++){let a=r.length===0?t[n]:HN({...t[n],handler:i(t[n].handler)});a.method===`*`?a.path.endsWith(`/*`)?(e.all(a.path,a),e.all(a.path.slice(0,-2),a)):e.all(a.path,a):a.path.endsWith(`/*`)?(e.on(a.method,a.path,a),e.on(a.method,a.path.slice(0,-2),a)):e.on(a.method,a.path,a)}return F});return LN.of({[IN]:IN,prefixed(e){return e=WN(e),LN.of({...this,prefixed:t=>this.prefixed(GN(t,e)),addAll:t=>n(t.map(Ise(e))),add:(t,r,i,a)=>n([HN({method:t,path:GN(r,e),handler:$j(i)?N(i):hp(i)?i:R(DN,i),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:n,add:(e,t,r,i)=>n([UN(e,t,r,i)]),addGlobalMiddleware:e=>P(()=>{t.add(e)}),asHttpEffect(){let n=kp(t=>{let n=t.context,r=ca(n,DN),i=e.find(r.method,r.url);if(i===void 0&&r.method===`HEAD`&&(i=e.find(`GET`,r.url)),i===void 0)return L(new VM({reason:new UM({request:r})}));let a=i.handler;if(Ai(a.prefix)&&(n=ra(n,DN,Mse(r,a.prefix.value))),n=ra(n,ON,i.searchParams),n=ra(n,RN,{route:a,params:i.params}),t.getRef(ns)!==rs){let e=oa(n,Yo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,a.path)}if(t.setContext(n),!a.uninterruptible){let e=su(t);if(e!==void 0)return e}return a.handler});if(t.size===0)return n;for(let e of Yee(t))n=e(n);return n}})});function Mse(e,t){let n=t.length;return e.modify({url:e.url.length<=n?`/`:e.url.slice(n)})}const Nse=/*#__PURE__*/ _a(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var RN=class extends (/*#__PURE__*/ j()(`effect/http/HttpRouter/RouteContext`)){};const zN=e=>Gf(R(LN,e)),BN=(e,t,n,r)=>zN(i=>i.add(e,t,n,r)),Pse=/*#__PURE__*/ Hf(LN)(jse),Fse=e=>tm(t=>{let n=la(t,mf),r=Ff.forkOrCreate(t);return z(If(Qf(e,Pse),r,n),e=>la(e,LN).asHttpEffect())}),VN=`~effect/http/HttpRouter/Route`,HN=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?Oi(e.prefix):e.prefix??Di(),[VN]:VN}),UN=(e,t,n,r)=>HN({...r,method:e,path:t,handler:$j(n)?N(n):hp(n)?n:R(DN,n),uninterruptible:r?.uninterruptible??!1}),WN=e=>e.endsWith(`/`)?e.slice(0,-1):e,GN=/*#__PURE__*/ O(2,(e,t)=>(t=WN(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),Ise=/*#__PURE__*/ O(2,(e,t)=>HN({...e,path:GN(e.path,t),prefix:ji(e.prefix,{onNone:()=>WN(t),onSome:e=>GN(e,t)})})),KN=function(){return arguments.length===0?qN:qN(arguments[0],arguments[1])},qN=(e,t)=>t?.global?Gf(I(function*(){let t=yield*LN,n=hp(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new Rse(hp(e)?Wf(z(e,e=>Xi(/* @__PURE__ */ new Map([[JN,e]])))):Bf(Xi(/* @__PURE__ */ new Map([[JN,e]]))));let Lse=0;const JN=`effect/http/HttpRouter/MiddlewareFn`;var Rse=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++Lse}`;this.layer=Wf(I({self:this},function*(){let e=yield*em(),t=[sa(e,JN)];if(this.dependencies){let n=yield*Ff,r=la(e,mf),i=yield*If(this.dependencies,n,r);t.push(...XN(i))}return Xi(/* @__PURE__ */ new Map([[n,t]]))})).pipe(Zf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?Qf(this.dependencies,t.layer):t.layer)}};const YN=/*#__PURE__*/ new WeakMap,XN=e=>{let t=YN.get(e);if(t)return t;let n=Ka(),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=Va(e).reverse()}return YN.set(e,t),t};(/*#__PURE__*/ KN(wse)).layer;var ZN=class extends (/*#__PURE__*/ j()(`effect/workers/Transferable/Collector`)){};const QN=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return ZN.of({addAllUnsafe:t,addAll:e=>P(()=>t(e)),readUnsafe:n,read:P(n),clearUnsafe:r,clear:P(r)})},$N=(e,t)=>e===void 0?t:`${e}.${t}`,eP=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),tP=`~effect/rpc/RpcSchema/StreamSchema`;function nP(e){return A(e,tP)}function rP(e){return nP(e)?Oi({success:e.success,error:e.error}):Di()}const zse=/*#__PURE__*/ tS(zE);function Bse(e,t){return mS(zse.ast,{[tP]:tP,success:e,error:t})}var Vse=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ ra(Rd,{name:`ClientAbort`,stack:Et,parent:void 0}))};const iP=`~effect/rpc/Rpc`;var aP=class{id;annotations;constructor(e){this.id=e,this.annotations=ea()}annotate(e,t){return this.annotations=ra(this.annotations,e,t),this}};const Hse={[iP]:iP,pipe(){return bt(this,arguments)},setSuccess(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return oP({_tag:this._tag,payloadSchema:hS(e)?e:U(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return oP({_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 oP({_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 oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ra(this.annotations,e,t)})},annotateMerge(e){return oP({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ma(this.annotations,e)})}},oP=e=>{function t(){}return Object.setPrototypeOf(t,Hse),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},sP=(e,t)=>{let n=t?.success??kS,r=t?.error??SS,i=t?.defect??SC(),a;return a=t?.primaryKey?class extends GC(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:hS(t?.payload)?t?.payload:t?.payload?U(t?.payload):kS,oP({_tag:e,payloadSchema:a,successSchema:t?.stream?Bse(n,r):n,errorSchema:t?.stream?SS:r,defectSchema:i,annotations:ea(),middlewares:/* @__PURE__ */ new Set})},cP=/*#__PURE__*/ new WeakMap,lP=e=>{if(cP.has(e))return cP.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=rP(t.successSchema);Ai(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=zC(Ai(r)?kS:t.successSchema,G([...n]),t.defectSchema);return cP.set(e,i),i},uP=e=>`~effect/rpc/Rpc/Wrapper`in e,dP=e=>e,Use={_tag:`Eof`},fP=e=>({_tag:`Defect`,defect:e}),Wse={_tag:`Pong`},Gse=JC;let Kse;const qse=e=>(Kse??=new TextDecoder).decode(e);var pP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcSerialization`)){};const mP=e=>pP.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:Gse,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>Jse(JSON.parse(typeof t==`string`?t:qse(t)),e),encode:t=>{let n=Yse(t,e);return n&&JSON.stringify(n)}}}});function Jse(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(!Jt(a))continue;let o=hP(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return Jt(e)?[hP(e)]:[]}function hP(e){if(Object.hasOwn(e,`method`)){let t=e;if(Gt(t.id)&&It(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??[],...A(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 gP(e,t){if(!(`requestId`in e))return _P(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(),_P):void 0):_P(e)}function Yse(e,t){if(Array.isArray(e)===!1)return gP(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=gP(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 _P(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&&A(n,`code`)?Number(n.code):0,message:n&&A(n,`message`)?n.message:JSON.stringify(e.exit.cause),data:e.exit.cause}:void 0}}case`Defect`:return{jsonrpc:`2.0`,id:Xse,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const Xse=-32603,Zse=e=>zf(pP)(mP(e)),Qse=()=>e=>Sp(()=>{let t=PT(1),n=[],r=(...e)=>tm(t=>(n.push([e,t]),F));return z(e((...e)=>r(...e)),e=>({...e,run(e){return t.withPermits(1)(I(function*(){let t=r;for(let[t,r]of n)yield*rm(Sp(()=>e(...t)),r);return n=[],r=e,yield*_m(wp,()=>(r=t,F))}))}}))}),$se=e=>Sp(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>tm(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),F});return z(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return I(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*rm(Sp(()=>i(e)),t)}return yield*_m(wp,()=>(t.delete(e),r.delete(e),F))})}}))});let ece=0;const vP=/*#__PURE__*/ B(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>ece++),o=yield*em(),s=la(o,mf),c=/* @__PURE__ */ new Map,l=!1;yield*yf(s,kp(e=>(l=!0,u(Wd(e.id)))));let u=B(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?sT(n.queue):aT(n.queue,e.cause):n.resume(e)}),d=e=>{let r=nP(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?Wg(s.headers):Ug,l=s?.context??ea();if(!r){let r=t=>f(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):Om($N(n,e._tag),{kind:`client`,attributes:eP(e._tag,t.spanAttributes)},r)}let u=p(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:YE(z(u,qE))}},f=(e,n,r,i,o,s,u)=>kp(d=>{if(l)return bm;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:Jg(d.getRef(yP),o)});if(u)return p;let m;return Sm(Cp(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?Am(r,{captureStackTrace:!1}):k,Fm(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),jp(iw(m),h(f,Array.from(e),s))))}),p=B(function*(e,r,o,s,u,d){if(l)return yield*bm;let f=i?void 0:yield*Dm($N(n,e._tag),{kind:`client`,attributes:eP(e._tag,t.spanAttributes)}),p=aw(),m=a(),g=ca(p.context,mf),_=yield*$w(u);return yield*vf(g,e=>(uT(_),c.has(m)?(c.delete(m),h(m,qd(e)?Array.from(Dd(e.cause)):[],d)):F)),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:Jg(p.getRef(yP),s)}).pipe(f?Am(f,{captureStackTrace:!1}):k,hm(e=>aT(_,e)),xm,Mm(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)=>Cp(i=>{let a=aw();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(dre(1e3),Fm(a.context)).addObserver(()=>{i(F)})}),g=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?F:rT(i.queue,e.values).pipe(r?R(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):k,zp(e=>aT(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),F):e.exit._tag===`Success`?sT(n.queue):aT(n.queue,e.exit.cause)):F}case`Defect`:return u(Ud(e.defect));case`ClientEnd`:return F}},_;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 tce=0;const nce=/*#__PURE__*/ B(function*(e,t){let n=tce++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*bP,c=rce(r),l=dae(r(SC())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):F,{client:f,write:p}=yield*vP(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?QN():void 0,o=aw(),l={rpc:r,context:i?ra(o.context,ZN,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(rm(l.context),Up,R(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}):F;case`Interrupt`:return d(t.requestId);case`Eof`:return F}}});return yield*i(n,e=>{switch(e._tag){case`Chunk`:{let t=dP(e.requestId),n=u.get(t);if(!n||ki(n.schemas.decodeChunk))return F;let r=n.schemas.decodeChunk.value;return wm(i=>i(r(e.values).pipe(rm(n.context),Up,R(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(hm(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Vd(e)}).pipe(jp(Ed(e)?F:Kp(d(t))))),lre(e=>!Ed(e),()=>F)))}case`Exit`:{let t=dP(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(rm(n.context),Up,Qp({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Vd(e)})}))):F}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=Hd(e.error);return _p(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return F}}).pipe(zp(Um),xm,Nm),f}),rce=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=rP(n.successSchema);return r={decodeChunk:Li(i,t=>sS(e(IS(t.success)))),encodePayload:dS(e(n.payloadSchema)),decodeExit:sS(e(lP(n)))},t.set(n,r),r}},yP=/*#__PURE__*/ _a(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Ug});var bP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcClient/Protocol`)){static make=$se};const ice=/*#__PURE__*/ B(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*em(),l=la(c,mf),u=ow(xf(l,`parallel`)),d=o===`unbounded`?void 0:yield*LT(o),f=/* @__PURE__ */ new Map,p=!1,m=sw(!1);yield*yf(l,kp(e=>{p=!0;for(let t of f.values()){if(t.ended=!0,t.fibers.size===0){u(Fm(c)(_(t)));continue}for(let n of t.fibers.values())n.interruptUnsafe(e.id)}return f.size===0?F:m.await}));let h=e=>kp(t=>{let n=f.get(e);if(!n)return F;for(let e of n.fibers.values())e.interruptUnsafe(t.id);return f.delete(e),F}),g=(e,n,r)=>Bp(kp(i=>{if(p)return bm;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new aP(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`||!a.fibers.has(n.requestId)))return bm;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?e.open:F}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,Vse.annotation),F):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:Wd()})}case`Eof`:return a.ended=!0,a.fibers.size>0?F:_(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?jp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return bm;let p=e.requests.get(l.tag),m=sa(c,p?.key);if(!p||!m){let e=Bp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Ud(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:mm(e,_(o))}let h=nP(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=uP(v),S=x&&v.fork,C=x&&v.uninterruptible,w=x?v.value:v,T=h?y(o,l,w):w,ee=p.middlewares.size>0?oce(c,T,g):T,te=!1,E=gf(),ne,re=_m(ee,e=>{te=!0;let n;e._tag===`Success`?Zd(e.value)?(ne=e.value,n=F):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}):n=!s&&Td(e.cause)&&!Ed(e.cause)?b(o,Sd(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=Cf(E,e);return e._tag===`Failure`&&fd(aw(),e.cause),r?mm(n,r):n});if(f?.onRequest&&(re=f.onRequest(re)),n){let e=oa(i.context,Yo);re=km(re,$N(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:eP(l.tag,t.spanAttributes),parent:r&&l.spanId?Zo({traceId:l.traceId,spanId:l.spanId,sampled:l.sampled}):void 0,links:r&&e?[{span:e,attributes:{}}]:void 0})}!S&&d&&(re=d.withPermit(re));let ie=Fm(ra(ace(m,i.context),mf,E));return u(ie(kp(e=>(o.fibers.set(l.id,e),re)),C?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ne){let n=u(ie(_m(nf(ne),e=>t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}))));o.fibers.set(l.id,n),ne=void 0,n.addObserver(e);return}!te&&n._tag===`Failure`&&u(ie(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Wd()}))),o.fibers.delete(l.id),o.latches?.delete(l.id),o.ended&&o.fibers.size===0&&u(ie(_(o)))}),F},y=(e,n,r)=>{let a;return i&&(e.latches??=/* @__PURE__ */ new Map,a=e.latches.get(n.id),a||(a=sw(!1),e.latches.set(n.id,a))),hp(r)?r.pipe(R(r=>vp({while:wt,body:Ct(R(dT(r),r=>{let i=t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r});return a?(a.closeUnsafe(),R(i,()=>a.await)):i})),step:Dt})),up(()=>F),um):nD(r,r=>{let i=t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r});return a?(a.closeUnsafe(),jp(i,a.await)):i})},b=(e,n)=>Sp(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?jp(i,_(e)):i});return k({write:g,disconnect:h})}),xP=/*#__PURE__*/ new WeakMap,ace=(e,t)=>{let n=xP.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,xP.set(e,n));let r=n.get(t);return r===void 0&&(r=ma(e.context,t),n.set(t,r)),r},oce=(e,t,n)=>{for(let r of n.rpc.middlewares)t=ca(e,r)(t,n);return t},sce=/*#__PURE__*/ B(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*SP,u=pS(n(SC())),d=uS(n(zC(SS,SS,SC()))),f=yield*em(),p=yield*hf(),m=yield*ice(e,{...t,disableClientAcks:!s,disableSpanPropagation:!c,onFromServer(e){let t=_.get(e.clientId);if(!t)return F;switch(e._tag){case`Chunk`:{let n=t.schemas.get(e.requestId);return n?y(t,e.requestId,n,n.encodeChunk(e.values),`Chunk`):F}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`)):F}case`Defect`:return x(t,e.defect);case`ClientEnd`:return _.delete(e.clientId),i(e.clientId)}}}).pipe(_f(p));yield*jm(vp({while:wt,body:Ct(R(mT(r),e=>(_.delete(e),m.disconnect(e)))),step:Dt}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=sa(f,e.key),i=rP(e.successSchema);t={decode:sS(n(e.payloadSchema)),encodeChunk:uS(n(IS(Ai(i)?i.value.success:CS))),encodeExit:uS(n(lP(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=zd(r)&&Kd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):R(rm(a?cm(r,ZN,a):r,n.context),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return zp(s,r=>{e.schemas.delete(t);let i=Sd(bd(r,e=>iv(e.issue)));return jp(b(e,t,n.encodeExit,i),m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))})},b=(e,t,n,r)=>zp(R(n(Ud(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,Sd(t))),x=(e,t)=>zp(o(e.id,fP(u(t))),e=>Km(Gm(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:QN()}:n);let a=r;return a.id=t,a.payload=i,a.headers=Wg(r.headers),m.write(e.id,a)};return yield*a((t,n)=>{let r=_.get(t);switch(r||(r={id:t,schemas:/* @__PURE__ */ new Map},_.set(t,r)),n._tag){case`Request`:{let t=Object.hasOwn(n,`tag`)?n.tag:``,i;switch(typeof n.id){case`number`:case`string`:i=dP(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 zd(s)&&Kd(s)?S(r,i,o,n,s.value):$p(rm(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,iv(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return zp(o(r.id,Wse),e=>x(r,Sd(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:dP(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(Gp(e=>Vm(`BUG: RpcServer protocol crashed`,e)),_m(e=>Sf(p,e)))});var SP=class extends (/*#__PURE__*/ j()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ Qse()};const cce=/*#__PURE__*/ B(function*(e={}){let t=yield*pP,n=pS(t.codecFor(SC())),r=t.includesFraming,i=!t.contentType.includes(`json`),a=yield*Qw(),o,s=0,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=new TextEncoder,d=I(function*(){let d=aw(),f=ca(d.context,DN),p=ca(d.context,mf),m=Object.entries(f.headers),h=yield*Up(i?z(f.arrayBuffer,e=>new Uint8Array(e)):f.text),g=s++,_=yield*Qw({capacity:r&&e.streamBufferSize!==`unbounded`?e.streamBufferSize??16:void 0}),v=t.makeUnsafe(),y=[],b=e=>typeof e==`string`?tT(_,u.encode(e)):tT(_,e),x={write:r?e=>{try{let t=v.encode(e);return t===void 0?F:b(t)}catch(e){return b(v.encode(fP(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?F:tT(_,e),end:sT(_)};yield*vf(p,()=>(c.delete(g),l.delete(g),nT(a,g),_.state._tag===`Done`?F:jp(lT(_),_p(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(dP(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(fP(n(e)))}if(yield*o(g,Use),!r){let e=yield*fT(_),n=v.encode(e);return iM(n===void 0?``:n,{contentType:t.contentType})}let S=yield*up(dT(_),()=>N([]));return _.state._tag===`Done`?nM(lce(S),{contentType:t.contentType}):lM(_oe(S).pipe(boe(qE(_))),{contentType:t.contentType})});return{protocol:yield*SP.make(e=>(o=e,N({disconnects:a,send(e,t){let n=c.get(e);return n?n.write(t):F},end(e){let t=c.get(e);return t?t.end:F},clientIds:P(()=>l),initialMessage:xp,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),lce=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},uce={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return CP({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 CP({requests:t,annotations:Xi(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return CP({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 CP({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return I(function*(){let n=yield*em(),r=hp(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})}),Xi(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 CP({requests:t,annotations:this.annotations})},toLayer(e){return Wf(this.toHandlers(e))},of:k,toLayerHandler(e,t){let n=this;return Wf(I(function*(){let r=yield*em(),i=hp(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),Xi(a)}))},accessHandler(e){return tm(t=>{let n=this.requests.get(e),{handler:r,context:i}=sa(t,n.key);return N((e,t)=>{t.rpc=n;let a=r(e,t),o=uP(a)?a.value:a;return hp(o)?nm(o,i):eD(o,i)})})},annotate(e,t){return CP({requests:this.requests,annotations:ra(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(na(e,t))},annotateMerge(e){return CP({requests:this.requests,annotations:ma(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(ma(e,r.annotations)));return CP({requests:t,annotations:this.annotations})}},CP=e=>Object.assign(function(){},uce,{requests:e.requests,annotations:e.annotations}),wP=(...e)=>CP({requests:new Map(e.map(e=>[e._tag,e])),annotations:ea()}),dce=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},fce=/* @__PURE__ */ zf($D,/* @__PURE__ */ eO({randomBytes:Je.randomBytes,digest:(e,t)=>Op({try:()=>Uint8Array.from(Je.createHash(dce(e)).update(t).digest()),catch:e=>CE({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),TP=e=>t=>wE({module:`FileSystem`,method:e,description:t.message??String(t)}),EP=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},DP=e=>Ri(Ni(e),yh),OP=(e,t)=>Op({try:()=>EP(e,`position`),catch:TP(t)}),pce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.access,/*#__PURE__*/ _k(`FileSystem`,`access`),/*#__PURE__*/ TP(`access`));return(t,n)=>{let r=ut.constants.F_OK;return n?.readable&&(r|=ut.constants.R_OK),n?.writable&&(r|=ut.constants.W_OK),e(t,r)}})(),mce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.cp,/*#__PURE__*/ _k(`FileSystem`,`copy`),/*#__PURE__*/ TP(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),hce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.copyFile,/*#__PURE__*/ _k(`FileSystem`,`copyFile`),/*#__PURE__*/ TP(`copyFile`));return(t,n)=>e(t,n)})(),gce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.chmod,/*#__PURE__*/ _k(`FileSystem`,`chmod`),/*#__PURE__*/ TP(`chmod`));return(t,n)=>e(t,n)})(),_ce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.chown,/*#__PURE__*/ _k(`FileSystem`,`chown`),/*#__PURE__*/ TP(`chown`));return(t,n,r)=>e(t,n,r)})(),vce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.glob,/*#__PURE__*/ _k(`FileSystem`,`glob`),/*#__PURE__*/ TP(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),yce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.link,/*#__PURE__*/ _k(`FileSystem`,`link`),/*#__PURE__*/ TP(`link`));return(t,n)=>e(t,n)})(),bce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.mkdir,/*#__PURE__*/ _k(`FileSystem`,`makeDirectory`),/*#__PURE__*/ TP(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),kP=e=>{let t=qm(ut.mkdtemp,_k(`FileSystem`,e),TP(e));return e=>Sp(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?Xe.join(e.directory,`.`):pt.tmpdir();return t(n?Xe.join(r,n):r+`/`)})},xce=/*#__PURE__*/ kP(`makeTempDirectory`),AP=e=>{let t=qm(ut.rm,_k(`FileSystem`,e),TP(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},Sce=/*#__PURE__*/ AP(`remove`),Cce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ kP(`makeTempDirectoryScoped`),t=/*#__PURE__*/ AP(`makeTempDirectoryScoped`);return n=>fm(e(n),e=>Up(t(e,{recursive:!0})))})(),wce=/*#__PURE__*/ (e=>{let t=qm(ut.open,_k(`FileSystem`,e),TP(e)),n=qm(ut.close,_k(`FileSystem`,e),TP(e));return(e,r)=>Ot(fm(t(e,r?.flag??`r`,r?.mode),e=>Up(n(e))),z(e=>Tce(e,r?.flag?.startsWith(`a`)??!1)))})(`open`),Tce=/*#__PURE__*/ (()=>{let e=e=>qm(ut.read,_k(`FileSystem`,e),TP(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ qm(ut.fstat,/*#__PURE__*/ _k(`FileSystem`,`stat`),/*#__PURE__*/ TP(`stat`)),i=/*#__PURE__*/ qm(ut.ftruncate,/*#__PURE__*/ _k(`FileSystem`,`truncate`),/*#__PURE__*/ TP(`truncate`)),a=/*#__PURE__*/ qm(ut.fsync,/*#__PURE__*/ _k(`FileSystem`,`sync`),/*#__PURE__*/ TP(`sync`)),o=e=>qm(ut.write,_k(`FileSystem`,e),TP(e)),s=/*#__PURE__*/ o(`write`),c=/*#__PURE__*/ o(`writeAll`);class l{[oD];fd;append;position=/*#__PURE__*/ BigInt(0);constructor(e,t){this[oD]=oD,this.fd=e,this.append=t}get stat(){return R(r(this.fd,{bigint:!0}),MP)}get sync(){return a(this.fd)}seek(e,t){return Sp(()=>{let n=t===`start`?e:this.position+e;return n<BigInt(0)?L(wE({module:`FileSystem`,method:`seek`,description:`Cannot seek before the start of the file`})):(this.position=n,N(n))})}read(e){return Sp(()=>{let n=this.position;return z(t(this.fd,{buffer:e,position:n}),e=>(this.position=n+BigInt(e),e))})}readAlloc(e){return Sp(()=>{try{if(!Number.isInteger(e)||e<0)throw RangeError(`size must be a non-negative integer`);let t=Buffer.allocUnsafeSlow(e),r=this.position;return z(n(this.fd,{buffer:t,position:r}),n=>{if(n===0)return Di();if(this.position=r+BigInt(n),n===e)return Oi(t);let i=Buffer.allocUnsafeSlow(n);return t.copy(i,0,0,n),Oi(i)})}catch(e){return L(TP(`readAlloc`)(e))}})}truncate(e){return z(i(this.fd,e||void 0),()=>{if(!this.append){let t=BigInt(e??0);this.position>t&&(this.position=t)}})}write(e){return Sp(()=>{let t=this.position;return R(this.append?N(void 0):OP(t,`write`),n=>z(s(this.fd,e,void 0,void 0,n),e=>(this.append||(this.position=t+BigInt(e)),e)))})}writeAllChunk(e){return Sp(()=>{let t=this.position;return R(this.append?N(void 0):OP(t,`writeAll`),n=>R(c(this.fd,e,void 0,void 0,n),n=>n===0?L(CE({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)):F)))})}writeAll(e){return e.length===0?F:this.writeAllChunk(e)}}return(e,t)=>new l(e,t)})(),jP=e=>{let t=kP(e);return B(function*(e){let n=yield*t(e),r=Je.randomBytes(6).toString(`hex`),i=Xe.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*PP(i,/* @__PURE__ */ new Uint8Array),i})},Ece=/*#__PURE__*/ jP(`makeTempFile`),Dce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ jP(`makeTempFileScoped`),t=/*#__PURE__*/ AP(`makeTempFileScoped`);return n=>fm(e(n),e=>Up(t(Xe.dirname(e),{recursive:!0})))})(),Oce=(e,t)=>bp({try:()=>ut.promises.readdir(e,t),catch:t=>_k(`FileSystem`,`readDirectory`)(t,[e])}),kce=e=>Cp((t,n)=>{try{ut.readFile(e,{signal:n},(n,r)=>{t(n?L(_k(`FileSystem`,`readFile`)(n,[e])):N(r))})}catch(e){t(L(TP(`readFile`)(e)))}}),Ace=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.readlink,/*#__PURE__*/ _k(`FileSystem`,`readLink`),/*#__PURE__*/ TP(`readLink`));return t=>e(t)})(),jce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.realpath,/*#__PURE__*/ _k(`FileSystem`,`realPath`),/*#__PURE__*/ TP(`realPath`));return t=>e(t)})(),Mce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.rename,/*#__PURE__*/ _k(`FileSystem`,`rename`),/*#__PURE__*/ TP(`rename`));return(t,n)=>e(t,n)})(),MP=e=>Op({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:Ni(e.mtime),atime:Ni(e.atime),birthtime:Ni(e.birthtime),dev:EP(e.dev,`dev`),rdev:DP(e.rdev),ino:DP(e.ino),mode:EP(e.mode,`mode`),nlink:DP(e.nlink),uid:DP(e.uid),gid:DP(e.gid),size:Lh(e.size),blksize:e.blksize===void 0?Di():Oi(Lh(e.blksize)),blocks:DP(e.blocks)}),catch:TP(`stat`)}),NP=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.stat,/*#__PURE__*/ _k(`FileSystem`,`stat`),/*#__PURE__*/ TP(`stat`));return t=>R(e(t,{bigint:!0}),MP)})(),Nce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.symlink,/*#__PURE__*/ _k(`FileSystem`,`symlink`),/*#__PURE__*/ TP(`symlink`));return(t,n)=>e(t,n)})(),Pce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.truncate,/*#__PURE__*/ _k(`FileSystem`,`truncate`),/*#__PURE__*/ TP(`truncate`));return(t,n)=>e(t,n)})(),Fce=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ qm(ut.utimes,/*#__PURE__*/ _k(`FileSystem`,`utime`),/*#__PURE__*/ TP(`utime`));return(t,n,r)=>e(t,n,r)})(),Ice=(e,t,n)=>poe(r=>fm(P(()=>{let i=t.type===`Directory`?e:Xe.dirname(e),a=ut.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:Pm($p(NP(Xe.resolve(i,t)),{onSuccess:e=>tT(r,{_tag:`Create`,path:t}),onFailure:e=>tT(r,{_tag:`Remove`,path:t})}));return;case`change`:nT(r,{_tag:`Update`,path:t});return}});return a.on(`error`,t=>{oT(r,hd(CE({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{cT(r)}),a}),e=>P(()=>e.close()))),Lce=(e,t,n)=>NP(t).pipe(z(r=>e.pipe(Ri(e=>e.register(t,r,n)),Mi(()=>Ice(t,r,n)))),YE),PP=(e,t,n)=>Cp((r,i)=>{try{ut.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?L(_k(`FileSystem`,`writeFile`)(t,[e])):F)})}catch(e){r(L(TP(`writeFile`)(e)))}}),Rce=/*#__PURE__*/ z(/*#__PURE__*/ om(zoe),e=>Roe({access:pce,chmod:gce,chown:_ce,copy:mce,copyFile:hce,glob:vce,link:yce,makeDirectory:bce,makeTempDirectory:xce,makeTempDirectoryScoped:Cce,makeTempFile:Ece,makeTempFileScoped:Dce,open:wce,readDirectory:Oce,readFile:kce,readLink:Ace,realPath:jce,remove:Sce,rename:Mce,stat:NP,symlink:Nce,truncate:Pce,utimes:Fce,watch(t,n){return Lce(e,t,n)},writeFile:PP})),FP=/* @__PURE__ */ Hf(aD)(Rce);var zce=class extends Qn{[IA];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[IA]=IA,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return Wg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??Ni(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=z(this.arrayBuffer,e=>Buffer.from(e).toString(`utf8`)),this.textEffect}get textUnsafe(){return Rm(this.text)}get json(){return R(this.text,e=>Op({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return Rm(this.json)}get urlParamsBody(){return R(this.text,e=>Op({try:()=>i_(new URLSearchParams(e)),catch:this.onError}))}get stream(){return xk({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect?this.arrayBufferEffect:(this.arrayBufferEffect=kp(e=>Tk(()=>this.source,{onError:this.onError,maxBytes:e.getRef(RA)})).pipe(vm,Rm),this.textEffect=z(this.arrayBufferEffect,e=>new TextDecoder().decode(e)),this.arrayBufferEffect)}};const IP=/*#__PURE__*/ _a(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var LP=class extends (/*#__PURE__*/ j()(`effect/http/FetchHttpClient/RequestInit`)){};const RP=/*#__PURE__*/ fj(/*#__PURE__*/ N(/* @__PURE__ */ aj((e,t,n,r)=>{let i=r.getRef(IP),a=oa(r.context,LP)??{},o=a.headers?Jg(Wg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=Yg(o,`content-length`));let s=r=>z(bp({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 nA({reason:new aA({request:e,cause:t})})}),t=>VA(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 R(Loe(e.body.stream),s)}return s(void 0)}))),Bce=/*#__PURE__*/ new Set(typeof ht.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),zP=(e,t)=>{let n={};return e!==void 0&&(n[ht.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[ht.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},BP=e=>e===void 0||e===3?void 0:{params:{[ht.constants.ZSTD_c_compressionLevel]:e}},Vce=(e,t,n)=>Cp(r=>{let i=(e,t)=>r(e===null?N(t):Dp(e));switch(t){case`gzip`:ht.gzip(e,{level:n?.level},i);break;case`deflate`:ht.deflate(e,{level:n?.level},i);break;case`br`:ht.brotliCompress(e,zP(n?.level,e.byteLength),i);break;case`zstd`:{let t=BP(n?.level);t===void 0?ht.zstdCompress(e,i):ht.zstdCompress(e,t,i);break}}}),Hce=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?z(Vce(i.body,n,r),e=>uM(hM(t,Gk(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),VP=(e,t)=>{switch(e){case`gzip`:return ht.createGzip({level:t?.level,flush:ht.constants.Z_SYNC_FLUSH});case`deflate`:return ht.createDeflate({level:t?.level,flush:ht.constants.Z_SYNC_FLUSH});case`br`:return ht.createBrotliCompress({...zP(t?.level),flush:ht.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return ht.createZstdCompress({...BP(t?.level),flush:ht.constants.ZSTD_e_flush})}},HP=(e,t)=>{let n;return new at({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)}})},UP=(e,t)=>dM(hM(e,t),`content-length`),Uce=/*#__PURE__*/ AM({platform:`node`,compression:/* @__PURE__ */ Hce({algorithms:Bce,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return N(UP(e,eA(wk(r.stream,{evaluate:()=>VP(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof at?r.body:void 0,a=HP(()=>{let e=VP(t,n);return i??=at.fromWeb(new Response(r.body).body),ot(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return N(UP(e,Uk(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return N(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=HP(()=>o===BigInt(0)?at.from([]):ut.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return cM(s,{headers:{...r,"content-type":r[`content-type`]??Mi(OM(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return cM(HP(()=>at.fromWeb(e.stream())),{headers:Jg(r,Gg({"content-type":r[`content-type`]??(e.type===``?Mi(OM(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),Wce=/*#__PURE__*/ Ot(/*#__PURE__*/ Hf(kM)(Uce),/*#__PURE__*/ Zf(FP),/*#__PURE__*/ Zf(Jj));var Gce=class extends rt{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=ase({...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 qce(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 Kce=e=>new Gce(e);var qce=class extends at{_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 WP=(e,t)=>fse(t).pipe(z(t=>xk({evaluate(){let n=Kce(t);return e.pipe(n),n},onError:e=>Qce(e)})),YE,XE(Yce)),Jce=(e,t)=>hse(WP(e,t),(e,t)=>bp({try:n=>dee.pipeline(t.file,ut.createWriteStream(e),{signal:n}),catch:e=>bN.fromReason(`InternalError`,e)})),Yce=e=>e._tag===`Field`?new Xce(e.info,e.value):new Zce(e);var GP=class extends Qn{[vN];constructor(){super(),this[vN]=vN}},Xce=class extends GP{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=sse(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Zce=class extends GP{_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=xk({evaluate:()=>e,onError:e=>bN.fromReason(`InternalError`,e)}),this.contentEffect=Ek(()=>e,{onError:e=>bN.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Qce(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return bN.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return bN.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return bN.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return bN.fromReason(`BodyTooLarge`,e)}default:return bN.fromReason(`Parse`,e)}}const KP=e=>({fromFileUrl:t=>Op({try:()=>et.fileURLToPath(t,{windows:e}),catch:e=>new xE({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>Op({try:()=>et.pathToFileURL(t,{windows:e}),catch:e=>new xE({module:`Path`,method:`toFileUrl`,cause:e})})});({...Xe.posix,.../*#__PURE__*/ KP(!1)}),{...Xe.win32,.../*#__PURE__*/ KP(!0)};const $ce=/* @__PURE__ */ zf(cD)({[sD]:sD,...Xe,.../*#__PURE__*/ KP(void 0)}),ele=/* @__PURE__ */ zf(HO,/*#__PURE__*/ UO({args:/*#__PURE__*/ P(()=>process.argv.slice(2)),stdinIsTerminal:/*#__PURE__*/ P(()=>process.stdin.isTTY===!0),stdoutIsTerminal:/*#__PURE__*/ P(()=>process.stdout.isTTY===!0),stdout:e=>vk({evaluate:()=>process.stdout,onError:e=>CE({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>vk({evaluate:()=>process.stderr,onError:e=>CE({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ xk({evaluate:()=>process.stdin,onError:e=>CE({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),tle=/*#__PURE__*/ Hf(qO,/*#__PURE__*/ (/* @__PURE__ */ B(function*(e=qP){let t=process.stdin,n=process.stdout,r=yield*Qw(),i=t.readableEnded,a=!1,o=()=>{i=!0,a||cT(r)};t.once(`end`,o),yield*pm(()=>P(()=>t.off(`end`,o)));let s=yield*doe({acquire:fm(P(()=>{let e=gt.createInterface({input:t,escapeCodeTimeout:50}),n=e=>nT(r,e),i=()=>{a=!1,cT(r)};return a=!0,gt.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})=>P(()=>{a=!1,e.off(`line`,o),e.off(`close`,n),t.isTTY&&t.setRawMode(!1),e.close(),i&&cT(r)})),idleTimeToLive:`10 millis`}),c=P(()=>n.columns??0),l=P(()=>n.rows??0),u=I(function*(){let n=yield*Qw(),r=(t,r)=>{let i={input:Pi(t),key:{name:r.name??``,ctrl:!!r.ctrl,meta:!!r.meta,shift:!!r.shift}};nT(n,i),e(i)&&cT(n)},a=setInterval(()=>{},2147483647),o=()=>{clearInterval(a),cT(n)};return yield*pm(()=>P(()=>{clearInterval(a),t.off(`keypress`,r),t.off(`end`,o)})),t.on(`keypress`,r),i?o():(yield*RE(s),t.once(`end`,o)),n}),d=Sp(()=>hT(r).pipe(R(ji({onNone:()=>um(jp(RE(s),mT(r))),onSome:N})),Hp(()=>new KO({}))));return JO({columns:c,rows:l,readInput:u,readLine:d,display:e=>Cm(Cp(t=>{n.write(e,e=>Gt(e)?t(F):t(L(wE({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(qP));function qP(e){return e.key.ctrl&&(e.key.name===`c`||e.key.name===`d`)}const nle=/*#__PURE__*/ Qf(Fk,/*#__PURE__*/ Yf(FP,fce,$ce,ele,tle)),rle=(e,t)=>{let n=Ose(e,sle,t.middleware);return kp(e=>{let r=e.context;return N(function(i,a){let o=ra(r,DN,new ile(i,a)),s=ow(Fm(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,KM.annotation)})})})};var ile=class e extends zce{[EN];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new VM({reason:new HM({request:this,cause:e})}),a),this[EN]=EN,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=kg(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||=Rm(vm(Jce(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return WP(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??L(new VM({reason:new HM({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${this.url})`}toJSON(){return zA(this,{_id:`HttpServerRequest`,method:this.method,url:this.originalUrl})}};const ale=/*#__PURE__*/ Yf(Wce,Yj,nle),ole=/*#__PURE__*/ eM({status:101}),sle=(e,t)=>{if(e.upgraded)return N(ole);let n=e.resolvedResponse;if(n.writableEnded)return F;let r=t.headers;if(!hg(t.cookies)){r={...r};let e=Og(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),jp(cle(t.body),Cp(e=>{let t=!1,r=()=>{t||(t=!0,n.off(`close`,r),e(F))};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(),F;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`?bp({try:e=>fee(i.body,n,{signal:e,end:!0}),catch:n=>new VM({reason:new GM({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(xm,Gp(JP(n,t))):Cp(e=>{n.end(i.body,()=>e(F))});case`Uint8Array`:return n.writeHead(t.status,t.statusText,r),i.contentLength<1048576?(n.end(i.text??i.body),F):Cp(e=>{n.end(i.text??i.body,()=>e(F))});case`FormData`:return Sp(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),Cp((r,i)=>{at.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(L(new VM({reason:new GM({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(F)})}).pipe(xm,Gp(JP(n,t)))});case`Stream`:{n.writeHead(t.status,t.statusText,r);let e=sw();return n.on(`drain`,()=>e.openUnsafe()),i.stream.pipe(Toe,nD(t=>{let r=t.length>1?Buffer.concat(t):t[0];return n.write(r)?F:(e.closeUnsafe(),e.await)}),xm,Qp({onSuccess:()=>P(()=>n.end()),onFailure:JP(n,t)}))}}},cle=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof at?P(()=>t.destroy()):F},JP=(e,t)=>n=>R(JM(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),Tp(a?xd(n,gd(t)):i)}),lle={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},ule=e=>lle[e];function YP(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const q=YP({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`});function XP(){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`)}const ZP={name:`HMAC`,hash:`SHA-256`},QP=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await XP().importKey(`raw`,t,ZP,!1,[`sign`,`verify`])},dle=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 XP().verify(ZP,n,i,new TextEncoder().encode(t))}catch{return!1}},fle=async(e,t)=>{let n=await QP(t),r=await XP().sign(ZP.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},ple=async(e,t)=>{let n=await fle(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},mle=/^application\/([a-z0-9.+-]*\+)?json/i;async function hle(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 d(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new d(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(mle.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new d(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 $P(e){return e instanceof d||e?.name===`APIError`}function gle(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function _le(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function eF(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const tF=(e,t)=>{let n=e;if(t){if(t===`secure`)n=`__Secure-`+e;else if(t===`host`)n=`__Host-`+e;else return}return n};function vle(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,gle(n))}n=i+1}return t}const nF=(e,t,n={})=>{let r;if(r=n?.prefix===`secure`?`${`__Secure-${e}`}=${t}`:n?.prefix===`host`?`${`__Host-${e}`}=${t}`:`${e}=${t}`,e.startsWith(`__Secure-`)&&!n.secure&&(n.secure=!0),e.startsWith(`__Host-`)&&(n.secure||=!0,n.path!==`/`&&(n.path=`/`),n.domain&&=void 0),n&&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&&n.prefix!==`host`&&(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&&(n.secure||=!0,r+=`; Partitioned`),r},rF=(e,t,n)=>(t=encodeURIComponent(t),nF(e,t,n)),iF=async(e,t,n,r)=>(t=await ple(t,n),nF(e,t,r));async function yle(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:aF(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:aF(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 aF(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 oF=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:s}=await yle(t,e);if(s)throw new o(s.message,s.issues);let c=`headers`in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):`request`in e&&eF(e.request)?e.request.headers:null,l=c?.get(`cookie`),u=l?vle(l):void 0,f={...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=>c?c.get(e):null,getCookie:(e,t)=>{let n=tF(e,t);return n&&u?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=tF(e,n);if(!r)return null;let i=u?.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 dle(s,o,await QP(t))?o:!1},setCookie:(e,t,n)=>{let i=rF(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await iF(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new d(`FOUND`,void 0,r)),error:(e,t,n)=>new d(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({...f,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(f.context,t.response),t.headers&&t.headers.forEach((e,t)=>{f.responseHeaders.set(t,e)})}return f};function ble(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 xle(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 Sle(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const Cle=/* @__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 sF(e){for(let t of Cle)e.delete(t)}function cF(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 lF(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);sF(n),cF(e.headers,n)}return e}if(Sle(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(cF(i,r?.headers),cF(i,e.headers),t?.headers){let e=new Headers(t.headers);sF(e),cF(i,e)}return i.set(`Content-Type`,`application/json`),new Response(JSON.stringify(n),{...r,headers:i,status:e.status??t?.status??r?.status,statusText:t?.statusText??r?.statusText})}if($P(e))return lF(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 sF(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`)):ble(e)&&(n=xle(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 uF(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,s=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new a(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new a(`Path cannot contain consecutive slashes`);let c=async(...e)=>{let t=e[0]||{},{data:n,error:a}=await _le(oF(t,{options:i,path:r}));if(a)throw a instanceof o?(i.onValidationError&&await i.onValidationError({message:a.message,issues:a.issues}),new d(400,{message:a.message,code:`VALIDATION_ERROR`})):a;let c=await s(n).catch(async e=>{if($P(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),l=n.responseHeaders,u=n.responseStatus;return t.asResponse?lF(c,{headers:l,status:u}):t.returnHeaders?t.returnStatus?{headers:l,response:c,status:u}:{headers:l,response:c}:t.returnStatus?{response:c,status:u}:c};return c.options=i,c.path=r,c}function dF(e,t){return[...e??[],...t??[]]}uF.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return uF(n,{...r,use:dF(r.use,e?.use)},i)}let[n,r]=t;return uF({...n,use:dF(n.use,e?.use)},r)}return t};function fF(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await oF(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 $P(e)&&Object.defineProperty(e,s,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}fF.create=e=>{function t(t,n){if(typeof t==`function`)return fF({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return fF({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};function pF(e){return u(h,e)}function mF(e){return r(te,e)}function hF(e){return i(ae,e)}const gF={};function _F(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 vF(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof re&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof re&&t.push({name:e,in:`query`,schema:{type:_F(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function wle(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof re||e.body instanceof S)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof re&&(n[e]={type:_F(t),description:t.description},t instanceof S||r.push(e))}),{required:e.body instanceof S?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function yF(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 Tle(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(gF[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:vF(n),responses:yF(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=wle(n);gF[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:vF(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:yF(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:gF}}const Ele=(e,t)=>`<!doctype html>
|
|
24
24
|
<html>
|
|
25
25
|
<head>
|
|
26
26
|
<title>Scalar API Reference</title>
|
|
@@ -410,11 +410,11 @@ To resolve this, you can:
|
|
|
410
410
|
1. Use only one of the conflicting plugins
|
|
411
411
|
2. Configure the plugins to use different paths (if supported)
|
|
412
412
|
3. Ensure plugins use different HTTP methods for the same path
|
|
413
|
-
`)}}function HJ(e,t){let n=Ce(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:BJ({signInSocial:mJ(),callbackOAuth:Qq,getSession:uH(),signOut:vJ,signUpEmail:bJ(),signInEmail:hJ(),resetPassword:dJ,verifyPassword:fJ,verifyEmail:LW,sendVerificationEmail:IW,changeEmail:kJ,changePassword:TJ,setPassword:EJ,updateSession:SJ(),updateUser:wJ(),deleteUser:DJ,requestPasswordReset:lJ,requestPasswordResetCallback:uJ,listSessions:_H(),revokeSession:vH,revokeSessions:yH,revokeOtherSessions:bH,linkSocialAccount:Bq,listUserAccounts:zq,deleteUserCallback:OJ,unlinkAccount:Vq,refreshToken:Jq,getAccessToken:qq,accountInfo:Yq,...r,ok:nJ,error:tJ},e),middlewares:i}}const UJ=(e,t)=>{let n=Ce(t),{api:r,middlewares:i}=HJ(e,t),a=new URL(e.baseURL).pathname;return Ble(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:lue},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=nI(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 Due(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[OH]:`onRequest`,[kH]:`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}`,{[OH]:`onResponse`,[kH]:`plugin:${r.id}`,[he]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},onError(n){if(jF(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?xe: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}jF(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)}}})},WJ=e=>H.pipe(
|
|
413
|
+
`)}}function HJ(e,t){let n=Ce(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:BJ({signInSocial:mJ(),callbackOAuth:Qq,getSession:uH(),signOut:vJ,signUpEmail:bJ(),signInEmail:hJ(),resetPassword:dJ,verifyPassword:fJ,verifyEmail:LW,sendVerificationEmail:IW,changeEmail:kJ,changePassword:TJ,setPassword:EJ,updateSession:SJ(),updateUser:wJ(),deleteUser:DJ,requestPasswordReset:lJ,requestPasswordResetCallback:uJ,listSessions:_H(),revokeSession:vH,revokeSessions:yH,revokeOtherSessions:bH,linkSocialAccount:Bq,listUserAccounts:zq,deleteUserCallback:OJ,unlinkAccount:Vq,refreshToken:Jq,getAccessToken:qq,accountInfo:Yq,...r,ok:nJ,error:tJ},e),middlewares:i}}const UJ=(e,t)=>{let n=Ce(t),{api:r,middlewares:i}=HJ(e,t),a=new URL(e.baseURL).pathname;return Ble(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:lue},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=nI(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 Due(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[OH]:`onRequest`,[kH]:`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}`,{[OH]:`onResponse`,[kH]:`plugin:${r.id}`,[he]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},onError(n){if(jF(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?xe: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}jF(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)}}})},WJ=e=>H.pipe(qS(N(e))),GJ={InvalidInput:400,Unauthenticated:401,Forbidden:403},KJ=U({path:W(G([H,rC])),message:H}),qJ=Z_();var JJ=class e extends qC()(`InvalidInput`,{message:WJ(`The input does not match the action's input.`),issues:W(KJ).pipe(qS(N([])))},{httpApiStatus:GJ.InvalidInput}){static fromSchemaError=({issue:t,message:n})=>new e({message:n,issues:qJ(t).issues.map(e=>({path:(e.path??[]).map(e=>{let t=Bt(e)?e:e.key;return zt(t)?String(t):t}),message:e.message}))})},YJ=class extends qC()(`Unauthenticated`,{message:WJ(`Authentication is required.`)},{httpApiStatus:GJ.Unauthenticated}){};const XJ=/^[\x21\x23-\x5B\x5D-\x7E]+$/,ZJ=H.check(nC(XJ));var QJ=class extends qC()(`Forbidden`,{message:WJ(`Not allowed.`),scopes:gS(IS(ZJ))},{httpApiStatus:GJ.Forbidden}){};const $J=[YJ,QJ],eY=G($J),tY=[JJ,...$J];G(tY);const nY=e=>e===void 0?[]:hS(e)?[e]:e,rY=(e,t=[])=>[.../* @__PURE__ */ new Set([...tY,...e.error,...t])],iY=Symbol.for(`@gjermundgaraba/effect-actions/Anyone`),aY=/^[A-Za-z0-9_-]{1,128}$/,oY=(e,t)=>{if(!aY.test(t)||t===`then`)throw Error(`Invalid ${e}: ${t}`)},sY=(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)}},cY=(e,t)=>sY(e,t,e=>e.name),lY=(e,t,n)=>{let r=t.filter(e=>!n.includes(e));if(r.length>0)throw Error(`Unknown ${e}: ${r.join(`, `)}`)},uY=e=>oy(e)?uY(e.thunk()):e,dY=e=>{let t=uY(e);return ay(t)?t.types.flatMap(dY):[t]},fY=e=>ty(e)?[e.literal]:xre(e)?e.enums.map(([,e])=>e):[void 0],pY=e=>dY(Ob(e)).flatMap(e=>{let t=iy(e)?e.propertySignatures.find(e=>e.name===`_tag`)?.type:void 0;return t===void 0?[]:dY(t).flatMap(fY).filter(It)}),mY=(e,t)=>{let n=t.flatMap(e=>pY(e.ast)).find(e=>Object.hasOwn(GJ,e));if(n!==void 0)throw Error(`${e}: error _tag "${n}" is built in, and declared on every surface`)},hY=()=>Math.random().toString(36).slice(2),gY=e=>{let t=j(`effect-actions/Implementation/${hY()}`);return{key:t,layer:Hf(t,e)}};var _Y=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!==iY)?Bne(n.#e.layer,n.#t.layer):n.#e.layer}static boundOf(t){let{actions:n}=t,r=e.own(t);return I(function*(){let e=yield*r.#e.key,t=n.some(e=>e.caller!==iY)?yield*r.#t.key:()=>F;return e.filter(([e])=>n.includes(e)).map(([e,n])=>[e,CY(e,n,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 vY=e=>Ha(e),yY=(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(`, `)}`)}},bY=(e,t)=>t===void 0?e:(yY(`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]:[_Y.share(n,e)]})),xY=e=>t=>{let[n,...r]=e.map(e=>_Y.layerOf(e));return n===void 0?t:Zf(t,Yf(n,...r))},SY=e=>z(_p(e,e=>_Y.boundOf(e)),e=>e.flat()),CY=(e,t,n)=>{let r={"action.name":e.name,"action.read_only":e.readOnly},i=e.caller===iY?F:R(om(e.caller),e=>Ai(e)?F:L(new YJ)),a=e.caller===iY?F:Sp(()=>n(e));return n=>{let o=km(Km(Sp(()=>t(n)),r),e.name,{captureStackTrace:!1,attributes:r});return um(i.pipe(jp(a),jp(o)))}},wY=`effect-actions/media`,TY=U({data:kC,mimeType:H});TY.annotate({[wY]:`image`});const EY=e=>e.annotations?.[wY]===`image`,DY=e=>EY(e)&&e.encoding===void 0?`image`:void 0,OY=MS(H,SS),kY=e=>hS(e)?e:Reflect.ownKeys(e).length===0?OY:U(e);function AY(e,t){oY(`action name`,e);let{caller:n,readOnly:r}=t;if(n!==iY&&!Qi(n))throw Error(`Missing caller: declare Action.Anyone or an identity service key`);if(n!==iY&&$i(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:kY(t.input??{}),success:t.success===void 0?kS:kY(t.success),error:nY(t.error),readOnly:r,mcp:{...t.mcp}};return mY(`Action "${i.name}"`,i.error),i}const jY=()=>F,MY=e=>{if(!Vt(e))throw Error(`Missing authorize: pass an authorization function, or Action.allowAll`);return e},NY=e=>{if(e===void 0)throw Error(`Protected actions require authorize, or Action.allowAll`);return e},PY=e=>{if(e!==void 0)throw Error(`A public-only target takes no authorize`);return jY},FY=e=>gY(hp(e)?z(e,MY):N(MY(e)));function IY(e,t,n){let r=Ha(e),i=r.map(e=>e.name);cY(`action`,r);let a=FY(r.some(e=>e.caller!==iY)?NY(n?.authorize):PY(n?.authorize)),o=t=>{let n=Vt(t)?Object.fromEntries(Array.isArray(e)?[]:r.map(({name:e})=>[e,t])):t;lY(`handlers`,Object.keys(n),i);let a=r.flatMap(e=>{let t=Object.hasOwn(n,e.name)?n[e.name]:void 0;return Vt(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=hp(t)?z(t,o):N(o(t));return new _Y(r,gY(s),a)}const LY=(e,t)=>{for(let n of e)if(n.caller!==iY&&(t===void 0||n.caller.key!==t.identity.key))throw Error(`Protected action '${n.name}' requires its matching authentication descriptor`)},RY=(e,t)=>R(om(e[`~verified`]),n=>Ai(n)?cm(t,e.identity,n.value):L(new YJ)),zY={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(/\n/g,`
|
|
414
414
|
data: `)}\n`,t+`
|
|
415
|
-
`}case`Retry`:return`retry: ${bo(e.duration)}\n\n`}}};function BY(e){let t=typeof e==`string`?ule(e):e;return e=>e.annotate({httpApiStatus:t})}const VY=/*#__PURE__*/ (e=>jS.pipe(BY(e)))(204),HY=e=>_S(e)&&A(e,`~effect/http-api/HttpApiSchema/Stream`),UY=e=>HY(e)&&e._tag===`StreamSse`,WY=e=>HY(e)&&e._tag===`StreamUint8Array`,GY=`~effect/http-api/HttpApiSchema/WithHeaders`,KY=e=>A(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),qY=e=>_S(e)&&A(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function JY(e,t,n){return gS(e.ast,{[GY]:GY,schema:t,headers:n})}function YY(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??XY(t._tag)}})}function XY(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 ZY(e){return t=>YY(t,{_tag:`Json`,...e})}function QY(e){return t=>YY(t,{_tag:`FormUrlEncoded`,...e})}const $Y=e=>{if(ty(e))return!0;let t=Ab(e);if(ty(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&ty(n)},eX=/*#__PURE__*/ Ub(`~httpApiEncoding`),tX=/*#__PURE__*/ Ub(`~httpApiWithHeaders`),nX=/*#__PURE__*/ Ub(`httpApiStatus`),rX={_tag:`Json`,contentType:`application/json`},iX={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function aX(e){return eX(e)??rX}function oX(e,t){return eX(e)||(dA(t)?rX:iX)}function sX(e){let t=aX(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function cX(e){return nX(e)??200}function lX(e){return qY(e)?nX(e.ast)??cX(e.schema.ast):cX(e.ast)}function uX(e){return qY(e)&&eX(e.ast)===void 0?sX(e.schema.ast):sX(e.ast)}function dX(e){return nX(e)??500}function fX(e){return qY(e)?nX(e.ast)??dX(e.schema.ast):dX(e.ast)}function pX(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const mX=`~effect/http-api/HttpApiEndpoint`;function hX(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function gX(e){let t=Array.from(e.success);return Wa(t)?t:[VY]}function _X(e){let t=new Set(e.error),n=e.disableCodecs?k:EX;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const vX={[mX]:mX,pipe(){return bt(this,arguments)},prefix(e){return bX({...yX(this),path:GN(this.path,e)})},middleware(e){return bX({...yX(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return bX({...yX(this),annotations:aa(this.annotations,e,t)})},annotateMerge(e){return bX({...yX(this),annotations:ga(this.annotations,e)})}},yX=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 bX(e){function t(){}return Object.setPrototypeOf(t,vX),Object.assign(t,e)}const xX=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?k:XC;return bX({identifier:t,path:n,method:e,params:SX(r?.params,a),query:SX(r?.query,a),headers:SX(r?.headers,a),payload:CX(r?.payload,e,i),success:TX(r?.success,e,i),error:DX(r?.error,i),annotations:na(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function SX(e,t){if(e!==void 0)return _S(e)?t(e):t(U(e))}function CX(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:_S(e)?[e]:[U(e).pipe(QY())],a=n?k:LX;for(let e of i){let n=oX(e.ast,t),i=pX(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 wX=`effect/http-api/stream/failure`;function TX(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Ha(e);return OX(r,t),new Set(n?r:r.map(EX))}const EX=/*#__PURE__*/ At(e=>HY(e)?e:qY(e)?JY(e,HY(e.schema)?e.schema:IX(e.schema,uX(e)),XC(e.headers)):FX(e));function DX(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Ha(e);for(let e of n){let t=qY(e)?e.schema:e;if(HY(t))throw Error(`Streaming schemas are not supported in error responses`)}return AX(n,fX),new Set(t?n:n.map(EX))}function OX(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=qY(i)?i.schema:i,a=lX(i);if(HY(e)){if(jX(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=kX(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(pX(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=kX(r,a),n=$Y(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=uX(i);if(pX(e.contentType)===pX(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(pX(uX(i).contentType)),t.noContent=t.noContent||n}}AX(e,lX)}function kX(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function AX(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=tX(r.ast),a=qY(r)?r.schema:i?.body??r,o=$Y(a.ast)?``:pX(HY(a)?a.contentType:uX(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(qY(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 jX(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(UY(e)&&MX(e.events.ast))throw Error(`SSE event name is reserved: ${wX}`)}function MX(e){return NX(Ab(e),/* @__PURE__ */ new Set)}function NX(e,t){if(t.has(e))return!1;if(t.add(e),oy(e))return e.types.some(e=>NX(e,t));if(sy(e))return NX(e.thunk(),t);if(!ay(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&PX(n.type,t)}function PX(e,t){if(t.has(e))return!1;t.add(e);let n=Ab(e);return n===e?ny(e)?e.literal===wX:oy(e)?e.types.some(e=>PX(e,t)):sy(e)?PX(e.thunk(),t):!1:PX(n,t)}function FX(e){let t=sX(e.ast),n=tX(e.ast);return n===void 0?IX(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:IX(n.body,t),headersCodec:XC(n.headers)}})}function IX(e,t){switch(t._tag){case`Json`:return YC(e);case`FormUrlEncoded`:return XC(e);case`Text`:case`Uint8Array`:return e}}function LX(e,t){switch(oX(e.ast,t)._tag){case`Json`:return YC(e);case`FormUrlEncoded`:return XC(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const RX=/*#__PURE__*/ xX(`POST`),zX=`~effect/http-api/HttpApi`,BX={[zX]:zX,pipe(){return bt(this,arguments)},add(...e){let t={...this.groups};for(let n of e)ar(t,n.identifier,n);return HX({...VX(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];ar(t,n,r.annotateMerge(ga(e.annotations,r.annotations)))}return HX({...VX(this),groups:t})},prefix(e){return HX({...VX(this),groups:La(this.groups,t=>t.prefix(e))})},middleware(e){return HX({...VX(this),groups:La(this.groups,t=>t.middleware(e))})},annotate(e,t){return HX({...VX(this),annotations:aa(this.annotations,e,t)})},annotateMerge(e){return HX({...VX(this),annotations:ga(this.annotations,e)})}},VX=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),HX=e=>{function t(){}return Object.setPrototypeOf(t,BX),Object.assign(t,e)},UX=e=>HX({identifier:e,groups:{},annotations:na()}),WX=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=ga(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:ga(n,e.annotations),successes:GX(gX(e),lX),errors:GX(_X(e),fX)})}},GX=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=qY(e)?e.schema:e;if(HY(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var KX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/AdditionalSchemas`)){},qX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ParseOptions`)){},JX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ParamsParseOptions`)){},YX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/QueryParseOptions`)){},XX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/HeadersParseOptions`)){},ZX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/PayloadParseOptions`)){},QX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/SuccessParseOptions`)){},$X=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const eZ=e=>{let t=ca(e,qX);return{params:ca(e,JX)??t,query:ca(e,YX)??t,headers:ca(e,XX)??t,payload:ca(e,ZX)??t,success:ca(e,QX)??t,error:ca(e,$X)??t}},tZ=/*#__PURE__*/ tM({status:400}),nZ=/*#__PURE__*/ tM({status:500}),rZ=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var iZ=class e extends (/*#__PURE__*/ Lo(`HttpApiSchemaError`)){[rZ]=rZ;get[iO](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return A(e,rZ)}static wrap(t,n){return Xm(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[FM](){return N(this[`~effect/ErrorReporter/ignore`]?tZ:nZ)}};const aZ=`~effect/http-api/HttpApiMiddleware`,oZ=`~effect/http-api/HttpApiMiddleware/Security`,sZ=e=>A(e,oZ),cZ=()=>(e,t)=>{let n=tr(),r;n!==0&&(nr(2),r=new globalThis.Error,nr(n));class i extends j()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[aZ]=aZ,a.error=lZ(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[oZ]=oZ,a.security=t.security}return a};function lZ(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const uZ=(e,t)=>zf(e,(e,n)=>Lp(e,e=>iZ.is(e)?t(e,n):L(e))),dZ=/*#__PURE__*/ new Set;function fZ(e){if(e===void 0)return dZ;let t=mb(e.ast);return ay(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function pZ(e,t){if(t===void 0||!e.includes(`:`))return e;let n=fZ(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 mZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Identifier`)){},hZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Title`)){},gZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Version`)){},_Z=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Description`)){},vZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/License`)){},yZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/ExternalDocs`)){},bZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Servers`)){},xZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Format`)){},SZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Summary`)){},CZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Deprecated`)){},wZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Override`)){};const TZ=/*#__PURE__*/ ya(`effect/http-api/OpenApi/Exclude`,{defaultValue:Tt});var EZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Transform`)){};const DZ={},OZ=/*#__PURE__*/ new WeakMap,kZ=e=>{if(Array.isArray(e))return e.map(kZ);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))ar(t,n,kZ(e[n]));return t}return e};function AZ(e,t,n){let r=ha(e,t);Mi(r)&&n(r.value)}function jZ(e,t){let n=t??DZ,r=OZ.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,OZ.set(n,r));let i=r.get(e);if(i!==void 0)return kZ(i);let a=MZ(e,n);return r.set(e,kZ(a)),a}function MZ(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:HZ(e,t),target:n}),n}AZ(e.annotations,hZ,e=>{n.info.title=e}),AZ(e.annotations,gZ,e=>{n.info.version=e}),AZ(e.annotations,_Z,e=>{n.info.description=e}),AZ(e.annotations,vZ,e=>{n.info.license=e}),AZ(e.annotations,SZ,e=>{n.info.summary=e}),AZ(e.annotations,bZ,e=>{n.servers=[...e]}),WX(e,{onGroup({group:e}){if(da(e.annotations,TZ))return;let t={name:sa(e.annotations,hZ,()=>e.identifier)};AZ(e.annotations,_Z,e=>{t.description=e}),AZ(e.annotations,yZ,e=>{t.externalDocs=e}),AZ(e.annotations,wZ,e=>{for(let[n,r]of Object.entries(e))ar(t,n,r)}),AZ(e.annotations,EZ,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(da(c,TZ))return;let u={tags:[sa(t.annotations,hZ,()=>t.identifier)],operationId:sa(e.annotations,mZ,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=fZ(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();ar(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??={},ar(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,By),a=i.length===1?i[0]:new Xy(i);u.responses[n].content??={},ar(u.responses[n].content,r,{schema:s(a,t)})})}),c!==void 0&&c.forEach((e,t)=>{u.responses[n].content??={},UY(e)?ar(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(NC(e.error,CC()).ast),errorSchema:s(e.error.ast),failureEvent:LZ}}):ar(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})}})}AZ(e.annotations,_Z,e=>{u.description=e}),AZ(e.annotations,SZ,e=>{u.summary=e}),AZ(e.annotations,CZ,e=>{u.deprecated=e}),AZ(e.annotations,yZ,e=>{u.externalDocs=e}),l.forEach(e=>{if(sZ(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=WZ(t);if(!Object.hasOwn(n.components.securitySchemes,e)){ar(n.components.securitySchemes,e,r);return}if(!bn(GZ(n.components.securitySchemes[e]),GZ(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=dA(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of hX(e)){if($Y(n.ast))continue;let r=oX(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(By);ar(e,n,{schema:s(t.length===1?t[0]:new Xy(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(RZ(e),()=>`Success`),g(zZ(_X(e),fX,BZ),()=>`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)||ar(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];AZ(e.annotations,wZ,e=>{for(let[t,r]of Object.entries(e))ar(n,t,r)}),AZ(e.annotations,EZ,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})}}),AZ(e.annotations,KX,e=>{e.forEach(e=>{let t=Wb(e.ast);if(t!==void 0){if(Object.hasOwn(n.components.schemas,t))throw new globalThis.Error(`Duplicate component schema identifier: ${t}`);ar(n.components.schemas,t,s(e.ast))}})}),NZ(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!Cx.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),AZ(e.annotations,wZ,e=>{for(let[t,r]of Object.entries(e))ar(n,t,r)}),AZ(e.annotations,EZ,e=>{n=e(n)}),n}function NZ(e,t,n){if(!Wa(e))return;let r=Xx(Ja(e,e=>e.ast),t),i=Ja(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:PZ(t,r.references,i.select)}),a=jie($ie({representations:i,references:IZ(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`){or(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))ar(n,e,t)}function PZ(e,t,n){let r=FZ(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 FZ(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return FZ(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:FZ(r,t,new Set(n).add(e.$ref))}function IZ(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;ar(n,e.$ref,r),i.push(r);continue}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 LZ=`effect/http-api/stream/failure`;function RZ(e){return zZ(gX(e),lX,BZ)}function zZ(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=tX(e.ast),c=qY(e)?e.schema:i?.body??e,l=qY(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;HY(c)?s(c,u):$Y(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,uX(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 BZ(e){return Gb(e)??Wb(e)}const VZ=/*#__PURE__*/ H.annotate({format:`binary`});function HZ(e,t){switch(t){case`Uint8Array`:return VZ.ast;case`Text`:return ey(e)&&e.encoding===void 0?H.ast:e;case`Multipart`:e=UZ(e)}return kx(e)}function UZ(e){return ey(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?VZ.ast:typeof e?.recur==`function`?e.recur(UZ):e}const WZ=e=>{let t={};switch(AZ(e.annotations,_Z,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=ha(e.annotations,xZ).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}}},GZ=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,KZ=(e,t)=>zN(B(function*(n){let r=yield*tm(),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*Dp(`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=At(e=>sM(jZ(e)));yield*n.add(`GET`,t.openapiPath,P(()=>r(e)))}})),qZ=(e,t,n)=>Wf(I(function*(){let r=(yield*tm()).pipe(va(mf)),i=e.groups[t],a=n(eQ(i)),o=hp(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(iQ(e,i,t,r));return Qi(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),JZ=`~effect/http-api/HttpApiBuilder/Handlers`,YZ=e=>{switch(e._tag){case`Http`:return z(DN,t=>Ig(ZZ(t.headers.authorization,e.scheme)??``));case`ApiKey`:{let t=e.in===`header`?e.key.toLowerCase():e.key,n=U({[t]:H}),r=e.in===`query`?yse(n):e.in===`cookie`?_se(n):vse(n);return Zp(r,{onFailure:()=>Ig(``),onSuccess:e=>Ig(e[t])})}case`Basic`:{let e={username:``,password:Ig(``)};return z(DN,t=>{let n=ZZ(t.headers.authorization,XZ);if(n===void 0)return e;let r=ja(Xh(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:Ig(r.slice(i+1))}})}}},XZ=`Basic`;function ZZ(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 QZ=(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},$Z={[JZ]:JZ,pipe(){return bt(this,arguments)},handle(e,t,n){return QZ(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;QZ(this,t,e,!1,r)}return this},handleRaw(e,t,n){return QZ(this,e,t,!0,n)}},eQ=e=>{let t=Object.create($Z);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function tQ(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=G(r),o=lS(e._tag===`FormUrlEncoded`?ZC(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=>_re(Ab(e.ast)))})}),n}function nQ(e,t,n){let r=dA(t.method),i=r?pX(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return aM(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=Up(t.multipart);return a.limits&&(e=im(e,xN(a.limits))),R(e,s)}return N(a.limits?tD(t.multipartStream,xN(a.limits)):t.multipartStream);case`Json`:return R(Up(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return L(new iS(new H_({message:`Expected a valid JSON body`})))}});case`Text`:return R(Up(t.text),s);case`FormUrlEncoded`:{let e=r?z(Up(t.urlParamsBody),f_):N(n);return R(e,s)}case`Uint8Array`:return R(z(Up(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function rQ(e,t,n,r,i,a){let o=ga(ga(e.annotations,t.annotations),n.annotations),s=eZ(o),c=fS(wQ(n,s.headers),s.success),l=fS(TQ(n,s.headers),s.error),u=VO(n.params,e=>lS(e,s.params)),d=VO(n.headers,e=>lS(e,s.headers)),f=VO(n.query,e=>lS(ZC(e),s.query)),p=pQ(n,s.success),m=fQ(n,s.success,s.headers),h=n.payload.size>0&&!a?tQ(n.payload,s.payload):void 0;return aQ(t,n,r,I(function*(){let e=ow().context,r=ua(e,DN),a=ua(e,RN),o=ua(e,ON),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*iZ.wrap(`Params`,u(a.params))),d&&(s.headers=yield*iZ.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*iZ.wrap(`Query`,f(o))),h){let e=nQ(h,r,o);if(eM(e))return e;e!==void 0&&(s.payload=yield*iZ.wrap(`Payload`,e))}let l=yield*i(s);if(eM(l))return l;let g;m!==void 0&&KY(l)&&(g=l.headers,l=l.body);let _=yield*iZ.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*iZ.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return pM(_,v)})).pipe(ure,Lp(e=>iZ.is(e)?Dp(e):Up(l(e))),im(r))}function iQ(e,t,n,r){let i=n.endpoint;return UN(i.method,pZ(i.path,i.params),rQ(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const aQ=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=ua(n,t);r=(sZ(t)?sQ(t,a):a)(r,i)}return r},oQ=/*#__PURE__*/ new WeakMap,sQ=(e,t)=>{let n=oQ.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:YZ(n),middleware:t[e]}));if(r.length===0)return k;let i=B(function*(e,t){e=Hp(e,e=>new lQ(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*Np(R(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(Ea(s)){if(uQ(s.failure))return yield*L(s.failure.error);n=s;continue}return s.success}return yield*Ap(n)});return oQ.set(t,i),i},cQ=`~effect/http-api/HttpApiBuilder/HandlerError`;var lQ=class{[cQ]=cQ;error;constructor(e){this.error=e}};const uQ=e=>A(e,cQ),dQ=/*#__PURE__*/ rS(eM);function fQ(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)qY(t)&&(r.set(lX(t),fS(t.headers,n)),HY(t.schema)||i.push(xQ(t,n)));return r.size===0?void 0:{encodeBody:fS(i.length===0?wS:i.length===1?i[0]:G(i),t),encodeHeaders:r}}function pQ(e,t){let n=mQ(e);if(n===void 0)return;let r=n.body,i=hQ(e),a=lX(n.schema),o=r.contentType;if(WY(r))return(e,t)=>BE(e)?N(uM(tD(e,t),{status:a,contentType:o})):i?void 0:new iS(new H_({message:`Expected a streaming response`}));let s=gQ(r,t);return(e,t)=>BE(e)?N(uM(tD(_Q(e,s),t),{status:a,contentType:o})):i?void 0:new iS(new H_({message:`Expected a streaming response`}))}function mQ(e){for(let t of e.success){let e=qY(t)?t.schema:t;if(HY(e))return{schema:t,body:e}}}function hQ(e){for(let t of e.success){let e=qY(t)?t.schema:t;if(_S(e)&&!HY(e))return!0}return e.success.size===0}function gQ(e,t){let n=YC(NC(e.error,CC()));return{sseMode:e.sseMode,encodeEvents:fS(W(e.events),t),encodeCause:fS(TC(n),t)}}function _Q(e,t){return e.pipe(t.sseMode===`data`?ZE(e=>({id:void 0,event:`message`,data:e})):k,voe(e=>Up(t.encodeEvents(e))),xoe(e=>HE(vQ(e,t))),ZE(bQ),Ooe)}function vQ(e,t){return t.encodeCause(e).pipe(Up,z(e=>({id:void 0,event:yQ,data:e})))}const yQ=`effect/http-api/stream/failure`;function bQ(e){return zY.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const xQ=/*#__PURE__*/ EQ(lX),SQ=/*#__PURE__*/ EQ(fX);function CQ(e,t){return qY(e)?OQ({schema:e,status:fX(e),encoding:uX(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):SQ(e,t)}function wQ(e,t){let n=gX(e).map(e=>xQ(e,t));return n.length===1?n[0]:G(n)}function TQ(e,t){let n=_X(e).map(e=>CQ(e,t));return n.length===0?wS:n.length===1?n[0]:G(n)}function EQ(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=tX(n.ast);if(i!==void 0)return OQ({schema:bS(n),status:e(i.body),encoding:sX(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=qY(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=qY(n)?n.schema:n,c=dQ.pipe(US(s,DQ(e,n)));return t.set(a,c),c}}function DQ(e,t){let n=qY(t)?t.schema:t;return zv({decode:(e,t)=>L(new W_({message:`Encode only schema`},e,t)),encode:kQ(e(t),uX(t),$Y(n.ast))})}function OQ(e){let t=fS(e.body),n=fS(e.headers,e.headersOptions),r=kQ(e.status,e.encoding,$Y(e.body.ast)),i=e=>e.issue,a=zv({decode:(e,t)=>L(new W_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(Hp(i),R(e=>r(e,o)),R(e=>z(Hp(n(s.headers),i),t=>pM(e,t))))}});return dQ.pipe(US(e.schema,a))}function kQ(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return N(tM({status:e}));try{let n=JSON.stringify(r);return N(aM(n,{status:e,contentType:t.contentType}))}catch{return L(new H_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>N(aM(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>N(rM(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>N(cM(n,{status:e}).pipe(dM(`content-type`,t.contentType)))}}const AQ=`~effect/http-api/HttpApiGroup`,jQ={[AQ]:AQ,add(...e){let t={...this.endpoints};for(let n of e)ar(t,n.identifier,n);return NQ({...MQ(this),endpoints:t})},prefix(e){return NQ({...MQ(this),endpoints:La(this.endpoints,t=>t.prefix(e))})},middleware(e){return NQ({...MQ(this),endpoints:La(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return NQ({...MQ(this),annotations:ga(this.annotations,e)})},annotate(e,t){return NQ({...MQ(this),annotations:aa(this.annotations,e,t)})},annotateEndpointsMerge(e){return NQ({...MQ(this),endpoints:La(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return NQ({...MQ(this),endpoints:La(this.endpoints,n=>n.annotate(e,t))})},pipe(){return bt(this,arguments)}},MQ=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),NQ=e=>{function t(){}return Object.setPrototypeOf(t,jQ),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},PQ=(e,t)=>NQ({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:na()}),FQ=`~effect/http-api/HttpApiSecurity`,IQ={[FQ]:FQ,pipe(){return bt(this,arguments)}},LQ=/*#__PURE__*/ (e=>Object.assign(Object.create(IQ),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:na()}))({scheme:`Bearer`}),RQ=e=>Object.assign(Object.create(IQ),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:na()}),zQ=Ub(`httpApiStatus`),BQ=e=>zQ(e)??(sy(e)?BQ(e.thunk()):void 0),VQ=e=>{let t=BQ(e.ast);if(t!==void 0)return[zQ(e.ast)===void 0?BY(t)(e):e];let n=uY(e.ast);return oy(n)&&n.checks===void 0&&n.encoding===void 0?n.types.flatMap(e=>VQ(gS(e))):[BY(422)(e)]},HQ=(e,t)=>{let n=e.flatMap(VQ).find(e=>cS(e)(t));return n===void 0?void 0:sM(mS(YC(n))(t),{status:zQ(n.ast)??422})},UQ=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var WQ=class extends cZ()(`effect-actions/http/SchemaErrors`,{error:[JJ]}){};const GQ=()=>uZ(WQ,e=>L(UQ.has(e.kind)?e:JJ.fromSchemaError(e.cause))),KQ=e=>(e??`/api`).split(`/`).filter(e=>e!==``),qQ=e=>`/${e.join(`/`)}`,JQ=e=>e.join(`/`)||`/`,YQ=(e,t)=>{let n=PQ(e,{topLevel:!0}),[r,...i]=t;return UX(`actions`).annotate(qX,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},XQ=(e,t,n)=>{n!==void 0&&yY(`the binding does not hold it`,n,e.actions);let r=t.flatMap(e=>e.actions),i=bY(t,n??e.actions.filter(e=>r.includes(e))),a=i.flatMap(e=>e.actions);if(a.length===0&&n===void 0&&t.length>0){let t=new Set(e.actions.map(({name:e})=>e));throw Error(`No action of these implementations is in this HTTP binding: ${r.map(({name:e})=>t.has(e)?`${e} (another contract)`:e).join(`, `)||`none`}`)}return cY(`served action`,a),i},ZQ=(e,t,n)=>RX(e.name,t,{payload:e.input.pipe(ZY()),success:e.success,error:rY(e,n).flatMap(VQ)}),QQ=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function $Q(e,t={}){cY(`action`,e);let n=nY(t.error);mY(`ActionHttp binding`,n),LY(e,t.authentication);let r=KQ(t.prefix),i=t.authentication?.[`~middleware`],a=t.authentication?.error??[],o=e.map(e=>{let t=i===void 0||e.caller===iY,o=ZQ(e,qQ([...r,e.name]),t?n:[...n,...a]).annotate(_Z,e.description);return t?o:o.middleware(i)}),s=YQ(JQ(r),o);return{actions:e,error:n,prefix:qQ(r),api:s,authentication:t.authentication}}const e$=e=>Af((t,n)=>am(If(e,t,n),na())),t$=()=>KN(z(tm(),e=>{let t=va(mf)(e);return e=>cm(e,e=>ga(t,e))})).layer;var n$=class extends cZ()(`effect-actions/ActionHttp/StepUp`){},r$=class extends cZ()(`effect-actions/ActionHttp/JsonContentType`){};const i$=()=>zf(r$,e=>R(DN,t=>t.headers[`content-type`]===void 0?N(aM(`Unsupported content-type: none`,{status:415})):e));function a$(e,t,n={}){let r=XQ(e,vY(t),n.actions),i=r.flatMap(e=>e.actions);LY(i,e.authentication),sY(`middleware`,n.middleware??[],e=>e.key);let a=KQ(e.prefix),o=JQ(a),s=YQ(o,i.map(t=>{let r=QQ(ZQ(t,qQ([...a,t.name]),e.error).middleware(r$).middleware(WQ),n.middleware);return t.caller===iY||e.authentication===void 0?r:r.middleware(n$).middleware(e.authentication[`~middleware`])})).annotate(ZX,{errors:`all`,onExcessProperty:`error`}),c=qf(I(function*(){let t=yield*SY(r),a=i.some(e=>e.caller!==iY)?e.authentication:void 0,c=a===void 0?Vf:yield*R(a[`~provider`],e=>e.descriptor===a?N(Yf(zf(a[`~middleware`],e.middleware),zf(n$,e.stepUp))):Dp(/* @__PURE__ */ Error(`Authentication "${a.name}": the binding's descriptor is not its provider's; build both from one descriptor`))),l=yield*_p(n.middleware??[],e=>z(om(e),t=>zf(e,t))),u=Object.fromEntries(t.map(([e,t])=>[e.name,e=>t(e.payload)]));return qZ(s,o,e=>e.handleAll(u)).pipe(Zf([GQ(),i$(),c,...l]),e$)})).pipe(xY(r));return KZ(s).pipe(Zf(c),Zf(t$()))}const o$=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,s$=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},c$=e=>s$(`Bearer`,e),l$=hS(eY),u$=cS(eY),d$=(e,t)=>Zt(e,`Forbidden`)&&e.scopes!==void 0?c$([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,o$.test(e.message)?e.message:void 0]]):void 0,f$=e=>sM(l$(e),{status:GJ[e._tag]}),p$=(e,t)=>{let n=f$(e),r=d$(e,t);return r===void 0?n:dM(n,`www-authenticate`,r)};var m$=class extends j()(`effect-actions/SteppedUp`){};const h$=e=>u$(e)&&(!Zt(e,`Forbidden`)||e.scopes!==void 0),g$=e=>Wp(e,e=>h$(e)?R(sm(m$),t=>Mi(t)?zO(t.value,ki(e)):F):F),_$=(e,t)=>I(function*(){let n=yield*LO(Oi()),r=yield*Pp(lm(e,m$,n)),i=yield*RO(n),a=qd(r)&&(Td(r.cause)||Ed(r.cause));return Mi(i)&&!a?p$(i.value,t):yield*r}),v$=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,y$=e=>zi(Fi(v$.exec(e??``)?.[1]),e=>Ig(e)),b$=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},x$=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:b$(e).href}),zue=e=>Mi(y$(e)),S$=(e,t)=>c$([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),C$=(e,t)=>{if(t!==void 0){if(!e)throw Error(`A protected resource is published only for a Bearer scheme`);if(!hp(t)){for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!XJ.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}`)}}},w$=(e,t)=>pM(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}:{}}),Bue=(e,t)=>{let n=t?.authentication,r=n===void 0||E$(n.security);C$(r,t?.protectedResource);let i=x$(t?.protectedResource),a=n!==void 0&&!r?D$(n.security,n.name):S$(i,zue(t?.authorization));if(!u$(e)){let t=HQ(n?.error??[],e);if(t===void 0)throw Error(`Not a refusal, nor an error the authentication declares`);return w$(t,a)}return w$(r?p$(e,i.metadataUrl):f$(e),a)},Vue=/\.well-known|[\t\n\r]/,Hue=e=>{let t=b$(e),n=t.href.slice(t.origin.length),r=sM({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 tM({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=>R(DN,a=>{let o=Vue.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`)?N(r):o&&a.method===`OPTIONS`?N(i(a)):e})},T$=e=>{let t=x$(e);return{metadataUrl:t.metadataUrl,invalid:S$(t,!0),anonymous:S$(t,!1),published:e===void 0?void 0:Hue(e)}},E$=e=>Zt(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,Uue=/^[\w.-]+$/,D$=(e,t)=>TO(e).pipe(DO(`Http`,({scheme:e})=>s$(e,[])),DO(`Basic`,()=>s$(`Basic`,[[`realm`,t]])),DO(`ApiKey`,()=>void 0),PO),O$=(e,t,...n)=>{let r=n[0]?.security??LQ,i=nY(n[0]?.error);if(!Uue.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key`);if(mY(`Authentication "${e}"`,i),!Zt(r,`Http`)&&!Zt(r,`ApiKey`)&&!Zt(r,`Basic`))throw Error(`Authentication takes one native HttpApiSecurity scheme`);return{name:e,identity:t,security:r,error:i,"~provider":j(`effect-actions/Authentication/Provider/${e}`),"~middleware":cZ()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":j(`effect-actions/Authentication/Verified/${e}`)}},k$=e=>Fg(e)?Rg(e)!==``:e.username!==``||Rg(e.password)!==``;function A$(e,t,n={}){let{security:r}=e,i=E$(r),a=n.protectedResource;C$(i,a);let o=hp(a)?z(a,e=>(C$(i,e),T$(e))):N(T$(a)),s=new YJ({message:i?`A bearer token is required.`:`A credential is required.`});return Hf(e[`~provider`],I(function*(){let n=yield*LN,{metadataUrl:a,invalid:c,anonymous:l,published:u}=yield*o;u!==void 0&&(yield*n.addGlobalMiddleware(u));let d=hp(t)?yield*t:t;if(!Vt(d))return yield*Dp(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let f=e=>k$(e)?d(e):L(s),p=kse((e,t)=>N(dM(t,`cache-control`,`no-store`))),m=t=>i?k$(t)?c:l:D$(r,e.name),h=t=>u$(t)?N(i?p$(t,a):f$(t)):Sp(()=>{let n=HQ(e.error,t);return n===void 0?Dp(t):N(n)}),g=(e,t,n)=>{let r=m(e);return em(f(e),{onFailure:h,onSuccess:e=>lm(t,n,e)}).pipe(gm(()=>p),Ase((e,t)=>N(w$(t,r))))};return{descriptor:e,middleware:{[e.name]:(t,{credential:n})=>g(n,t,e.identity)},stepUp:e=>i?Vp(e,h$,e=>N(p$(e,a))):e,http:((t,n)=>R(YZ(r),r=>n&&!k$(r)?t:g(r,i?_$(t,a):t,e[`~verified`]))),route:(t=>R(YZ(r),n=>g(n,Vp(t,u$,h),e.identity)))}}))}var j$=class extends JC()(`BadRequest`,{error:H},{httpApiStatus:400}){},M$=class extends JC()(`NotFound`,{error:H},{httpApiStatus:404}){},N$=class extends JC()(`Conflict`,{error:H},{httpApiStatus:409}){},P$=class extends JC()(`TooManyRequests`,{error:H},{httpApiStatus:429}){},F$=class extends JC()(`InternalServerError`,{error:H},{httpApiStatus:500}){cause},I$=class extends JC()(`ServiceUnavailable`,{error:H},{httpApiStatus:503}){};const L$=[j$,M$,N$,P$,F$,I$],R$=[...L$,QJ];var z$=class extends j()(`clankerauth/CurrentOwner`){};const B$=e=>O$(`clankerauth.OwnerSession`,z$,{security:RQ({in:`cookie`,key:e}),error:L$}),Wue=B$(`better-auth.session_token`),V$=O$(`clankerauth.OwnerToken`,z$,{error:L$}),Gue=U({email:H,password:H}),Kue=BS([`none`,`client_secret_basic`,`client_secret_post`]),H$=BS([`web`,`native`]),U$=W(H).check(vC({message:`Choose unique Resources`})),que=U({client_name:H,redirect_uris:W(H),resources:U$,token_endpoint_auth_method:Kue,application_type:H$}),Jue=U({client_id:H,client_name:H,redirect_uris:W(H),application_type:H$}),W$=U({client_id:H}),Yue=U({client_id:H,resource:yS(H)}),Xue=U({client_id:H,blocked:kS}),G$=U({onboarding:yS(BS([`managed`,`dcr`,`cimd`])),blocked:yS(kS),client_id:H,client_name:yS(H),redirect_uris:W(H),token_endpoint_auth_method:yS(H),application_type:yS(VS(H)),scope:yS(H),grant_types:yS(W(H))}),K$=G$.pipe(NS({client_secret:yS(H),client_secret_expires_at:yS(OS)})),q$=U({identifier:H,name:H,scopes:W(H)}),Zue=q$.pipe(NS({builtIn:kS})),J$=U({identifier:H,name:H.check(rC(/\S/u,{message:`Resources require a name`})),scopes:W(H.check(rC(/^\s*[\x21\x23-\x5B\x5D-\x7E]+\s*$/u,{message:`Resources require well-formed custom scopes`})))}),Que=U({identifier:H}),Y$=U({client_id:H,resource:H}),$ue=U({client_id:H,resources:U$}),ede=U({clientAccess:W(Y$)}),X$=PS(H,W(H)),Z$=PS(H,W(H).check(fC(1,{message:`Select explicitly granted, currently available Resource scopes`}),vC({message:`Select explicitly granted, currently available Resource scopes`}))).check(_C(1,{message:`Select at least one Resource and scope`})),Q$=H.check(hC(100,{message:`Key names require 1–100 characters`}),rC(/\S/u,{message:`Key names require 1–100 characters`})),$$=RC,tde=U({client_id:H,resource:H,scopes:W(H),approvedAt:VS($$),refreshedAt:VS($$)}),nde=U({name:Q$,permissions:Z$,expiresAt:VS($$)}),rde=U({keyId:H}),ide=U({keyId:H,name:yS(Q$),permissions:yS(Z$),enabled:yS(kS)}),e1=U({keyId:H,name:H,enabled:kS,permissions:X$,expiresAt:VS($$),createdAt:$$}),t1={caller:iY,error:L$},n1={caller:z$,error:L$},r1=[AY(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...t1,success:U({required:kS})}),AY(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...t1,input:Gue,success:U({created:kS}).pipe(BY(201))}),AY(`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,...t1,input:U({resource:H}),success:U({list:H})})],ade=U({clients:W(G$),resources:W(Zue),clientAccess:W(Y$),connections:W(tde),email:H,issuer:H}),i1=[AY(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...n1,success:ade}),AY(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...n1,input:que,success:K$.pipe(BY(201))}),AY(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...n1,input:Jue,success:G$}),AY(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...n1,input:W$,success:U({deleted:kS})}),AY(`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,...n1,input:Yue,success:U({revoked:kS})}),AY(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...n1,input:Xue,success:U({blocked:kS})}),AY(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...n1,input:W$,success:K$}),AY(`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,...n1,input:$ue,success:ede}),AY(`createResource`,{description:`Create an OAuth resource and its scopes.`,readOnly:!1,...n1,input:J$,success:q$.pipe(BY(201))}),AY(`updateResource`,{description:`Update an OAuth resource and its scopes.`,readOnly:!1,...n1,input:J$,success:q$}),AY(`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,...n1,input:Que,success:U({deleted:kS})}),AY(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...n1,success:U({keys:W(e1)})}),AY(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...n1,input:nde,success:e1.pipe(NS({key:H}),BY(201))}),AY(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...n1,input:ide,success:e1}),AY(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...n1,input:rde,success:U({deleted:kS})})],a1=e=>$Q([...i1,...r1],{authentication:e});a1(Wue);const ode=$Q(i1,{prefix:`/api/owner`,authentication:V$}),sde=new Map(R$.map(e=>[e,Ub(`httpApiStatus`)(e.ast)??500])),cde=e=>R$.some(t=>cS(t)(e)),o1=e=>{let t=new F$({error:`Request could not be completed`});return t.cause=e,t},lde=sae(U({message:vS(H),error_description:vS(H)})),ude=e=>({error:Pi(Bi(lde(e.body),e=>Fi(e.message??e.error_description)),()=>`Request could not be completed`)});function s1(e){if(cde(e))return e;if(jF(e)){let t=ude(e);switch(e.statusCode){case 400:case 422:return new j$(t);case 401:case 403:return new QJ({message:t.error});case 404:return new M$(t);case 409:return new N$(t);case 429:return new P$(t);case 503:return new I$(t)}}return GM(e)&&dde(e.reason)?new j$({error:`Request body could not be read`}):o1(e)}const dde=Zt(`RequestParseError`),c1=(e,t)=>new JJ({message:t,issues:[{path:e,message:t}]}),l1=e=>bp({try:e,catch:s1}),fde=oM(G(R$)),pde=e=>{let t=R$.find(t=>cS(t)(e));return t===void 0?Dp(/* @__PURE__ */ Error(`Undeclared API error`)):fde(e,{status:sde.get(t)??500}).pipe(Up)},u1=e=>pde(s1(e));var mde=/* @__PURE__ */ e({NodeSqliteDialect:()=>d1}),hde=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},gde=class{#e;#t=new vde;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new _de(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(qe.raw(`begin`))}async commitTransaction(e){await e.executeQuery(qe.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(qe.raw(`rollback`))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#n?.close()}},_de=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.`)}},vde=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?.()}},yde=class extends Ve{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},d1=class{#e;constructor(e){this.#e={...e}}createDriver(){return new gde(this.#e)}createQueryCompiler(){return new yde}createAdapter(){return new hde}createIntrospector(e){return Be(e)}};const f1=e=>{let t=lS(e);return e=>Hp(t(e),o1)};function p1(e){return(t,...n)=>bp({try:async()=>(await ze(t,...n).execute(e)).rows,catch:o1})}const m1=V(`Database.transaction`)(function*(e,t){let n=yield*bp({try:()=>e.startTransaction().execute(),catch:o1}),r=yield*Pp(t(p1(n))),i=Kp(bp({try:()=>n.rollback().execute(),catch:o1})),a=bp({try:()=>n.commit().execute(),catch:o1}).pipe(Wp(()=>i));return yield*Kd(r)?a:i,yield*r},wm);async function bde(e){let t=new _t(e);try{t.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`);let e=new He({dialect:new d1({database:t})});return await ze`SELECT 1`.execute(e),{kysely:e,sql:p1(e),close:()=>e.destroy()}}catch(e){throw t.close(),e}}const h1=e=>`${g1}${e}`,g1=`resource:`,_1=(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})`,v1=V(`Grants.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:h1(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*_1(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})`}),y1={read:`clankerauth:read`,write:`clankerauth:write`},b1=e=>new URL(`/`,e).href,xde=e=>`${e}/mcp`,x1=[`offline_access`],Sde=f1(TC(W(H))),Cde=f1(U({identifier:H,name:H,allowedScopes:H})),S1=f1(W(Y$)),wde=f1(W(U({clientId:H}))),Tde=f1(W(U({userId:VS(H)}))),C1=e=>({identifier:encodeURIComponent(e)}),Ede=B(function*(e,t,n,r,i){let a=yield*RT(1),o=e=>a.withPermit(e),s=V(`Resources.decode`)(function*(e){let t=yield*Cde(e),n=yield*Sde(t.allowedScopes);return{identifier:t.identifier,name:t.name,scopes:n.filter(e=>!x1.includes(e))}}),c=V(`Resources.list`)(function*(){let e=yield*t`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*_p(e,s)}),l=V(`Resources.get`)(function*(e){let n=yield*t`SELECT identifier, name, allowedScopes FROM oauthResource WHERE identifier = ${e}`;return n[0]?yield*s(n[0]):void 0}),u=V(`Resources.access`)(function*(){return yield*S1(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),d=V(`Resources.accessForClient`)(function*(e,t){return yield*S1(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)}),f=(e,t)=>[.../* @__PURE__ */ new Set([...x1,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],p=V(`Resources.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*c1([`resources`,n],`Unknown Resource`)}),m=V(`Resources.scopesFor`)(function*(e){let t=yield*c();return yield*p(t,e),f(t,e)}),h=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},g=V(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!h(t))return yield*c1([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>x1.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*c1([`scopes`,i],`offline_access is reserved`)}),_=V(`Resources.syncClient`)(function*(e,t,n){let r=yield*d(n,e),i=JSON.stringify(f(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*ep} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),v=V(`Resources.synchronize`)(function*(){let e=yield*c(),n=f(e,e.map(e=>e.identifier));r(n),yield*t`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*ep} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*wde(yield*t`SELECT clientId FROM oauthClient WHERE userId IS NOT NULL ORDER BY clientId`))yield*_(t,e,n.clientId)}),y=e=>e===i?L(c1([`identifier`],`The administration Resource is fixed`)):F;return{list:c,get:l,access:u,hasAccess:V(`Resources.hasAccess`)(function*(e,n){return(yield*t`SELECT 1 FROM oauthClient c WHERE c.clientId = ${e} AND (c.userId IS NULL
|
|
416
|
-
OR EXISTS (SELECT 1 FROM oauthClientResource l WHERE l.clientId = c.clientId AND l.resourceId = ${n}))`).length>0}),scopesFor:m,synchronize:v,create:V(`Resources.create`)(function*(t,r){let i=yield*g(t);return(yield*l(i.identifier))||(yield*m1(e,e=>v1(e,{resource:i.identifier}))),yield*l1(()=>n().api.adminCreateOAuthResource({headers:r,body:{identifier:i.identifier,name:i.name,allowedScopes:[...x1,...i.scopes]}})),yield*v(),i},o),update:V(`Resources.update`)(function*(e,t){let r=yield*g(e);return yield*y(r.identifier),yield*l1(()=>n().api.adminUpdateOAuthResource({headers:t,params:C1(r.identifier),body:{name:r.name,allowedScopes:[...x1,...r.scopes]}})),yield*v(),r},o),delete:V(`Resources.delete`)(function*(t,r){return yield*y(t),yield*l1(()=>n().api.adminDeleteOAuthResource({headers:r,params:C1(t)})),yield*m1(e,e=>v1(e,{resource:t})),yield*v(),{deleted:!0}},o),setAccess:V(`Resources.setAccess`)(function*(n,r){let[i]=yield*
|
|
417
|
-
VALUES (${see()}, ${n}, ${t}, ${new Date(o).toISOString()})`;yield*_(e,a,n)})),yield*d(n,t)},o)}});var w1=class extends j()(`clankerauth/ResponseCookies`){};const
|
|
415
|
+
`}case`Retry`:return`retry: ${bo(e.duration)}\n\n`}}};function BY(e){let t=typeof e==`string`?ule(e):e;return e=>e.annotate({httpApiStatus:t})}const VY=/*#__PURE__*/ (e=>kS.pipe(BY(e)))(204),HY=e=>hS(e)&&A(e,`~effect/http-api/HttpApiSchema/Stream`),UY=e=>HY(e)&&e._tag===`StreamSse`,WY=e=>HY(e)&&e._tag===`StreamUint8Array`,GY=`~effect/http-api/HttpApiSchema/WithHeaders`,KY=e=>A(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),qY=e=>hS(e)&&A(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function JY(e,t,n){return mS(e.ast,{[GY]:GY,schema:t,headers:n})}function YY(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??XY(t._tag)}})}function XY(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 ZY(e){return t=>YY(t,{_tag:`Json`,...e})}function QY(e){return t=>YY(t,{_tag:`FormUrlEncoded`,...e})}const $Y=e=>{if(ey(e))return!0;let t=Ob(e);if(ey(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&ey(n)},eX=/*#__PURE__*/ Vb(`~httpApiEncoding`),tX=/*#__PURE__*/ Vb(`~httpApiWithHeaders`),nX=/*#__PURE__*/ Vb(`httpApiStatus`),rX={_tag:`Json`,contentType:`application/json`},iX={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function aX(e){return eX(e)??rX}function oX(e,t){return eX(e)||(uA(t)?rX:iX)}function sX(e){let t=aX(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function cX(e){return nX(e)??200}function lX(e){return qY(e)?nX(e.ast)??cX(e.schema.ast):cX(e.ast)}function uX(e){return qY(e)&&eX(e.ast)===void 0?sX(e.schema.ast):sX(e.ast)}function dX(e){return nX(e)??500}function fX(e){return qY(e)?nX(e.ast)??dX(e.schema.ast):dX(e.ast)}function pX(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const mX=`~effect/http-api/HttpApiEndpoint`;function hX(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function gX(e){let t=Array.from(e.success);return Wa(t)?t:[VY]}function _X(e){let t=new Set(e.error),n=e.disableCodecs?k:EX;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const vX={[mX]:mX,pipe(){return bt(this,arguments)},prefix(e){return bX({...yX(this),path:GN(this.path,e)})},middleware(e){return bX({...yX(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return bX({...yX(this),annotations:ra(this.annotations,e,t)})},annotateMerge(e){return bX({...yX(this),annotations:ma(this.annotations,e)})}},yX=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 bX(e){function t(){}return Object.setPrototypeOf(t,vX),Object.assign(t,e)}const xX=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?k:YC;return bX({identifier:t,path:n,method:e,params:SX(r?.params,a),query:SX(r?.query,a),headers:SX(r?.headers,a),payload:CX(r?.payload,e,i),success:TX(r?.success,e,i),error:DX(r?.error,i),annotations:ea(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function SX(e,t){if(e!==void 0)return hS(e)?t(e):t(U(e))}function CX(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:hS(e)?[e]:[U(e).pipe(QY())],a=n?k:LX;for(let e of i){let n=oX(e.ast,t),i=pX(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 wX=`effect/http-api/stream/failure`;function TX(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Ha(e);return OX(r,t),new Set(n?r:r.map(EX))}const EX=/*#__PURE__*/ At(e=>HY(e)?e:qY(e)?JY(e,HY(e.schema)?e.schema:IX(e.schema,uX(e)),YC(e.headers)):FX(e));function DX(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Ha(e);for(let e of n){let t=qY(e)?e.schema:e;if(HY(t))throw Error(`Streaming schemas are not supported in error responses`)}return AX(n,fX),new Set(t?n:n.map(EX))}function OX(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=qY(i)?i.schema:i,a=lX(i);if(HY(e)){if(jX(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=kX(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(pX(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=kX(r,a),n=$Y(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=uX(i);if(pX(e.contentType)===pX(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(pX(uX(i).contentType)),t.noContent=t.noContent||n}}AX(e,lX)}function kX(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function AX(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=tX(r.ast),a=qY(r)?r.schema:i?.body??r,o=$Y(a.ast)?``:pX(HY(a)?a.contentType:uX(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(qY(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 jX(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(UY(e)&&MX(e.events.ast))throw Error(`SSE event name is reserved: ${wX}`)}function MX(e){return NX(Ob(e),/* @__PURE__ */ new Set)}function NX(e,t){if(t.has(e))return!1;if(t.add(e),ay(e))return e.types.some(e=>NX(e,t));if(oy(e))return NX(e.thunk(),t);if(!iy(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&PX(n.type,t)}function PX(e,t){if(t.has(e))return!1;t.add(e);let n=Ob(e);return n===e?ty(e)?e.literal===wX:ay(e)?e.types.some(e=>PX(e,t)):oy(e)?PX(e.thunk(),t):!1:PX(n,t)}function FX(e){let t=sX(e.ast),n=tX(e.ast);return n===void 0?IX(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:IX(n.body,t),headersCodec:YC(n.headers)}})}function IX(e,t){switch(t._tag){case`Json`:return JC(e);case`FormUrlEncoded`:return YC(e);case`Text`:case`Uint8Array`:return e}}function LX(e,t){switch(oX(e.ast,t)._tag){case`Json`:return JC(e);case`FormUrlEncoded`:return YC(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const RX=/*#__PURE__*/ xX(`POST`),zX=`~effect/http-api/HttpApi`,BX={[zX]:zX,pipe(){return bt(this,arguments)},add(...e){let t={...this.groups};for(let n of e)ir(t,n.identifier,n);return HX({...VX(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(ma(e.annotations,r.annotations)))}return HX({...VX(this),groups:t})},prefix(e){return HX({...VX(this),groups:Fa(this.groups,t=>t.prefix(e))})},middleware(e){return HX({...VX(this),groups:Fa(this.groups,t=>t.middleware(e))})},annotate(e,t){return HX({...VX(this),annotations:ra(this.annotations,e,t)})},annotateMerge(e){return HX({...VX(this),annotations:ma(this.annotations,e)})}},VX=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),HX=e=>{function t(){}return Object.setPrototypeOf(t,BX),Object.assign(t,e)},UX=e=>HX({identifier:e,groups:{},annotations:ea()}),WX=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=ma(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:ma(n,e.annotations),successes:GX(gX(e),lX),errors:GX(_X(e),fX)})}},GX=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=qY(e)?e.schema:e;if(HY(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var KX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/AdditionalSchemas`)){},qX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ParseOptions`)){},JX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ParamsParseOptions`)){},YX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/QueryParseOptions`)){},XX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/HeadersParseOptions`)){},ZX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/PayloadParseOptions`)){},QX=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/SuccessParseOptions`)){},$X=class extends (/*#__PURE__*/ j()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const eZ=e=>{let t=oa(e,qX);return{params:oa(e,JX)??t,query:oa(e,YX)??t,headers:oa(e,XX)??t,payload:oa(e,ZX)??t,success:oa(e,QX)??t,error:oa(e,$X)??t}},tZ=/*#__PURE__*/ eM({status:400}),nZ=/*#__PURE__*/ eM({status:500}),rZ=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var iZ=class e extends (/*#__PURE__*/ Io(`HttpApiSchemaError`)){[rZ]=rZ;get[rO](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return A(e,rZ)}static wrap(t,n){return Ym(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[PM](){return N(this[`~effect/ErrorReporter/ignore`]?tZ:nZ)}};const aZ=`~effect/http-api/HttpApiMiddleware`,oZ=`~effect/http-api/HttpApiMiddleware/Security`,sZ=e=>A(e,oZ),cZ=()=>(e,t)=>{let n=er(),r;n!==0&&(tr(2),r=new globalThis.Error,tr(n));class i extends j()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[aZ]=aZ,a.error=lZ(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[oZ]=oZ,a.security=t.security}return a};function lZ(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const uZ=(e,t)=>zf(e,(e,n)=>Lp(e,e=>iZ.is(e)?t(e,n):L(e))),dZ=/*#__PURE__*/ new Set;function fZ(e){if(e===void 0)return dZ;let t=fb(e.ast);return iy(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function pZ(e,t){if(t===void 0||!e.includes(`:`))return e;let n=fZ(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 mZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Identifier`)){},hZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Title`)){},gZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Version`)){},_Z=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Description`)){},vZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/License`)){},yZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/ExternalDocs`)){},bZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Servers`)){},xZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Format`)){},SZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Summary`)){},CZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Deprecated`)){},wZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Override`)){};const TZ=/*#__PURE__*/ _a(`effect/http-api/OpenApi/Exclude`,{defaultValue:Tt});var EZ=class extends (/*#__PURE__*/ j()(`effect/http-api/OpenApi/Transform`)){};const DZ={},OZ=/*#__PURE__*/ new WeakMap,kZ=e=>{if(Array.isArray(e))return e.map(kZ);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))ir(t,n,kZ(e[n]));return t}return e};function AZ(e,t,n){let r=pa(e,t);Ai(r)&&n(r.value)}function jZ(e,t){let n=t??DZ,r=OZ.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,OZ.set(n,r));let i=r.get(e);if(i!==void 0)return kZ(i);let a=MZ(e,n);return r.set(e,kZ(a)),a}function MZ(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:HZ(e,t),target:n}),n}AZ(e.annotations,hZ,e=>{n.info.title=e}),AZ(e.annotations,gZ,e=>{n.info.version=e}),AZ(e.annotations,_Z,e=>{n.info.description=e}),AZ(e.annotations,vZ,e=>{n.info.license=e}),AZ(e.annotations,SZ,e=>{n.info.summary=e}),AZ(e.annotations,bZ,e=>{n.servers=[...e]}),WX(e,{onGroup({group:e}){if(la(e.annotations,TZ))return;let t={name:aa(e.annotations,hZ,()=>e.identifier)};AZ(e.annotations,_Z,e=>{t.description=e}),AZ(e.annotations,yZ,e=>{t.externalDocs=e}),AZ(e.annotations,wZ,e=>{for(let[n,r]of Object.entries(e))ir(t,n,r)}),AZ(e.annotations,EZ,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(la(c,TZ))return;let u={tags:[aa(t.annotations,hZ,()=>t.identifier)],operationId:aa(e.annotations,mZ,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=fZ(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,zy),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??={},UY(e)?ir(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(MC(e.error,SC()).ast),errorSchema:s(e.error.ast),failureEvent:LZ}}):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})}})}AZ(e.annotations,_Z,e=>{u.description=e}),AZ(e.annotations,SZ,e=>{u.summary=e}),AZ(e.annotations,CZ,e=>{u.deprecated=e}),AZ(e.annotations,yZ,e=>{u.externalDocs=e}),l.forEach(e=>{if(sZ(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=WZ(t);if(!Object.hasOwn(n.components.securitySchemes,e)){ir(n.components.securitySchemes,e,r);return}if(!bn(GZ(n.components.securitySchemes[e]),GZ(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=uA(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of hX(e)){if($Y(n.ast))continue;let r=oX(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(zy);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(RZ(e),()=>`Success`),g(zZ(_X(e),fX,BZ),()=>`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];AZ(e.annotations,wZ,e=>{for(let[t,r]of Object.entries(e))ir(n,t,r)}),AZ(e.annotations,EZ,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})}}),AZ(e.annotations,KX,e=>{e.forEach(e=>{let t=Hb(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))}})}),NZ(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!xx.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),AZ(e.annotations,wZ,e=>{for(let[t,r]of Object.entries(e))ir(n,t,r)}),AZ(e.annotations,EZ,e=>{n=e(n)}),n}function NZ(e,t,n){if(!Wa(e))return;let r=Jx(Ja(e,e=>e.ast),t),i=Ja(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:PZ(t,r.references,i.select)}),a=Nie(tae({representations:i,references:IZ(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 PZ(e,t,n){let r=FZ(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 FZ(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return FZ(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:FZ(r,t,new Set(n).add(e.$ref))}function IZ(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);continue}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 LZ=`effect/http-api/stream/failure`;function RZ(e){return zZ(gX(e),lX,BZ)}function zZ(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=tX(e.ast),c=qY(e)?e.schema:i?.body??e,l=qY(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;HY(c)?s(c,u):$Y(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,uX(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 BZ(e){return Ub(e)??Hb(e)}const VZ=/*#__PURE__*/ H.annotate({format:`binary`});function HZ(e,t){switch(t){case`Uint8Array`:return VZ.ast;case`Text`:return $v(e)&&e.encoding===void 0?H.ast:e;case`Multipart`:e=UZ(e)}return Dx(e)}function UZ(e){return $v(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?VZ.ast:typeof e?.recur==`function`?e.recur(UZ):e}const WZ=e=>{let t={};switch(AZ(e.annotations,_Z,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=pa(e.annotations,xZ).pipe(Li(e=>({bearerFormat:e})),Fi);return{...t,type:`http`,scheme:e.scheme,...n}}case`ApiKey`:return{...t,type:`apiKey`,name:e.key,in:e.in}}},GZ=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,KZ=(e,t)=>zN(B(function*(n){let r=yield*em(),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*Dp(`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=At(e=>oM(jZ(e)));yield*n.add(`GET`,t.openapiPath,P(()=>r(e)))}})),qZ=(e,t,n)=>Wf(I(function*(){let r=(yield*em()).pipe(ga(mf)),i=e.groups[t],a=n(eQ(i)),o=hp(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(iQ(e,i,t,r));return Xi(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),JZ=`~effect/http-api/HttpApiBuilder/Handlers`,YZ=e=>{switch(e._tag){case`Http`:return z(DN,t=>Fg(ZZ(t.headers.authorization,e.scheme)??``));case`ApiKey`:{let t=e.in===`header`?e.key.toLowerCase():e.key,n=U({[t]:H}),r=e.in===`query`?yse(n):e.in===`cookie`?_se(n):vse(n);return Zp(r,{onFailure:()=>Fg(``),onSuccess:e=>Fg(e[t])})}case`Basic`:{let e={username:``,password:Fg(``)};return z(DN,t=>{let n=ZZ(t.headers.authorization,XZ);if(n===void 0)return e;let r=ka(Yh(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:Fg(r.slice(i+1))}})}}},XZ=`Basic`;function ZZ(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 QZ=(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},$Z={[JZ]:JZ,pipe(){return bt(this,arguments)},handle(e,t,n){return QZ(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;QZ(this,t,e,!1,r)}return this},handleRaw(e,t,n){return QZ(this,e,t,!0,n)}},eQ=e=>{let t=Object.create($Z);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function tQ(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=G(r),o=sS(e._tag===`FormUrlEncoded`?XC(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=>vre(Ob(e.ast)))})}),n}function nQ(e,t,n){let r=uA(t.method),i=r?pX(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return iM(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=Up(t.multipart);return a.limits&&(e=rm(e,xN(a.limits))),R(e,s)}return N(a.limits?eD(t.multipartStream,xN(a.limits)):t.multipartStream);case`Json`:return R(Up(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return L(new nS(new V_({message:`Expected a valid JSON body`})))}});case`Text`:return R(Up(t.text),s);case`FormUrlEncoded`:{let e=r?z(Up(t.urlParamsBody),d_):N(n);return R(e,s)}case`Uint8Array`:return R(z(Up(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function rQ(e,t,n,r,i,a){let o=ma(ma(e.annotations,t.annotations),n.annotations),s=eZ(o),c=uS(wQ(n,s.headers),s.success),l=uS(TQ(n,s.headers),s.error),u=BO(n.params,e=>sS(e,s.params)),d=BO(n.headers,e=>sS(e,s.headers)),f=BO(n.query,e=>sS(XC(e),s.query)),p=pQ(n,s.success),m=fQ(n,s.success,s.headers),h=n.payload.size>0&&!a?tQ(n.payload,s.payload):void 0;return aQ(t,n,r,I(function*(){let e=aw().context,r=ca(e,DN),a=ca(e,RN),o=ca(e,ON),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*iZ.wrap(`Params`,u(a.params))),d&&(s.headers=yield*iZ.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*iZ.wrap(`Query`,f(o))),h){let e=nQ(h,r,o);if($j(e))return e;e!==void 0&&(s.payload=yield*iZ.wrap(`Payload`,e))}let l=yield*i(s);if($j(l))return l;let g;m!==void 0&&KY(l)&&(g=l.headers,l=l.body);let _=yield*iZ.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*iZ.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return fM(_,v)})).pipe(ure,Lp(e=>iZ.is(e)?Dp(e):Up(l(e))),rm(r))}function iQ(e,t,n,r){let i=n.endpoint;return UN(i.method,pZ(i.path,i.params),rQ(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const aQ=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=ca(n,t);r=(sZ(t)?sQ(t,a):a)(r,i)}return r},oQ=/*#__PURE__*/ new WeakMap,sQ=(e,t)=>{let n=oQ.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:YZ(n),middleware:t[e]}));if(r.length===0)return k;let i=B(function*(e,t){e=Hp(e,e=>new lQ(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*Np(R(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(wa(s)){if(uQ(s.failure))return yield*L(s.failure.error);n=s;continue}return s.success}return yield*Ap(n)});return oQ.set(t,i),i},cQ=`~effect/http-api/HttpApiBuilder/HandlerError`;var lQ=class{[cQ]=cQ;error;constructor(e){this.error=e}};const uQ=e=>A(e,cQ),dQ=/*#__PURE__*/ tS($j);function fQ(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)qY(t)&&(r.set(lX(t),uS(t.headers,n)),HY(t.schema)||i.push(xQ(t,n)));return r.size===0?void 0:{encodeBody:uS(i.length===0?SS:i.length===1?i[0]:G(i),t),encodeHeaders:r}}function pQ(e,t){let n=mQ(e);if(n===void 0)return;let r=n.body,i=hQ(e),a=lX(n.schema),o=r.contentType;if(WY(r))return(e,t)=>zE(e)?N(lM(eD(e,t),{status:a,contentType:o})):i?void 0:new nS(new V_({message:`Expected a streaming response`}));let s=gQ(r,t);return(e,t)=>zE(e)?N(lM(eD(_Q(e,s),t),{status:a,contentType:o})):i?void 0:new nS(new V_({message:`Expected a streaming response`}))}function mQ(e){for(let t of e.success){let e=qY(t)?t.schema:t;if(HY(e))return{schema:t,body:e}}}function hQ(e){for(let t of e.success){let e=qY(t)?t.schema:t;if(hS(e)&&!HY(e))return!0}return e.success.size===0}function gQ(e,t){let n=JC(MC(e.error,SC()));return{sseMode:e.sseMode,encodeEvents:uS(W(e.events),t),encodeCause:uS(wC(n),t)}}function _Q(e,t){return e.pipe(t.sseMode===`data`?XE(e=>({id:void 0,event:`message`,data:e})):k,yoe(e=>Up(t.encodeEvents(e))),Soe(e=>VE(vQ(e,t))),XE(bQ),koe)}function vQ(e,t){return t.encodeCause(e).pipe(Up,z(e=>({id:void 0,event:yQ,data:e})))}const yQ=`effect/http-api/stream/failure`;function bQ(e){return zY.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const xQ=/*#__PURE__*/ EQ(lX),SQ=/*#__PURE__*/ EQ(fX);function CQ(e,t){return qY(e)?OQ({schema:e,status:fX(e),encoding:uX(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):SQ(e,t)}function wQ(e,t){let n=gX(e).map(e=>xQ(e,t));return n.length===1?n[0]:G(n)}function TQ(e,t){let n=_X(e).map(e=>CQ(e,t));return n.length===0?SS:n.length===1?n[0]:G(n)}function EQ(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=tX(n.ast);if(i!==void 0)return OQ({schema:vS(n),status:e(i.body),encoding:sX(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=qY(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=qY(n)?n.schema:n,c=dQ.pipe(VS(s,DQ(e,n)));return t.set(a,c),c}}function DQ(e,t){let n=qY(t)?t.schema:t;return Rv({decode:(e,t)=>L(new U_({message:`Encode only schema`},e,t)),encode:kQ(e(t),uX(t),$Y(n.ast))})}function OQ(e){let t=uS(e.body),n=uS(e.headers,e.headersOptions),r=kQ(e.status,e.encoding,$Y(e.body.ast)),i=e=>e.issue,a=Rv({decode:(e,t)=>L(new U_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(Hp(i),R(e=>r(e,o)),R(e=>z(Hp(n(s.headers),i),t=>fM(e,t))))}});return dQ.pipe(VS(e.schema,a))}function kQ(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return N(eM({status:e}));try{let n=JSON.stringify(r);return N(iM(n,{status:e,contentType:t.contentType}))}catch{return L(new V_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>N(iM(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>N(nM(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>N(sM(n,{status:e}).pipe(uM(`content-type`,t.contentType)))}}const AQ=`~effect/http-api/HttpApiGroup`,jQ={[AQ]:AQ,add(...e){let t={...this.endpoints};for(let n of e)ir(t,n.identifier,n);return NQ({...MQ(this),endpoints:t})},prefix(e){return NQ({...MQ(this),endpoints:Fa(this.endpoints,t=>t.prefix(e))})},middleware(e){return NQ({...MQ(this),endpoints:Fa(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return NQ({...MQ(this),annotations:ma(this.annotations,e)})},annotate(e,t){return NQ({...MQ(this),annotations:ra(this.annotations,e,t)})},annotateEndpointsMerge(e){return NQ({...MQ(this),endpoints:Fa(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return NQ({...MQ(this),endpoints:Fa(this.endpoints,n=>n.annotate(e,t))})},pipe(){return bt(this,arguments)}},MQ=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),NQ=e=>{function t(){}return Object.setPrototypeOf(t,jQ),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},PQ=(e,t)=>NQ({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ea()}),FQ=`~effect/http-api/HttpApiSecurity`,IQ={[FQ]:FQ,pipe(){return bt(this,arguments)}},LQ=/*#__PURE__*/ (e=>Object.assign(Object.create(IQ),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:ea()}))({scheme:`Bearer`}),RQ=e=>Object.assign(Object.create(IQ),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:ea()}),zQ=Vb(`httpApiStatus`),BQ=e=>zQ(e)??(oy(e)?BQ(e.thunk()):void 0),VQ=e=>{let t=BQ(e.ast);if(t!==void 0)return[zQ(e.ast)===void 0?BY(t)(e):e];let n=uY(e.ast);return ay(n)&&n.checks===void 0&&n.encoding===void 0?n.types.flatMap(e=>VQ(mS(e))):[BY(422)(e)]},HQ=(e,t)=>{let n=e.flatMap(VQ).find(e=>oS(e)(t));return n===void 0?void 0:oM(fS(JC(n))(t),{status:zQ(n.ast)??422})},UQ=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var WQ=class extends cZ()(`effect-actions/http/SchemaErrors`,{error:[JJ]}){};const GQ=()=>uZ(WQ,e=>L(UQ.has(e.kind)?e:JJ.fromSchemaError(e.cause))),KQ=e=>(e??`/api`).split(`/`).filter(e=>e!==``),qQ=e=>`/${e.join(`/`)}`,JQ=e=>e.join(`/`)||`/`,YQ=(e,t)=>{let n=PQ(e,{topLevel:!0}),[r,...i]=t;return UX(`actions`).annotate(qX,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},XQ=(e,t,n)=>{n!==void 0&&yY(`the binding does not hold it`,n,e.actions);let r=t.flatMap(e=>e.actions),i=bY(t,n??e.actions.filter(e=>r.includes(e))),a=i.flatMap(e=>e.actions);if(a.length===0&&n===void 0&&t.length>0){let t=new Set(e.actions.map(({name:e})=>e));throw Error(`No action of these implementations is in this HTTP binding: ${r.map(({name:e})=>t.has(e)?`${e} (another contract)`:e).join(`, `)||`none`}`)}return cY(`served action`,a),i},ZQ=(e,t,n)=>RX(e.name,t,{payload:e.input.pipe(ZY()),success:e.success,error:rY(e,n).flatMap(VQ)}),QQ=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function $Q(e,t={}){cY(`action`,e);let n=nY(t.error);mY(`ActionHttp binding`,n),LY(e,t.authentication);let r=KQ(t.prefix),i=t.authentication?.[`~middleware`],a=t.authentication?.error??[],o=e.map(e=>{let t=i===void 0||e.caller===iY,o=ZQ(e,qQ([...r,e.name]),t?n:[...n,...a]).annotate(_Z,e.description);return t?o:o.middleware(i)}),s=YQ(JQ(r),o);return{actions:e,error:n,prefix:qQ(r),api:s,authentication:t.authentication}}const e$=e=>Af((t,n)=>im(If(e,t,n),ea())),t$=()=>KN(z(em(),e=>{let t=ga(mf)(e);return e=>sm(e,e=>ma(t,e))})).layer;var n$=class extends cZ()(`effect-actions/ActionHttp/StepUp`){},r$=class extends cZ()(`effect-actions/ActionHttp/JsonContentType`){};const i$=()=>zf(r$,e=>R(DN,t=>t.headers[`content-type`]===void 0?N(iM(`Unsupported content-type: none`,{status:415})):e));function a$(e,t,n={}){let r=XQ(e,vY(t),n.actions),i=r.flatMap(e=>e.actions);LY(i,e.authentication),sY(`middleware`,n.middleware??[],e=>e.key);let a=KQ(e.prefix),o=JQ(a),s=YQ(o,i.map(t=>{let r=QQ(ZQ(t,qQ([...a,t.name]),e.error).middleware(r$).middleware(WQ),n.middleware);return t.caller===iY||e.authentication===void 0?r:r.middleware(n$).middleware(e.authentication[`~middleware`])})).annotate(ZX,{errors:`all`,onExcessProperty:`error`}),c=qf(I(function*(){let t=yield*SY(r),a=i.some(e=>e.caller!==iY)?e.authentication:void 0,c=a===void 0?Vf:yield*R(a[`~provider`],e=>e.descriptor===a?N(Yf(zf(a[`~middleware`],e.middleware),zf(n$,e.stepUp))):Dp(/* @__PURE__ */ Error(`Authentication "${a.name}": the binding's descriptor is not its provider's; build both from one descriptor`))),l=yield*_p(n.middleware??[],e=>z(am(e),t=>zf(e,t))),u=Object.fromEntries(t.map(([e,t])=>[e.name,e=>t(e.payload)]));return qZ(s,o,e=>e.handleAll(u)).pipe(Zf([GQ(),i$(),c,...l]),e$)})).pipe(xY(r));return KZ(s).pipe(Zf(c),Zf(t$()))}const o$=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,s$=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},c$=e=>s$(`Bearer`,e),l$=pS(eY),u$=oS(eY),d$=(e,t)=>Zt(e,`Forbidden`)&&e.scopes!==void 0?c$([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,o$.test(e.message)?e.message:void 0]]):void 0,f$=e=>oM(l$(e),{status:GJ[e._tag]}),p$=(e,t)=>{let n=f$(e),r=d$(e,t);return r===void 0?n:uM(n,`www-authenticate`,r)};var m$=class extends j()(`effect-actions/SteppedUp`){};const h$=e=>u$(e)&&(!Zt(e,`Forbidden`)||e.scopes!==void 0),g$=e=>Wp(e,e=>h$(e)?R(om(m$),t=>Ai(t)?RO(t.value,Oi(e)):F):F),_$=(e,t)=>I(function*(){let n=yield*IO(Di()),r=yield*Pp(cm(e,m$,n)),i=yield*LO(n),a=qd(r)&&(Td(r.cause)||Ed(r.cause));return Ai(i)&&!a?p$(i.value,t):yield*r}),v$=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,y$=e=>Li(Ni(v$.exec(e??``)?.[1]),e=>Fg(e)),b$=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},x$=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:b$(e).href}),zue=e=>Ai(y$(e)),S$=(e,t)=>c$([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),C$=(e,t)=>{if(t!==void 0){if(!e)throw Error(`A protected resource is published only for a Bearer scheme`);if(!hp(t)){for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!XJ.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}`)}}},w$=(e,t)=>fM(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}:{}}),Bue=(e,t)=>{let n=t?.authentication,r=n===void 0||E$(n.security);C$(r,t?.protectedResource);let i=x$(t?.protectedResource),a=n!==void 0&&!r?D$(n.security,n.name):S$(i,zue(t?.authorization));if(!u$(e)){let t=HQ(n?.error??[],e);if(t===void 0)throw Error(`Not a refusal, nor an error the authentication declares`);return w$(t,a)}return w$(r?p$(e,i.metadataUrl):f$(e),a)},Vue=/\.well-known|[\t\n\r]/,Hue=e=>{let t=b$(e),n=t.href.slice(t.origin.length),r=oM({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 eM({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=>R(DN,a=>{let o=Vue.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`)?N(r):o&&a.method===`OPTIONS`?N(i(a)):e})},T$=e=>{let t=x$(e);return{metadataUrl:t.metadataUrl,invalid:S$(t,!0),anonymous:S$(t,!1),published:e===void 0?void 0:Hue(e)}},E$=e=>Zt(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,Uue=/^[\w.-]+$/,D$=(e,t)=>wO(e).pipe(EO(`Http`,({scheme:e})=>s$(e,[])),EO(`Basic`,()=>s$(`Basic`,[[`realm`,t]])),EO(`ApiKey`,()=>void 0),NO),O$=(e,t,...n)=>{let r=n[0]?.security??LQ,i=nY(n[0]?.error);if(!Uue.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key`);if(mY(`Authentication "${e}"`,i),!Zt(r,`Http`)&&!Zt(r,`ApiKey`)&&!Zt(r,`Basic`))throw Error(`Authentication takes one native HttpApiSecurity scheme`);return{name:e,identity:t,security:r,error:i,"~provider":j(`effect-actions/Authentication/Provider/${e}`),"~middleware":cZ()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":j(`effect-actions/Authentication/Verified/${e}`)}},k$=e=>Pg(e)?Lg(e)!==``:e.username!==``||Lg(e.password)!==``;function A$(e,t,n={}){let{security:r}=e,i=E$(r),a=n.protectedResource;C$(i,a);let o=hp(a)?z(a,e=>(C$(i,e),T$(e))):N(T$(a)),s=new YJ({message:i?`A bearer token is required.`:`A credential is required.`});return Hf(e[`~provider`],I(function*(){let n=yield*LN,{metadataUrl:a,invalid:c,anonymous:l,published:u}=yield*o;u!==void 0&&(yield*n.addGlobalMiddleware(u));let d=hp(t)?yield*t:t;if(!Vt(d))return yield*Dp(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let f=e=>k$(e)?d(e):L(s),p=kse((e,t)=>N(uM(t,`cache-control`,`no-store`))),m=t=>i?k$(t)?c:l:D$(r,e.name),h=t=>u$(t)?N(i?p$(t,a):f$(t)):Sp(()=>{let n=HQ(e.error,t);return n===void 0?Dp(t):N(n)}),g=(e,t,n)=>{let r=m(e);return $p(f(e),{onFailure:h,onSuccess:e=>cm(t,n,e)}).pipe(hm(()=>p),Ase((e,t)=>N(w$(t,r))))};return{descriptor:e,middleware:{[e.name]:(t,{credential:n})=>g(n,t,e.identity)},stepUp:e=>i?Vp(e,h$,e=>N(p$(e,a))):e,http:((t,n)=>R(YZ(r),r=>n&&!k$(r)?t:g(r,i?_$(t,a):t,e[`~verified`]))),route:(t=>R(YZ(r),n=>g(n,Vp(t,u$,h),e.identity)))}}))}var j$=class extends qC()(`BadRequest`,{error:H},{httpApiStatus:400}){},M$=class extends qC()(`NotFound`,{error:H},{httpApiStatus:404}){},N$=class extends qC()(`Conflict`,{error:H},{httpApiStatus:409}){},P$=class extends qC()(`TooManyRequests`,{error:H},{httpApiStatus:429}){},F$=class extends qC()(`InternalServerError`,{error:H},{httpApiStatus:500}){cause},I$=class extends qC()(`ServiceUnavailable`,{error:H},{httpApiStatus:503}){};const L$=[j$,M$,N$,P$,F$,I$],R$=[...L$,QJ];var z$=class extends j()(`clankerauth/CurrentOwner`){};const B$=e=>O$(`clankerauth.OwnerSession`,z$,{security:RQ({in:`cookie`,key:e}),error:L$}),Wue=B$(`better-auth.session_token`),V$=O$(`clankerauth.OwnerToken`,z$,{error:L$}),Gue=U({email:H,password:H}),Kue=RS([`none`,`client_secret_basic`,`client_secret_post`]),H$=RS([`web`,`native`]),U$=W(H).check(_C({message:`Choose unique Resources`})),que=U({client_name:H,redirect_uris:W(H),resources:U$,token_endpoint_auth_method:Kue,application_type:H$}),Jue=U({client_id:H,client_name:H,redirect_uris:W(H),application_type:H$}),W$=U({client_id:H}),Yue=U({client_id:H,resource:_S(H)}),Xue=U({client_id:H,blocked:DS}),G$=U({onboarding:_S(RS([`managed`,`dcr`,`cimd`])),blocked:_S(DS),client_id:H,client_name:_S(H),redirect_uris:W(H),token_endpoint_auth_method:_S(H),application_type:_S(zS(H)),scope:_S(H),grant_types:_S(W(H))}),K$=G$.pipe(jS({client_secret:_S(H),client_secret_expires_at:_S(ES)})),q$=U({identifier:H,name:H,scopes:W(H)}),Zue=q$.pipe(jS({builtIn:DS})),J$=U({identifier:H,name:H.check(nC(/\S/u,{message:`Resources require a name`})),scopes:W(H.check(nC(/^\s*[\x21\x23-\x5B\x5D-\x7E]+\s*$/u,{message:`Resources require well-formed custom scopes`})))}),Que=U({identifier:H}),Y$=U({client_id:H,resource:H}),$ue=U({client_id:H,resources:U$}),ede=U({clientAccess:W(Y$)}),X$=MS(H,W(H)),Z$=MS(H,W(H).check(dC(1,{message:`Select explicitly granted, currently available Resource scopes`}),_C({message:`Select explicitly granted, currently available Resource scopes`}))).check(gC(1,{message:`Select at least one Resource and scope`})),Q$=H.check(mC(100,{message:`Key names require 1–100 characters`}),nC(/\S/u,{message:`Key names require 1–100 characters`})),$$=LC,tde=U({client_id:H,resource:H,scopes:W(H),approvedAt:zS($$),refreshedAt:zS($$)}),nde=U({name:Q$,permissions:Z$,expiresAt:zS($$)}),rde=U({keyId:H}),ide=U({keyId:H,name:_S(Q$),permissions:_S(Z$),enabled:_S(DS)}),e1=U({keyId:H,name:H,enabled:DS,permissions:X$,expiresAt:zS($$),createdAt:$$}),t1={caller:iY,error:L$},n1={caller:z$,error:L$},r1=[AY(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...t1,success:U({required:DS})}),AY(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...t1,input:Gue,success:U({created:DS}).pipe(BY(201))}),AY(`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,...t1,input:U({resource:H}),success:U({list:H})})],ade=U({clients:W(G$),resources:W(Zue),clientAccess:W(Y$),connections:W(tde),email:H,issuer:H}),i1=[AY(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...n1,success:ade}),AY(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...n1,input:que,success:K$.pipe(BY(201))}),AY(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...n1,input:Jue,success:G$}),AY(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...n1,input:W$,success:U({deleted:DS})}),AY(`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,...n1,input:Yue,success:U({revoked:DS})}),AY(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...n1,input:Xue,success:U({blocked:DS})}),AY(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...n1,input:W$,success:K$}),AY(`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,...n1,input:$ue,success:ede}),AY(`createResource`,{description:`Create an OAuth resource and its scopes.`,readOnly:!1,...n1,input:J$,success:q$.pipe(BY(201))}),AY(`updateResource`,{description:`Update an OAuth resource and its scopes.`,readOnly:!1,...n1,input:J$,success:q$}),AY(`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,...n1,input:Que,success:U({deleted:DS})}),AY(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...n1,success:U({keys:W(e1)})}),AY(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...n1,input:nde,success:e1.pipe(jS({key:H}),BY(201))}),AY(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...n1,input:ide,success:e1}),AY(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...n1,input:rde,success:U({deleted:DS})})],a1=e=>$Q([...i1,...r1],{authentication:e});a1(Wue);const ode=$Q(i1,{prefix:`/api/owner`,authentication:V$}),sde=new Map(R$.map(e=>[e,Vb(`httpApiStatus`)(e.ast)??500])),cde=e=>R$.some(t=>oS(t)(e)),o1=e=>{let t=new F$({error:`Request could not be completed`});return t.cause=e,t},lde=lae(U({message:gS(H),error_description:gS(H)})),ude=e=>({error:Mi(Ri(lde(e.body),e=>Ni(e.message??e.error_description)),()=>`Request could not be completed`)});function s1(e){if(cde(e))return e;if(jF(e)){let t=ude(e);switch(e.statusCode){case 400:case 422:return new j$(t);case 401:case 403:return new QJ({message:t.error});case 404:return new M$(t);case 409:return new N$(t);case 429:return new P$(t);case 503:return new I$(t)}}return WM(e)&&dde(e.reason)?new j$({error:`Request body could not be read`}):o1(e)}const dde=Zt(`RequestParseError`),c1=(e,t)=>new JJ({message:t,issues:[{path:e,message:t}]}),l1=e=>bp({try:e,catch:s1}),fde=aM(G(R$)),pde=e=>{let t=R$.find(t=>oS(t)(e));return t===void 0?Dp(/* @__PURE__ */ Error(`Undeclared API error`)):fde(e,{status:sde.get(t)??500}).pipe(Up)},u1=e=>pde(s1(e));var mde=/* @__PURE__ */ e({NodeSqliteDialect:()=>d1}),hde=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},gde=class{#e;#t=new vde;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new _de(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(qe.raw(`begin`))}async commitTransaction(e){await e.executeQuery(qe.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(qe.raw(`rollback`))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#n?.close()}},_de=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.`)}},vde=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?.()}},yde=class extends Ve{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},d1=class{#e;constructor(e){this.#e={...e}}createDriver(){return new gde(this.#e)}createQueryCompiler(){return new yde}createAdapter(){return new hde}createIntrospector(e){return Be(e)}};const f1=e=>{let t=sS(e);return e=>Hp(t(e),o1)};function p1(e){return(t,...n)=>bp({try:async()=>(await ze(t,...n).execute(e)).rows,catch:o1})}const m1=V(`Database.transaction`)(function*(e,t){let n=yield*bp({try:()=>e.startTransaction().execute(),catch:o1}),r=yield*Pp(t(p1(n))),i=Kp(bp({try:()=>n.rollback().execute(),catch:o1})),a=bp({try:()=>n.commit().execute(),catch:o1}).pipe(Wp(()=>i));return yield*Kd(r)?a:i,yield*r},Cm);async function bde(e){let t=new _t(e);try{t.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`);let e=new He({dialect:new d1({database:t})});return await ze`SELECT 1`.execute(e),{kysely:e,sql:p1(e),close:()=>e.destroy()}}catch(e){throw t.close(),e}}const h1=e=>`${g1}${e}`,g1=`resource:`,_1=(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})`,v1=V(`Grants.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:h1(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*_1(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})`}),y1={read:`clankerauth:read`,write:`clankerauth:write`},b1=e=>new URL(`/`,e).href,x1=[`offline_access`],xde=f1(wC(W(H))),Sde=f1(U({identifier:H,name:H,allowedScopes:H})),S1=f1(W(Y$)),Cde=f1(W(U({clientId:H}))),wde=f1(W(U({userId:zS(H)}))),C1=e=>({identifier:encodeURIComponent(e)}),Tde=B(function*(e,t,n,r,i){let a=yield*LT(1),o=e=>a.withPermit(e),s=V(`Resources.decode`)(function*(e){let t=yield*Sde(e),n=yield*xde(t.allowedScopes);return{identifier:t.identifier,name:t.name,scopes:n.filter(e=>!x1.includes(e))}}),c=V(`Resources.list`)(function*(){let e=yield*t`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*_p(e,s)}),l=V(`Resources.get`)(function*(e){let n=yield*t`SELECT identifier, name, allowedScopes FROM oauthResource WHERE identifier = ${e}`;return n[0]?yield*s(n[0]):void 0}),u=V(`Resources.access`)(function*(){return yield*S1(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),d=V(`Resources.accessForClient`)(function*(e,t){return yield*S1(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)}),f=(e,t)=>[.../* @__PURE__ */ new Set([...x1,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],p=V(`Resources.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*c1([`resources`,n],`Unknown Resource`)}),m=V(`Resources.scopesFor`)(function*(e){let t=yield*c();return yield*p(t,e),f(t,e)}),h=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},g=V(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!h(t))return yield*c1([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>x1.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*c1([`scopes`,i],`offline_access is reserved`)}),_=V(`Resources.syncClient`)(function*(e,t,n){let r=yield*d(n,e),i=JSON.stringify(f(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*ep} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),v=V(`Resources.synchronize`)(function*(){let e=yield*c(),n=f(e,e.map(e=>e.identifier));r(n),yield*t`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*ep} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*Cde(yield*t`SELECT clientId FROM oauthClient WHERE userId IS NOT NULL ORDER BY clientId`))yield*_(t,e,n.clientId)}),y=e=>e===i?L(c1([`identifier`],`The administration Resource is fixed`)):F;return{list:c,get:l,access:u,hasAccess:V(`Resources.hasAccess`)(function*(e,n){return(yield*t`SELECT 1 FROM oauthClient c WHERE c.clientId = ${e} AND (c.userId IS NULL
|
|
416
|
+
OR EXISTS (SELECT 1 FROM oauthClientResource l WHERE l.clientId = c.clientId AND l.resourceId = ${n}))`).length>0}),scopesFor:m,synchronize:v,create:V(`Resources.create`)(function*(t,r){let i=yield*g(t);return(yield*l(i.identifier))||(yield*m1(e,e=>v1(e,{resource:i.identifier}))),yield*l1(()=>n().api.adminCreateOAuthResource({headers:r,body:{identifier:i.identifier,name:i.name,allowedScopes:[...x1,...i.scopes]}})),yield*v(),i},o),update:V(`Resources.update`)(function*(e,t){let r=yield*g(e);return yield*y(r.identifier),yield*l1(()=>n().api.adminUpdateOAuthResource({headers:t,params:C1(r.identifier),body:{name:r.name,allowedScopes:[...x1,...r.scopes]}})),yield*v(),r},o),delete:V(`Resources.delete`)(function*(t,r){return yield*y(t),yield*l1(()=>n().api.adminDeleteOAuthResource({headers:r,params:C1(t)})),yield*m1(e,e=>v1(e,{resource:t})),yield*v(),{deleted:!0}},o),setAccess:V(`Resources.setAccess`)(function*(n,r){let[i]=yield*wde(yield*t`SELECT userId FROM oauthClient WHERE clientId = ${n}`);if(!i)return yield*L(new M$({error:`Client not found`}));if(i.userId===null)return yield*L(new j$({error:`Automatic Clients may ask for any Resource; revoke or block them instead`}));let a=yield*c();yield*p(a,r);let o=yield*ep;return yield*m1(e,e=>I(function*(){let t=(yield*d(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*v1(e,{clientId:n,resource:i});for(let t of r)yield*e`INSERT OR IGNORE INTO oauthClientResource (id, clientId, resourceId, createdAt)
|
|
417
|
+
VALUES (${see()}, ${n}, ${t}, ${new Date(o).toISOString()})`;yield*_(e,a,n)})),yield*d(n,t)},o)}});var w1=class extends j()(`clankerauth/ResponseCookies`){};const Ede=KN()(e=>I(function*(){let t=[],n=yield*cm(e,w1,{add:e=>P(()=>t.push(...e))});return t.length?mM(n,fg(t)):n}));async function Dde(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=_e(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./dist-D9NNVevc.mjs`);n=i(r)(e)}return n.transaction||(xe.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 Ode(e){return Dde(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./kysely-adapter-BhjUN_Ts.mjs`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new l(`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 kde(e){let{indexesByTable:t,tables:n}=eee(e),r={};for(let e in n){let t=n[e],i=t.fields,a={};if(Object.entries(i).forEach(([e,t])=>{if(a[t.fieldName||e]=t,t.references){let r=n[t.references.model];r&&(a[t.fieldName||e].references={...t.references,model:r.modelName,field:t.references.field})}}),r[t.modelName]){r[t.modelName].fields={...r[t.modelName].fields,...a},t.disableMigrations&&(r[t.modelName].disableMigrations=!0);continue}r[t.modelName]={fields:a,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,n]of t)r[e]&&(r[e].indexes=n);return r}const Ade={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 T1(e,t){return`${ye(e)}\u0000${ye(t)}`}function E1(e,t){return`${e}\u0000${t}`}function D1(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 O1(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function k1(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[T1(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 jde(e,t,n,r){if(r)return k1(await r(n));let i;switch(t.type){case`sqlite`:i=(await ze`
|
|
418
418
|
SELECT
|
|
419
419
|
tables.name AS "tableName",
|
|
420
420
|
index_list.name AS "indexName",
|
|
@@ -486,7 +486,7 @@ data: `)}\n`,t+`
|
|
|
486
486
|
WHERE table_schemas.name = ${t.schema}
|
|
487
487
|
AND indexes.name IS NOT NULL
|
|
488
488
|
AND index_columns.key_ordinal > 0
|
|
489
|
-
`.execute(e)).rows}let a=/* @__PURE__ */ new Map;for(let e of i){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=T1(t,n),o=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=o===void 0?O1(e.isUnique??e.is_unique):!O1(o),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=O1(e.isPartial),d=!O1(e.isDisabled)&&!O1(e.isHypothetical)&&(e.isValid===void 0||O1(e.isValid)),f=a.get(i);a.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 k1([...a.values()])}async function
|
|
489
|
+
`.execute(e)).rows}let a=/* @__PURE__ */ new Map;for(let e of i){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=T1(t,n),o=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=o===void 0?O1(e.isUnique??e.is_unique):!O1(o),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=O1(e.isPartial),d=!O1(e.isDisabled)&&!O1(e.isHypothetical)&&(e.isValid===void 0||O1(e.isValid)),f=a.get(i);a.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 k1([...a.values()])}async function Mde(e,t){let n;switch(t.type){case`postgres`:case`sqlite`:return/* @__PURE__ */ new Map;case`mysql`:n=(await ze`
|
|
490
490
|
SELECT
|
|
491
491
|
table_name AS tableName,
|
|
492
492
|
column_name AS columnName,
|
|
@@ -504,12 +504,12 @@ data: `)}\n`,t+`
|
|
|
504
504
|
INNER JOIN sys.schemas AS table_schemas
|
|
505
505
|
ON table_schemas.schema_id = tables.schema_id
|
|
506
506
|
WHERE table_schemas.name = ${t.schema}
|
|
507
|
-
`.execute(e)).rows}let r=/* @__PURE__ */ new Map;for(let e of n){let t=e.tableName??e.TABLE_NAME,n=e.columnName??e.COLUMN_NAME;if(!t||!n)continue;let i=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);r.set(E1(t,n),{maxIndexBytes:i<0?null:i})}return r}function Pde({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 u=r[s];if(u){if(u.type===`string`||Array.isArray(u.type)){if(!n.has(s)){let e=ve({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let u=e.get(E1(o,s));if(!u?.maxIndexBytes)throw new l(`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+=u.maxIndexBytes}else c+=16}}if(c>s)throw new l(`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 Fde=class extends l{};function Ide(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function Lde(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 Rde(e,t,n){let r=e.selectFrom(n).select(ze`1`.as(`present`));return(await(t===`mssql`?r.top(1):r.limit(1)).execute()).length>0}function zde(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=jde[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function A1(e,{throwOnUnsafe:t=!0}={}){let n=Ade(e),r=_e(e),i=Se(e.logger),a=[],o=e=>{if(t)throw new Fde(e);a.push(e)},{kysely:s,databaseType:c,introspectIndexes:u,schemaName:d}=await aee(e);c||=(i.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),s||(i.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 f=await s.introspection.getTables(),p,m=f;switch(c){case`postgres`:{let e=d??await Ue(s);p={type:`postgres`,schema:e},i.debug(`PostgreSQL migration: Using schema '${e}' (${d?`from database.schemaName`:`from search_path`})`);try{(await s.introspection.getSchemas()).some(({name:t})=>t===e)||(d?i.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):i.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){i.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}m=f.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),i.debug(`Found ${m.length} table(s) in schema '${e}': ${m.map(e=>e.name).join(`, `)||`(none)`}`);break}case`mssql`:{let e=await Ke(s);p={type:`mssql`,schema:e},i.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),m=f.filter(t=>t.schema===e);break}case`mysql`:p={type:`mysql`};break;case`sqlite`:p={type:`sqlite`}}let h=await Mde(s,p,f.map(e=>e.name),u),g=await Nde(s,p),_=Me(iee(s,n),Ge(m)).filter(e=>e.kind===`unexpected-required-column`).map(e=>Ne(e,`database`)),v=[],y=[],b=[],x=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(n)){if(t.disableMigrations)continue;let n=m.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=T1(e,i),o=h.get(a);if(o){if(!D1(o,r))throw new l(`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(c===`sqlite`||c===`postgres`){let t=[...h.values()].find(t=>ye(t.name)===ye(i)&&ye(t.table)!==ye(e));if(t)throw new l(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=x.get(a);if(s){if(!D1({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new l(`Database index name "${i}" identifies more than one index on table "${e}".`);continue}n&&(c===`mysql`||c===`mssql`)&&Pde({columnBounds:g,dbType:c,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),x.set(a,r),b.push({table:e,index:r,name:i})}if(!n){let n=v.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=v.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?v.push(r):v[n].fields={...v[n].fields,...t.fields}:v.splice(i,0,r);continue}let r={};for(let[a,o]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===a);if(!t){r[a]=o;continue}o.required!==!1&&t.isNullable&&i.warn(`Column "${a}" 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.`),!zde(t.dataType,o.type,c)&&i.warn(`Field ${a} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(r).length>0&&y.push({table:e,fields:r,order:t.order||1/0})}let S=[];d&&v.length>0&&S.push(s.schema.createSchema(d).ifNotExists());let C=e.advanced?.database?.generateId===`uuid`,w=e.advanced?.database?.generateId===`serial`;function T(e,t,n){let r=e.type,i=c||`sqlite`,a={string:{sqlite:`text`,postgres:`text`,mysql:n?`varchar(${n})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:n?`varchar(${n})`: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:ze`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:w?ze`integer GENERATED BY DEFAULT AS IDENTITY`:C?`uuid`:`text`,mysql:w?`integer`:`varchar(36)`,mssql:w?`integer`:`varchar(36)`,sqlite:w?`integer`:`text`},foreignKeyId:{postgres:w?`integer`:C?`uuid`:`text`,mysql:w?`integer`:`varchar(36)`,mssql:w?`integer`:`varchar(36)`,sqlite:w?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(t===`id`||e.references?.field===`id`)return t===`id`?a.id[i]:a.foreignKeyId[i];if(Array.isArray(r))return`text`;if(!(r in a))throw Error(`Unsupported field type '${String(r)}' for field '${t}'. 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 a[r][i]}let ee=ree({schema:r,usePlural:!1}),te=Re({schema:r,usePlural:!1});function E(e,t){try{return`${ee(e)}.${te({model:e,field:t})}`}catch{return`${e}.${t}`}}let ne=[],re=(e,t)=>{if(c!==`mysql`&&c!==`mssql`)return;let r=n[e];if(r)return ve({columnName:t,dialect:c,fields:r.fields,indexes:r.indexes??[]})};if(y.length){let e=/* @__PURE__ */ new Map;for(let t of y)for(let[n,r]of Object.entries(t.fields)){let a=Ide(r,c),l=Lde(r);if(r.required!==!1&&!a&&!l){let i=e.get(t.table);if(i===void 0&&(i=await Rde(s,c,t.table),e.set(t.table,i)),i){let e=r.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``;o(`Cannot add required column "${n}" to populated table "${t.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 u=T(r,n,re(t.table,n)),d=s.schema.alterTable(t.table);if(r.index||r.unique){let e=Oe(t.table,n,r.unique??!1),a=s.schema.createIndex(e).on(t.table).columns([n]);r.unique&&(a=a.unique(),r.required===!1&&c===`mssql`&&(a=a.where(n,`is not`,null)),r.required!==!1&&r.defaultValue!==void 0&&r.defaultValue!==null&&typeof r.defaultValue!=`function`&&i.warn(`Adding unique column "${n}" to existing table "${t.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.`)),ne.push(a)}let f=d.addColumn(n,u,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(E(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),a?e=c===`mysql`?e.defaultTo(ze`CURRENT_TIMESTAMP(3)`):e.defaultTo(ze`CURRENT_TIMESTAMP`):l&&(e=e.defaultTo(typeof r.defaultValue==`boolean`&&(c===`sqlite`||c===`mssql`)?+!!r.defaultValue:r.defaultValue)),e));S.push(f)}}if(v.length)for(let e of v){let t=T({type:w?`number`:`string`},`id`),n=s.schema.createTable(e.table).addColumn(`id`,t,e=>w?c===`postgres`||c===`sqlite`?e.primaryKey().notNull():c===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():C&&c===`postgres`?e.primaryKey().defaultTo(ze`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[t,r]of Object.entries(e.fields)){let i=T(r,t,re(e.table,t));if(n=n.addColumn(t,i,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(E(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),r.unique&&(e=e.unique()),r.type===`date`&&typeof r.defaultValue==`function`&&(c===`postgres`||c===`mysql`||c===`mssql`)&&(e=c===`mysql`?e.defaultTo(ze`CURRENT_TIMESTAMP(3)`):e.defaultTo(ze`CURRENT_TIMESTAMP`)),e)),r.index&&!r.unique){let n=s.schema.createIndex(Oe(e.table,t,!1)).on(e.table).columns([t]);ne.push(n)}}S.push(n)}for(let{table:e,index:t,name:n}of b){let r=s.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),ne.push(r)}for(let e of ne)S.push(e);async function ie(){try{for(let e of S)await e.execute()}finally{S.length&&e.database&&Fe(e.database)}}async function ae(){return S.map(e=>e.compile().sql).join(`;
|
|
507
|
+
`.execute(e)).rows}let r=/* @__PURE__ */ new Map;for(let e of n){let t=e.tableName??e.TABLE_NAME,n=e.columnName??e.COLUMN_NAME;if(!t||!n)continue;let i=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);r.set(E1(t,n),{maxIndexBytes:i<0?null:i})}return r}function Nde({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 u=r[s];if(u){if(u.type===`string`||Array.isArray(u.type)){if(!n.has(s)){let e=ve({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let u=e.get(E1(o,s));if(!u?.maxIndexBytes)throw new l(`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+=u.maxIndexBytes}else c+=16}}if(c>s)throw new l(`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 Pde=class extends l{};function Fde(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function Ide(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 Lde(e,t,n){let r=e.selectFrom(n).select(ze`1`.as(`present`));return(await(t===`mssql`?r.top(1):r.limit(1)).execute()).length>0}function Rde(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=Ade[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function A1(e,{throwOnUnsafe:t=!0}={}){let n=kde(e),r=_e(e),i=Se(e.logger),a=[],o=e=>{if(t)throw new Pde(e);a.push(e)},{kysely:s,databaseType:c,introspectIndexes:u,schemaName:d}=await aee(e);c||=(i.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),s||(i.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 f=await s.introspection.getTables(),p,m=f;switch(c){case`postgres`:{let e=d??await Ue(s);p={type:`postgres`,schema:e},i.debug(`PostgreSQL migration: Using schema '${e}' (${d?`from database.schemaName`:`from search_path`})`);try{(await s.introspection.getSchemas()).some(({name:t})=>t===e)||(d?i.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):i.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){i.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}m=f.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),i.debug(`Found ${m.length} table(s) in schema '${e}': ${m.map(e=>e.name).join(`, `)||`(none)`}`);break}case`mssql`:{let e=await Ke(s);p={type:`mssql`,schema:e},i.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),m=f.filter(t=>t.schema===e);break}case`mysql`:p={type:`mysql`};break;case`sqlite`:p={type:`sqlite`}}let h=await jde(s,p,f.map(e=>e.name),u),g=await Mde(s,p),_=Me(iee(s,n),Ge(m)).filter(e=>e.kind===`unexpected-required-column`).map(e=>Ne(e,`database`)),v=[],y=[],b=[],x=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(n)){if(t.disableMigrations)continue;let n=m.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=T1(e,i),o=h.get(a);if(o){if(!D1(o,r))throw new l(`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(c===`sqlite`||c===`postgres`){let t=[...h.values()].find(t=>ye(t.name)===ye(i)&&ye(t.table)!==ye(e));if(t)throw new l(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=x.get(a);if(s){if(!D1({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new l(`Database index name "${i}" identifies more than one index on table "${e}".`);continue}n&&(c===`mysql`||c===`mssql`)&&Nde({columnBounds:g,dbType:c,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),x.set(a,r),b.push({table:e,index:r,name:i})}if(!n){let n=v.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=v.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?v.push(r):v[n].fields={...v[n].fields,...t.fields}:v.splice(i,0,r);continue}let r={};for(let[a,o]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===a);if(!t){r[a]=o;continue}o.required!==!1&&t.isNullable&&i.warn(`Column "${a}" 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.`),!Rde(t.dataType,o.type,c)&&i.warn(`Field ${a} in table ${e} has a different type in the database. Expected ${o.type} but got ${t.dataType}.`)}Object.keys(r).length>0&&y.push({table:e,fields:r,order:t.order||1/0})}let S=[];d&&v.length>0&&S.push(s.schema.createSchema(d).ifNotExists());let C=e.advanced?.database?.generateId===`uuid`,w=e.advanced?.database?.generateId===`serial`;function T(e,t,n){let r=e.type,i=c||`sqlite`,a={string:{sqlite:`text`,postgres:`text`,mysql:n?`varchar(${n})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:n?`varchar(${n})`: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:ze`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:w?ze`integer GENERATED BY DEFAULT AS IDENTITY`:C?`uuid`:`text`,mysql:w?`integer`:`varchar(36)`,mssql:w?`integer`:`varchar(36)`,sqlite:w?`integer`:`text`},foreignKeyId:{postgres:w?`integer`:C?`uuid`:`text`,mysql:w?`integer`:`varchar(36)`,mssql:w?`integer`:`varchar(36)`,sqlite:w?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(t===`id`||e.references?.field===`id`)return t===`id`?a.id[i]:a.foreignKeyId[i];if(Array.isArray(r))return`text`;if(!(r in a))throw Error(`Unsupported field type '${String(r)}' for field '${t}'. 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 a[r][i]}let ee=ree({schema:r,usePlural:!1}),te=Re({schema:r,usePlural:!1});function E(e,t){try{return`${ee(e)}.${te({model:e,field:t})}`}catch{return`${e}.${t}`}}let ne=[],re=(e,t)=>{if(c!==`mysql`&&c!==`mssql`)return;let r=n[e];if(r)return ve({columnName:t,dialect:c,fields:r.fields,indexes:r.indexes??[]})};if(y.length){let e=/* @__PURE__ */ new Map;for(let t of y)for(let[n,r]of Object.entries(t.fields)){let a=Fde(r,c),l=Ide(r);if(r.required!==!1&&!a&&!l){let i=e.get(t.table);if(i===void 0&&(i=await Lde(s,c,t.table),e.set(t.table,i)),i){let e=r.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``;o(`Cannot add required column "${n}" to populated table "${t.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 u=T(r,n,re(t.table,n)),d=s.schema.alterTable(t.table);if(r.index||r.unique){let e=Oe(t.table,n,r.unique??!1),a=s.schema.createIndex(e).on(t.table).columns([n]);r.unique&&(a=a.unique(),r.required===!1&&c===`mssql`&&(a=a.where(n,`is not`,null)),r.required!==!1&&r.defaultValue!==void 0&&r.defaultValue!==null&&typeof r.defaultValue!=`function`&&i.warn(`Adding unique column "${n}" to existing table "${t.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.`)),ne.push(a)}let f=d.addColumn(n,u,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(E(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),a?e=c===`mysql`?e.defaultTo(ze`CURRENT_TIMESTAMP(3)`):e.defaultTo(ze`CURRENT_TIMESTAMP`):l&&(e=e.defaultTo(typeof r.defaultValue==`boolean`&&(c===`sqlite`||c===`mssql`)?+!!r.defaultValue:r.defaultValue)),e));S.push(f)}}if(v.length)for(let e of v){let t=T({type:w?`number`:`string`},`id`),n=s.schema.createTable(e.table).addColumn(`id`,t,e=>w?c===`postgres`||c===`sqlite`?e.primaryKey().notNull():c===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():C&&c===`postgres`?e.primaryKey().defaultTo(ze`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[t,r]of Object.entries(e.fields)){let i=T(r,t,re(e.table,t));if(n=n.addColumn(t,i,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(E(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),r.unique&&(e=e.unique()),r.type===`date`&&typeof r.defaultValue==`function`&&(c===`postgres`||c===`mysql`||c===`mssql`)&&(e=c===`mysql`?e.defaultTo(ze`CURRENT_TIMESTAMP(3)`):e.defaultTo(ze`CURRENT_TIMESTAMP`)),e)),r.index&&!r.unique){let n=s.schema.createIndex(Oe(e.table,t,!1)).on(e.table).columns([t]);ne.push(n)}}S.push(n)}for(let{table:e,index:t,name:n}of b){let r=s.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),ne.push(r)}for(let e of ne)S.push(e);async function ie(){try{for(let e of S)await e.execute()}finally{S.length&&e.database&&Fe(e.database)}}async function ae(){return S.map(e=>e.compile().sql).join(`;
|
|
508
508
|
|
|
509
|
-
`)+`;`}return{toBeCreated:v,toBeAdded:y,toBeAddedIndexes:b,unsafeChanges:a,schemaProblems:_,runMigrations:ie,compileMigrations:ae}}function Bde(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function Vde(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new l(`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 l(`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 l(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function Hde(e,t){if(e.length===0)throw new l("`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 l(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new l(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new l(`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.`),Bde(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function Ude(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 Wde(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 Gde(){let e=Ae.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 Kde(){return Ae.CI!==`false`&&(`BUILD_ID`in Ae||`BUILD_NUMBER`in Ae||`CI`in Ae||`CI_APP_ID`in Ae||`CI_BUILD_ID`in Ae||`CI_BUILD_NUMBER`in Ae||`CI_NAME`in Ae||`CONTINUOUS_INTEGRATION`in Ae||`RUN_ID`in Ae)}function qde(){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 Jde(){return nee(`NODE_ENV`)===`production`?`production`:Kde()?`ci`:ke()?`test`:`development`}async function j1(e){let t=await CH(`SHA-256`).digest(e);return JV.encode(t)}const Yde=e=>De(`a-z`,`A-Z`,`0-9`)(e||32);let M1;async function N1(){if(M1)return M1;try{let e=process.cwd();if(!e)return;let t=await vt.readFile(Ze.join(e,`package.json`),`utf-8`);return M1=JSON.parse(t),M1}catch{}}async function P1(e){if(M1)return M1.dependencies?.[e]||M1.devDependencies?.[e]||M1.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=Ze.join(t,`node_modules`,e,`package.json`),r=await vt.readFile(n,`utf-8`);return JSON.parse(r).version||await F1(e)||void 0}catch{}return F1(e)}async function F1(e){let t=await N1();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function Xde(){return(await N1())?.name}async function Zde(){try{let e=mt.cpus();return{deploymentVendor:Qde(),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 rfe(),isDocker:await L1(),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 Qde(){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 I1;async function $de(){try{return dt.statSync(`/.dockerenv`),!0}catch{return!1}}async function efe(){try{return dt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function L1(){return I1===void 0&&(I1=await $de()||await efe()),I1}let R1;const tfe=async()=>{try{return dt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function nfe(){return R1===void 0&&(R1=await tfe()||await L1()),R1}async function rfe(){try{return process.platform===`linux`&&(mt.release().toLowerCase().includes(`microsoft`)||dt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await nfe():!1}catch{return!1}}let z1=null;async function B1(e){if(z1)return z1;let t=await Xde();return t?(z1=await j1(e?e+t:t),z1):e?(z1=await j1(e),z1):(z1=Yde(32),z1)}async function ife(){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 P1(e);if(n)return{name:t,version:n}}}async function afe(){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 P1(e);if(n)return{name:t,version:n}}}const ofe=async function(){};async function sfe(e,t){let n=e.telemetry?.debug||ge(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=tee.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:ofe};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(xe.error):r&&(n?xe.info(`telemetry event`,JSON.stringify(e,null,2)):await PG(r,{method:`POST`,body:e}).catch(xe.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(ge(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!ke())})(),o;return a&&(o=await B1(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await Wde(e,t),runtime:qde(),database:await ife(),framework:await afe(),environment:Jde(),systemInfo:await Zde(),packageManager:Gde()},anonymousId:o})),{publish:async t=>{a&&(o||=await B1(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function cfe(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function lfe(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!ke()){if(n&&ue)throw new l("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 l("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`."),cfe(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function ufe(e,t,n){let r=PI(t);r||(t=IH(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=IH(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=$H(t),o=Se(t.logger),s=YF(t.baseURL);if(YF(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new l(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:qF(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.
|
|
509
|
+
`)+`;`}return{toBeCreated:v,toBeAdded:y,toBeAddedIndexes:b,unsafeChanges:a,schemaProblems:_,runMigrations:ie,compileMigrations:ae}}function zde(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function Bde(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new l(`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 l(`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 l(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function Vde(e,t){if(e.length===0)throw new l("`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 l(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new l(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new l(`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.`),zde(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function Hde(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 Ude(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 Wde(){let e=Ae.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 Gde(){return Ae.CI!==`false`&&(`BUILD_ID`in Ae||`BUILD_NUMBER`in Ae||`CI`in Ae||`CI_APP_ID`in Ae||`CI_BUILD_ID`in Ae||`CI_BUILD_NUMBER`in Ae||`CI_NAME`in Ae||`CONTINUOUS_INTEGRATION`in Ae||`RUN_ID`in Ae)}function Kde(){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 qde(){return nee(`NODE_ENV`)===`production`?`production`:Gde()?`ci`:ke()?`test`:`development`}async function j1(e){let t=await CH(`SHA-256`).digest(e);return JV.encode(t)}const Jde=e=>De(`a-z`,`A-Z`,`0-9`)(e||32);let M1;async function N1(){if(M1)return M1;try{let e=process.cwd();if(!e)return;let t=await vt.readFile(Ze.join(e,`package.json`),`utf-8`);return M1=JSON.parse(t),M1}catch{}}async function P1(e){if(M1)return M1.dependencies?.[e]||M1.devDependencies?.[e]||M1.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=Ze.join(t,`node_modules`,e,`package.json`),r=await vt.readFile(n,`utf-8`);return JSON.parse(r).version||await F1(e)||void 0}catch{}return F1(e)}async function F1(e){let t=await N1();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function Yde(){return(await N1())?.name}async function Xde(){try{let e=mt.cpus();return{deploymentVendor:Zde(),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 nfe(),isDocker:await L1(),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 Zde(){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 I1;async function Qde(){try{return dt.statSync(`/.dockerenv`),!0}catch{return!1}}async function $de(){try{return dt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function L1(){return I1===void 0&&(I1=await Qde()||await $de()),I1}let R1;const efe=async()=>{try{return dt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function tfe(){return R1===void 0&&(R1=await efe()||await L1()),R1}async function nfe(){try{return process.platform===`linux`&&(mt.release().toLowerCase().includes(`microsoft`)||dt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await tfe():!1}catch{return!1}}let z1=null;async function B1(e){if(z1)return z1;let t=await Yde();return t?(z1=await j1(e?e+t:t),z1):e?(z1=await j1(e),z1):(z1=Jde(32),z1)}async function rfe(){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 P1(e);if(n)return{name:t,version:n}}}async function ife(){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 P1(e);if(n)return{name:t,version:n}}}const afe=async function(){};async function ofe(e,t){let n=e.telemetry?.debug||ge(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=tee.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:afe};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(xe.error):r&&(n?xe.info(`telemetry event`,JSON.stringify(e,null,2)):await PG(r,{method:`POST`,body:e}).catch(xe.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(ge(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!ke())})(),o;return a&&(o=await B1(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await Ude(e,t),runtime:Kde(),database:await rfe(),framework:await ife(),environment:qde(),systemInfo:await Xde(),packageManager:Wde()},anonymousId:o})),{publish:async t=>{a&&(o||=await B1(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function sfe(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function cfe(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!ke()){if(n&&ue)throw new l("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 l("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`."),sfe(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function lfe(e,t,n){let r=PI(t);r||(t=IH(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=IH(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=$H(t),o=Se(t.logger),s=YF(t.baseURL);if(YF(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new l(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:qF(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.
|
|
510
510
|
You are using the memory DB with generateId: false.
|
|
511
511
|
This will cause no id to be generated for any model.
|
|
512
|
-
Most of the features of Better Auth will not work correctly.`);let u=t.secrets??Vde(Ae.BETTER_AUTH_SECRETS),d=t.secret||Ae.BETTER_AUTH_SECRET||Ae.AUTH_SECRET||``,f,p;u?(Hde(u,o),f=u[0].value,p=Ude(u,d)):(f=d||`better-auth-secret-12345678901234567890`,lfe(f,o),p=f),t={...t,secret:f,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},VJ(t,o);let m=t.advanced?.ipAddress?.trustedProxies;if(m&&m.length>0){let e=gue(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=nH(t),g=_e(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=Fq[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:Le(n)},{publish:y}=await sfe(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),C=await eU(t),w=await aU(t),T={appName:t.appName||`Better Auth`,baseURL:c||``,version:de(),socialProviders:_,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:g,trustedOrigins:C,trustedProviders:w,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>tI(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:f,secretConfig:p,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??ue,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||_U,verify:t.emailAndPassword?.password?.verify||vU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:oJ},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:MH(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:v}),createAuthCookie:tH(t),async runMigrations(){throw new l(`runMigrations will be set by the specific init implementation`)},publishTelemetry:y,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!ke():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},ee=QH(T);return FV(ee)&&await ee,T.checkSchema=je(T.adapter),T.explicitSchemaCheck=Pe(T.adapter),T}const dfe=async e=>{let t=await ufe(await kde(e),e,e=>We(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new l(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await A1(e);await t()},t},ffe=(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 Ie?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=HJ(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(YF(e.baseURL))a=await rU(r,t,nU(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=qF(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new l(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:JF(n)||void 0},e=a.options}a.trustedOrigins=await eU(e,t),a.trustedProviders=await aU(e,t)}let{handler:o}=UJ(a,e);return Aue(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...q}}},pfe=e=>ffe(e,dfe),X=YP({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 V1(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 mfe={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*:/},hfe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,H1={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},gfe=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function _fe(e){return e instanceof Date&&!isNaN(e.getTime())}function vfe(e){let t=gfe.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 _fe(f)?f:null}function yfe(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 H1)return H1[s];if(!hfe.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(mfe).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`);return}if(a&&typeof t==`string`){let e=vfe(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function bfe(e,t={strict:!0}){return yfe(e,t)}function U1(e){return e==null?null:typeof e==`object`?e:Ee(e)}function W1(e){return e!=null&&typeof e==`string`}async function xfe(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>W1(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=U1(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 G1(e,t,n){let r=U1(t.metadata);if(W1(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 K1(e){return`api-key:${e}`}function q1(e){return`api-key:by-id:${e}`}function J1(e){return`api-key:by-ref:${e}`}function Sfe(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 Y1(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 X1(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function Z1(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 Q1(e,t,n){let r=K1(t);return Y1(await n.get(r))}async function $1(e,t,n){let r=q1(t);return Y1(await n.get(r))}const e0=/* @__PURE__ */ new Map;function Cfe(e,t){let n=(e0.get(e)??Promise.resolve()).then(t,t).finally(()=>{e0.get(e)===n&&e0.delete(e)});return e0.set(e,n),n}async function t0(e,t,n){await Cfe(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 n0(e,t,n,r,i){let a=Sfe(t),o=J1(t.referenceId);if(i.fallbackToDatabase){await Promise.all([n.set(K1(t.key),a,r),n.set(q1(t.id),a,r),n.delete(o)]);return}await Promise.all([n.set(K1(t.key),a,r),n.set(q1(t.id),a,r)]),await t0(n,o,e=>e.includes(t.id)?e:[...e,t.id])}async function wfe(e,t,n,r){let i=J1(t.referenceId);if(r.fallbackToDatabase){await Promise.all([n.delete(K1(t.key)),n.delete(q1(t.id)),n.delete(i)]);return}await Promise.all([n.delete(K1(t.key)),n.delete(q1(t.id)),t0(n,i,e=>e.filter(e=>e!==t.id))])}async function r0(e,t,n){let r=X1(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 Q1(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 n0(e,i,r,Z1(i),n),i}return n.storage===`secondary-storage`?r?await Q1(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function i0(e,t,n){let r=X1(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 $1(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 n0(e,i,r,Z1(i),n),i}return n.storage===`secondary-storage`?r?await $1(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function a0(e,t,n){let r=X1(e,n),i=Z1(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await n0(e,t,r,i,n);return}}async function o0(e,t,n){let r=X1(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 wfe(e,t,r,n);return}}function s0(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 c0(e,t,n,r){let i=X1(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=J1(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 V1(n,t=>$1(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s0(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 V1(l,t=>n0(e,t,i,Z1(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=J1(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 V1(l,t=>$1(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s0(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 Tfe(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 l0(e,t,n,r){let i=Tfe(e);if(!i){let e=X.ORGANIZATION_PLUGIN_REQUIRED;throw c.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=X.USER_NOT_MEMBER_OF_ORGANIZATION;throw c.from(`FORBIDDEN`,e)}if(!await Efe(e,a.role,n,r,i)){let e=X.INSUFFICIENT_API_KEY_PERMISSIONS;throw c.from(`FORBIDDEN`,e)}return a}async function Efe(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-Bz1iQbJ0.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const u0=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Dfe(e){return e instanceof c||e instanceof c||e?.name===`APIError`}const Ofe=D({configId:f().meta({description:`The configuration ID to use for the API key. If not provided, the default configuration will be used.`}).optional(),name:f().meta({description:`Name of the Api Key`}).optional(),expiresIn:m().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable().default(null),prefix:f().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:m().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:ie().optional(),refillAmount:m().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:m().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:m().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:m().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:T().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:g(f(),_(f())).meta({description:`Permissions of the Api Key.`}).optional(),userId:pF().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:pF().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function kfe({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return J(`/api-key/create`,{method:`POST`,body:Ofe,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:l,metadata:u,refillAmount:d,refillInterval:f,permissions:p,rateLimitMax:m,rateLimitTimeWindow:h,rateLimitEnabled:g}=n.body,_=m0(n.context,t,i),v=_.customKeyGenerator||e,y=await fH(n,{disableCookieCache:!0}),b=n.request||n.headers;if(b&&(d!==void 0||f!==void 0||m!==void 0||h!==void 0||g!==void 0||p!==void 0||l!==null))throw c.from(`BAD_REQUEST`,X.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);let x=_.references??`user`,S;if(x===`organization`){let e=n.body.organizationId;if(!e){let e=X.ORGANIZATION_ID_REQUIRED;throw c.from(`BAD_REQUEST`,e)}let t=y?.user.id||n.body.userId;if(!t)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);await l0(n,t,e,`create`),S=e}else if(b){if(!y?.user.id){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}S=y.user.id}else{let e=n.body.userId,t=y?.user.id;if(!t&&!e){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}if(y&&e&&t!==e){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}S=t||e}if(u){if(_.enableMetadata===!1)throw c.from(`BAD_REQUEST`,X.METADATA_DISABLED);if(typeof u!=`object`)throw c.from(`BAD_REQUEST`,X.INVALID_METADATA_TYPE)}if(d&&!f){let e=X.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw c.from(`BAD_REQUEST`,e)}if(f&&!d){let e=X.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw c.from(`BAD_REQUEST`,e)}if(o){if(_.keyExpiration.disableCustomExpiresTime===!0){let e=X.KEY_DISABLED_EXPIRATION;throw c.from(`BAD_REQUEST`,e)}let e=o/86400;if(_.keyExpiration.minExpiresIn>e){let e=X.EXPIRES_IN_IS_TOO_SMALL;throw c.from(`BAD_REQUEST`,e)}if(_.keyExpiration.maxExpiresIn<e){let e=X.EXPIRES_IN_IS_TOO_LARGE;throw c.from(`BAD_REQUEST`,e)}}if(s&&(s.length<_.minimumPrefixLength||s.length>_.maximumPrefixLength))throw c.from(`BAD_REQUEST`,X.INVALID_PREFIX_LENGTH);if(a){if(a.length<_.minimumNameLength||a.length>_.maximumNameLength)throw c.from(`BAD_REQUEST`,X.INVALID_NAME_LENGTH)}else if(_.requireName)throw c.from(`BAD_REQUEST`,X.NAME_REQUIRED);r(n.context);let C=await v({length:_.defaultKeyLength,prefix:s||_.defaultPrefix}),w=_.disableKeyHashing?C:await y0(C),T=null;_.startingCharactersConfig.shouldStore&&(T=C.substring(0,_.startingCharactersConfig.charactersLength));let ee=_.permissions?.defaultPermissions?typeof _.permissions.defaultPermissions==`function`?await _.permissions.defaultPermissions(S,n):_.permissions.defaultPermissions:void 0,te=p?JSON.stringify(p):ee?JSON.stringify(ee):void 0,E={configId:_.configId??`default`,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,name:a??null,prefix:s??_.defaultPrefix??null,start:T,key:w,enabled:!0,expiresAt:o?u0(o,`sec`):_.keyExpiration.defaultExpiresIn?u0(_.keyExpiration.defaultExpiresIn,`sec`):null,referenceId:S,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:m??_.rateLimit.maxRequests??null,rateLimitTimeWindow:h??_.rateLimit.timeWindow??null,remaining:l===null?l:l??d??null,refillAmount:d??null,refillInterval:f??null,rateLimitEnabled:g===void 0?_.rateLimit.enabled??!0:g,requestCount:0,permissions:te};u&&(E.metadata=u);let ne;if(_.storage===`secondary-storage`&&_.fallbackToDatabase)ne=await n.context.adapter.create({model:b0,data:E}),await a0(n,ne,_);else if(_.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||Le();ne={...E,id:e},await a0(n,ne,_)}else ne=await n.context.adapter.create({model:b0,data:E});return n.json({...ne,key:C,metadata:u??null,permissions:ne.permissions?Ee(ne.permissions):null})})}function Afe({deleteAllExpiredApiKeys:e}){return J.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 jfe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:f().meta({description:`The id of the Api Key`})});function Mfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/delete`,{method:`POST`,body:jfe,use:[mH],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 c.from(`UNAUTHORIZED`,X.USER_BANNED);let o=m0(t.context,e,r),s=null;if(s=await i0(t,i,o),!s||!g0(s.configId,o.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let l=m0(t.context,e,s.configId);if((l.references??`user`)===`organization`)await l0(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);try{l.storage===`secondary-storage`&&l.fallbackToDatabase?(await o0(t,s,l),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:s.id}]})):l.storage===`database`?await t.context.adapter.delete({model:b0,where:[{field:`id`,value:s.id}]}):await o0(t,s,l)}catch(e){throw c.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const Nfe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),id:f().meta({description:`The id of the Api Key`})});function Pfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/get`,{method:`GET`,query:Nfe,use:[mH],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=m0(t.context,e,r),s=null;if(s=await i0(t,i,o),!s||!g0(s.configId,o.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let l=m0(t.context,e,s.configId);if((l.references??`user`)===`organization`)await l0(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);n(t.context);let u=await G1(t,s,l),{key:d,...f}=s;return t.json({...f,metadata:u,permissions:f.permissions?Ee(f.permissions):null})})}function Ffe(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const Ife=D({configId:f().meta({description:`Filter by configuration ID. If not provided, returns keys from all configurations.`}).optional(),organizationId:f().meta({description:`Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys.`}).optional(),limit:mF().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:mF().int().nonnegative().meta({description:`The offset to start from`}).optional(),sortBy:f().meta({description:`The field to sort by (e.g., createdAt, name, expiresAt)`}).optional(),sortDirection:E([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function Lfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/list`,{method:`GET`,use:[mH],query:Ife,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 l0(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await c0(t,c,m0(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=Ffe(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>c0(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=>h0(t.configId)?h0(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>g0(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:U1(e.metadata),permissions:n.permissions?Ee(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(xfe(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const Rfe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:f().meta({description:`The id of the Api Key`}),userId:pF().meta({description:`The id of the user which the api key belongs to. server-only. Eg: "some-user-id"`}).optional(),name:f().meta({description:`The name of the key`}).optional(),enabled:T().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:m().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:m().meta({description:`The refill amount`}).optional(),refillInterval:m().meta({description:`The refill interval`}).optional(),metadata:ie().optional(),expiresIn:m().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:T().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:m().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:m().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:g(f(),_(f())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function zfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/update`,{method:`POST`,body:Rfe,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:l,refillInterval:u,remaining:d,name:f,permissions:p,rateLimitEnabled:m,rateLimitTimeWindow:h,rateLimitMax:g}=t.body,_=await fH(t,{disableCookieCache:!0}),v=t.request||t.headers,y=v&&!_?null:_?.user||{id:t.body.userId};if(!y?.id||_&&t.body.userId&&_?.user.id!==t.body.userId)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);if(v&&(l!==void 0||u!==void 0||g!==void 0||h!==void 0||m!==void 0||d!==void 0||p!==void 0))throw c.from(`BAD_REQUEST`,X.SERVER_ONLY_PROPERTY);let b=m0(t.context,e,r),x=null;if(x=await i0(t,i,b),!x||!g0(x.configId,b.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let S=m0(t.context,e,x.configId);if((S.references??`user`)===`organization`)await l0(t,y.id,x.referenceId,`update`);else if(x.referenceId!==y.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let C={};if(f!==void 0){if(f.length<S.minimumNameLength||f.length>S.maximumNameLength)throw c.from(`BAD_REQUEST`,X.INVALID_NAME_LENGTH);C.name=f}if(o!==void 0&&(C.enabled=o),a!==void 0){if(S.keyExpiration.disableCustomExpiresTime===!0)throw c.from(`BAD_REQUEST`,X.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<S.keyExpiration.minExpiresIn)throw c.from(`BAD_REQUEST`,X.EXPIRES_IN_IS_TOO_SMALL);if(e>S.keyExpiration.maxExpiresIn)throw c.from(`BAD_REQUEST`,X.EXPIRES_IN_IS_TOO_LARGE)}C.expiresAt=a?u0(a,`sec`):null}if(s!==void 0&&S.enableMetadata===!0){if(typeof s!=`object`)throw c.from(`BAD_REQUEST`,X.INVALID_METADATA_TYPE);C.metadata=s}if(d!==void 0&&(C.remaining=d),l!==void 0||u!==void 0){if(l!==void 0&&u===void 0)throw c.from(`BAD_REQUEST`,X.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(u!==void 0&&l===void 0)throw c.from(`BAD_REQUEST`,X.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);C.refillAmount=l,C.refillInterval=u}if(m!==void 0&&(C.rateLimitEnabled=m),h!==void 0&&(C.rateLimitTimeWindow=h),g!==void 0&&(C.rateLimitMax=g),p!==void 0&&(C.permissions=JSON.stringify(p)),Object.keys(C).length===0)throw c.from(`BAD_REQUEST`,X.NO_VALUES_TO_UPDATE);let w=x;try{if(S.storage===`secondary-storage`&&S.fallbackToDatabase){let e=await t.context.adapter.update({model:b0,where:[{field:`id`,value:x.id}],update:C});e&&(await a0(t,e,S),w=e)}else if(S.storage===`database`){let e=await t.context.adapter.update({model:b0,where:[{field:`id`,value:x.id}],update:C});e&&(w=e)}else{let e={...x,...C,updatedAt:/* @__PURE__ */ new Date};await a0(t,e,S),w=e}}catch(e){throw c.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let T=await G1(t,w,S),{key:ee,...te}=w;return t.json({...te,metadata:T,permissions:te.permissions?Ee(te.permissions):null})})}function d0(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:X.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function f0({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let l=n.disableKeyHashing?e:await y0(e),u=await r0(t,l,n);if(!u||o!==void 0&&!g0(u.configId,o))throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);let d=m0(t.context,r,u.configId);if(s&&d.customAPIKeyValidator&&!await d.customAPIKeyValidator({ctx:t,key:e}))throw c.from(`UNAUTHORIZED`,X.KEY_NOT_FOUND);if(u.enabled===!1)throw c.from(`UNAUTHORIZED`,X.KEY_DISABLED);if(u.expiresAt&&Date.now()>new Date(u.expiresAt).getTime()){let e=async()=>{d.storage===`secondary-storage`&&d.fallbackToDatabase?(await o0(t,u,d),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})):d.storage===`secondary-storage`?await o0(t,u,d):await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})};throw d.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),c.from(`UNAUTHORIZED`,X.KEY_EXPIRED)}if(a){let e=u.permissions?Ee(u.permissions):null;if(!e||!oee(e).authorize(a).success)throw c.from(`UNAUTHORIZED`,X.KEY_NOT_FOUND)}if(u.remaining===0&&u.refillAmount===null){let e=async()=>{d.storage===`secondary-storage`&&d.fallbackToDatabase?(await o0(t,u,d),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})):d.storage===`secondary-storage`?await o0(t,u,d):await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})};throw d.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED)}return{apiKey:d.storage===`database`||d.storage===`secondary-storage`&&d.fallbackToDatabase?await Bfe({ctx:t,apiKey:u,opts:d,hashedKey:l}):await Hfe({ctx:t,apiKey:u,opts:d,hashedKey:l}),opts:d}}async function Bfe({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await Vfe(e,t)),i=await p0(e,i,n);let a=await e.context.adapter.update({model:b0,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await a0(e,a,n),a}async function Vfe(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:b0,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:b0,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED);return a}async function p0(e,t,n){let r=d0(t,n);if(r.type===`deny`)throw new c(`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:b0,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:b0,where:[{field:`id`,value:t.id}]});if(!a)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return p0(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:b0,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:b0,where:[{field:`id`,value:t.id}]});if(!o)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return p0(e,o,n)}async function Hfe({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 c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED);i--}let o={...Ufe(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await r0(e,r,n);if(!t)return null;let i={...t,...o};return await a0(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 l=await s();if(!l)throw c.from(`INTERNAL_SERVER_ERROR`,X.FAILED_TO_UPDATE_API_KEY);return l}function Ufe(e,t){let n=d0(e,t);switch(n.type){case`deny`:throw new c(`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 Wfe=D({configId:f().meta({description:`Configuration ID to scope verification to. When omitted, the key is validated against its own configuration.`}).optional(),key:f().meta({description:`The key to verify`}),permissions:g(f(),_(f())).meta({description:`The permissions to verify.`}).optional()});function Gfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J.serverOnly({method:`POST`,body:Wfe},async r=>{let{configId:i,key:a}=r.body,o=m0(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:X.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await f0({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),Dfe(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:X.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 G1(r,s,c)),u.permissions=u.permissions?Ee(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function m0(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=X.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw c.from(`BAD_REQUEST`,t)}return{...n,configId:`default`}};return n?t.find(e=>e.configId===n)??r():r()}function h0(e){return!e||e==="default"}function g0(e,t){return h0(e)&&h0(t)?!0:e===t}let _0=null;async function v0(e,t=!1){_0&&!t&&(/* @__PURE__ */ new Date()).getTime()-_0.getTime()<1e4||(_0=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:b0,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 Kfe({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:kfe({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),verifyApiKey:Gfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),getApiKey:Pfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),updateApiKey:zfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),deleteApiKey:Mfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),listApiKeys:Lfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),deleteAllExpiredApiKeys:Afe({deleteAllExpiredApiKeys:v0})}}const qfe=({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?bfe(e):null}}}}}}),y0=async e=>{let t=await CH(`SHA-256`).digest(new TextEncoder().encode(e));return YV.encode(new Uint8Array(t),{padding:!1})},b0=`apikey`;function Jfe(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new l(`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 l(`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=YI(qfe({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=yU(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 u=Kfe({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.7`,$ERROR_CODES:X,hooks:{before:[{matcher:e=>!!s(e),handler:RF(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw c.from(`BAD_REQUEST`,X.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw c.from(`FORBIDDEN`,X.INVALID_API_KEY);let{apiKey:a}=await f0({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=v0(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=X.INVALID_REFERENCE_ID_FROM_API_KEY;throw c.from(`UNAUTHORIZED`,e)}let l=await e.context.internalAdapter.findUserById(a.referenceId);if(!l){let e=X.INVALID_REFERENCE_ID_FROM_API_KEY;throw c.from(`UNAUTHORIZED`,e)}let u={user:l,session:{id:a.id,token:t,userId:a.referenceId,userAgent:e.request?.headers.get(`user-agent`)??null,ipAddress:e.request?vI(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||u0(e.context.options.session?.expiresIn||604800,`ms`)}};return e.context.session=u,e.path===`/get-session`?u:{context:e}})}]},endpoints:{createApiKey:u.createApiKey,verifyApiKey:u.verifyApiKey,getApiKey:u.getApiKey,updateApiKey:u.updateApiKey,deleteApiKey:u.deleteApiKey,listApiKeys:u.listApiKeys,deleteAllExpiredApiKeys:u.deleteAllExpiredApiKeys},schema:i}}const x0=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await OI(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 OI(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 OI(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 OI(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 OI(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function S0(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+RV(e)}async function Yfe(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await nV(t,{...n,extractable:!0});return{publicWebKey:await RB(r),privateWebKey:await RB(i),alg:t,cfg:n}}async function C0(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await Yfe(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 TW({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 x0(e.context.adapter,t).createJwk(e,d)}async function w0(e,t,n){if(t?.jwt?.sign)return null;let r=x0(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new l(`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 l(`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 C0(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new l(`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 l(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await C0(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await EW({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new l(`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 QB(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function T0(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=S0(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 w0(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new NB(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 E0(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await T0(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 D0(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 Xfe(e,t,n){let r=$B(t),i=r.kid;if(!i)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let a=await x0(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 QB(JSON.parse(o.publicKey),s)}:(e.context.logger.debug(`No JWT algorithm available for cookie-cache JWT kid: ${i}`),null)}async function Zfe(e,t,n,r){let i=await w0(e,r);if(!i)throw new l("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new NB({...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(D0(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function Qfe(e,t,n){try{if($B(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await Xfe(e,t,n);if(!r)return null;let{payload:i}=await OB(t,r.publicKey,{...UV({issuer:D0(e)}),algorithms:[r.alg]}),a=WV(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 $fe(e){return{sign:(t,n,r)=>Zfe(t,n,r,e),verify:(t,n)=>Qfe(t,n,e)}}const epe={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 tpe(e,t){let n=PF();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(JV.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await x0(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 QB(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 OB(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 npe=D({payload:g(f(),ie()),overrideOptions:g(f(),ie()).optional()}),rpe=D({token:f(),issuer:f().optional()}),ipe=e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new l(`options.jwks.remoteUrl must be set when using options.jwt.sign`);if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new l(`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 l(`options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'`);return{id:`jwt`,version:`1.7.7`,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!==`jwt`)throw new l('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new l("`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:$fe(e)}}}},endpoints:{getJwks:J(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 c(`NOT_FOUND`);let n=x0(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await C0(t,e),r=await n.getAllKeys(t)),!r?.length)throw new l(`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,u=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??u,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:J(`/token`,{method:`GET`,requireHeaders:!0,use:[mH],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 E0(t,e);return t.json({token:n})}),signJWT:J.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:npe},async t=>{let n=await T0(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:n})}),verifyJWT:J.serverOnly({method:`POST`,metadata:{$Infer:{body:{},response:{}}},body:rpe},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await tpe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:RF(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await E0(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:YI(epe,e?.schema)}};var O0=Object.defineProperty,k0=(e,t)=>{let n={};for(var r in e)O0(n,r,{get:e[r],enumerable:!0});return t||O0(n,Symbol.toStringTag,{value:`Module`}),n};const A0=`ba_iat`,j0=`ba_pl`,M0=`ba_param`;function N0(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 ape(e){e.delete(M0);let t=[.../* @__PURE__ */ new Set([...e.keys(),M0])].sort();for(let n of t)e.append(M0,n)}function ope(e){let t=new URLSearchParams(e).get(A0);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const spe=[`authorization_code`,`client_credentials`,`refresh_token`],P0=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],cpe=[`none`,...P0],lpe=new Set(cpe);function F0(e,t){if(!(t.trim().length>0))throw new l(`OAuth Provider extension ${e} cannot be empty`)}function I0(e,t){F0(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new l(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function upe(e){I0(`grant type`,e)}function dpe(e){if(F0(`token_endpoint_auth_method`,e),lpe.has(e))throw new l(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function fpe(e){if(I0(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new l(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function ppe(e){let t=Object.keys(e.grants??{});for(let e of t)upe(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){dpe(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new l(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)fpe(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)F0(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function L0(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){if(n.has(r))throw new l(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function R0(e){let t=(e??[]).map(ppe);L0(`grant type`,t.flatMap(e=>e.grantTypes)),L0(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),L0(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),L0(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function z0(e){return e.extensions??[]}function B0(e){return z0(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function mpe(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new l(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];R0(i),n.options.extensions=i}function hpe(e){return z0(e).flatMap(e=>Object.keys(e.grants??{}))}function V0(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??spe,...hpe(e)]))}function gpe(e,t){for(let n of z0(e)){let e=n.grants?.[t];if(e)return e}}function H0(e){return z0(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function U0(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...P0,...H0(e)]))}function W0(e,t){return t?H0(e).includes(t):!1}function _pe(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of z0(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 G0(e,t,n,r){let i={...r};for(let a of z0(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 K0(e,t){let n={};for(let r of z0(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e)){if(t in n){xe.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`);continue}n[t]=r}}return n}function vpe(e,t){return K0(e,e=>e.claims?.accessToken?.(t))}function ype(e,t){return K0(e,e=>e.claims?.idToken?.(t))}function bpe(e,t){return K0(e,e=>e.claims?.userInfo?.(t))}function xpe(e){return z0(e).some(e=>e.claims?.userInfo)}function Spe(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Cpe(){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);return}return n}},set(t,n){e.set(t,n)}}}const q0=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new l(`jwt_config`);return t};function J0(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 wpe(e){if(e instanceof Date||!e||typeof e!=`object`)return J0(e);let t=J0(e.createdAt)??J0(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return J0(n.createdAt)??J0(n.created_at)}function Y0(e){if(typeof e==`string`)return[e];if(e?.length)return e}function X0(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const Z0=/* @__PURE__ */ new WeakMap;function Tpe(e){let t=Z0.get(e);if(t)return t;let n=Cpe();return Z0.set(e,n),n}async function Q0(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 OW(N0(n).toString(),t);return i.length===1&&!!r&&fU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}async function $0(e,t,n){let r=Tpe(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=B0(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 e2(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const t2=async e=>{let t=await CH(`SHA-256`).digest(new TextEncoder().encode(e));return YV.encode(new Uint8Array(t),{padding:!1})};async function n2(e,t,n){if(t===`encrypted`)return await EW({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new l(`Unsupported decryption storageMethod type '${t}'`)}async function Epe(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 d(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await t2(r):void 0;return!!e&&fU(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&&fU(e,n)}}if(i===`encrypted`)try{let t=await n2(e,i,n);return!!r&&fU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await n2(e,i,n);return!!r&&fU(t,r)}throw new l(`Unsupported verify storageMethod type '${i}'`)}async function r2(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await TW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await t2(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 l(`Unsupported storeClientSecret type '${r}'`)}async function i2(e=`hashed`,t,n){if(e===`hashed`)return await t2(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new l(`storeToken: unsupported storageMethod type '${e}'`)}async function a2(e=`hashed`,t,n){if(e===`hashed`)return await t2(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new l(`getStoredToken: unsupported storageMethod type '${e}'`)}const o2=/^Basic +/i,Dpe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Ope(e){return e.match(Dpe)?.[1]}const s2=[`client_secret`,`client_assertion`,`client_assertion_type`];function c2(e){throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function kpe(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&c2(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&c2(`${e} must be a string`),r[e]=t)};for(let e of s2)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&&c2(`client_id must not be repeated`),n=r[0];for(let e of s2){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&c2(`${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)&&c2(`A request must use only one client authentication method`),t.client_id=n;for(let e of s2)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Ape(e){if(o2.test(e))try{let{clientId:t,clientSecret:n}=ZW(e);return{client_id:t,client_secret:n}}catch{throw new d(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function l2(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 jpe(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new d(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function u2(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new d(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function d2(e,t,n,r,i,a,o,s){let c=await $0(e,t,n);c||u2(`missing client`,{method:s}),c.disabled&&u2(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&u2(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||W0(t,c.tokenEndpointAuthMethod))&&!a)throw new d(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&u2(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&u2(`public client, client secret should not be received`,{method:s}),r&&!await Epe(e,t,c.clientSecret,r)&&u2(`invalid client_secret`,{method:s})),jpe(c,i),o&&!l2(c,o))throw new d(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function f2(e){if(e)return typeof e==`string`?JSON.parse(e):e}function p2(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 m2(e,t,n){let r={...e.body??{}};await kpe(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 d(`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=_pe(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(()=>Xme).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&&!o2.test(i)){let e=Ope(i);if(!e)throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});u2(`unsupported authorization scheme`,{scheme:e})}if(i&&o2.test(i)){let e=Ape(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 h2(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 Mpe(e){let t=e.redirectUris?.[0];if(!t)throw new l(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function Npe(e,t,n){return OW(`${Mpe(t)}.${e}`,n)}async function g2(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Npe(e,t,n.pairwiseSecret):e}function _2(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 v2(e,t){if(!t)return!1;let n=J0(e);return n?n.getTime()>=t.getTime():!1}function y2(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 b2(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function x2(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 Ppe=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;function S2(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(`//`)&&Ppe.test(t)}const C2=p().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),C}if(oue.includes(n.protocol)){t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`});return}e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!XH(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`})}),Fpe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function w2(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e)){if(Fpe.has(r)){t.push(r);continue}n[r]=i}return t.length>0&&xe.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const T2=g(f(),se()).nullable(),Ipe=x({essential:T().optional(),value:f().optional(),values:_(f()).optional()}).nullable(),Lpe=D({acr:Ipe.optional()}).catchall(T2),Rpe=x({userinfo:g(f(),T2).optional(),id_token:Lpe.optional()});function zpe(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function E2(e){let t=zpe(e),n=Rpe.safeParse(t);return n.success?n.data:void 0}const D2=n([f(),g(f(),se())]),Bpe=D2,O2=D2.refine(e=>E2(e)!==void 0,{error:`claims must be a valid Claims request object`});function Vpe(e){return e===void 0||E2(e)!==void 0}function k2(e,t){let n=E2(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 Hpe(e,t){let n=E2(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 Upe(e,t){let n=E2(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 A2(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const j2={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>A2(e.name).given},family_name:{scope:`profile`,resolve:e=>A2(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},M2=Object.keys(j2);function N2(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const Wpe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function Gpe(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e)){if(Wpe.has(r)){t.push(r);continue}n[r]=i}return t.length>0&&xe.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function P2(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 vpe(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 Gpe({...p,...d??{},...m,...f})}const F2=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],Kpe=new Set(F2);async function I2(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r;try{r=new URL(t)}catch{return{ok:!1,reason:`resource identifier ${t} must be an absolute URI (RFC 8707 §2)`}}return r.hash?{ok:!1,reason:`resource identifier ${t} must not contain a URI fragment (RFC 8707 §2)`}:{ok:!0}}async function qpe(e,t){let n=await I2(e,t);if(!n.ok)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const Jpe=e=>`${e}/oauth2/userinfo`;async function Ype(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 Xpe(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 L2(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=>H2(e,t,n)))).every(Boolean)}async function R2(e,t,n){let r=Xpe(n.resource),i=n.requestedScopes.includes(`openid`),a=Jpe(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 H2(e,t,n);if(r){if(r.disabled)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r);continue}throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:l}=z2(t);l&&s.length>0&&await Zpe(e,t,n.clientId,s);let u=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=u.filter(e=>t.has(e));if(n.length===0)throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});u=n}let d=null,f=null;for(let e of s)e.accessTokenTtl!=null&&(d=d===null?e.accessTokenTtl:Math.min(d,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(f=f===null?e.refreshTokenTtl:Math.min(f,e.refreshTokenTtl));let p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Set;for(let e of s)e.signingAlgorithm&&p.add(e.signingAlgorithm),e.signingKeyId&&m.add(e.signingKeyId);if(p.size>1)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(m.size>1)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let h=p.values().next().value??null,g=m.values().next().value??null,_={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(_,e.customClaims);let v=s.some(e=>e.dpopBoundAccessTokensRequired===!0),y=i?[...o,a]:o,b=[...new Set(y)];return{audienceClaim:b.length===1?b[0]:b,accessTokenTtl:d,refreshTokenTtl:f,signingAlgorithm:h,signingKeyId:g,rawCustomClaims:_,dpopBoundAccessTokensRequired:v,effectiveScopes:u}}async function Zpe(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 c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function Qpe(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 $pe(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 z2(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const B2=/* @__PURE__ */ new Map;function V2(e){if(e===void 0){B2.clear();return}B2.delete(e)}async function H2(e,t,n){if(await ime(e.context,t),t.cachedResources?.has(n)){let e=B2.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)&&B2.set(n,Object.assign({},r)),r}function eme(e){return e.name??e.identifier}function tme(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function U2(e,t){return{identifier:e.identifier,name:eme(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 nme(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=U2(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 W2=/no such table|relation.*does not exist|table.*does(?: not|n[''']?t) exist/i;let G2=/* @__PURE__ */ new WeakMap;function rme(e){let t=e.adapter,n=G2.get(t);if(n)return n;let r={completed:!1,promise:null};return G2.set(t,r),r}async function K2(e,t){let n=tme(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 I2(t,a.identifier);if(!n.ok){xe.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!Kpe.has(o.signingAlgorithm)){xe.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${F2.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s;try{s=await e.adapter.findOne({model:i,where:[{field:`identifier`,value:o.identifier}]})}catch(e){let t=e instanceof Error?e.message:String(e);if(W2.test(t)){xe.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`);return}throw e}let c=/* @__PURE__ */ new Date;if(!s){try{await e.adapter.create({model:i,data:U2(o,c)})}catch(e){let t=e instanceof Error?e.message:String(e);if(/unique|duplicate|UNIQUE/i.test(t)){xe.debug(`oauth-provider: resource ${o.identifier} already inserted by a concurrent process — skipping.`);continue}if(W2.test(t)){xe.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`);return}throw e}continue}r!==`insertOnly`&&await e.adapter.update({model:i,where:[{field:`identifier`,value:o.identifier}],update:nme(o,r,c)})}}async function ime(e,t){let n=rme(e);if(n.completed!==!0)return n.promise===null&&(n.promise=K2(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function ame(e){let t=z2(e);xe.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function q2(e){return e.headers?.get(`dpop`)??void 0}function J2(e,t){return e.request?.url??`${e.context.baseURL}${t}`}const ome=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function Y2(e){return ome.has(e)}function X2(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function Z2(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new c(`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)||Y2(e));if(a.length>0)throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}const sme=[`javascript:`,`data:`,`vbscript:`],Q2=f().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),C;if(e.includes(`#`)){t.addIssue({code:`custom`,message:`resource must not contain a fragment`});return}sme.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),cme=E([`none`,`consent`,`login`,`create`,`select_account`]),lme=f().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`});return}for(let e of n){let n=cme.safeParse(e);if(!n.success){t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`});continue}r.add(n.data)}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}),$2=D({keys:_(g(f(),se())).min(1)}),ume=n([m(),f().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`}),C):n}),dme=f().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),e4=D({response_type:f().pipe(E([`code`])).optional(),request:f().optional(),request_uri:f().optional(),redirect_uri:C2.optional(),scope:f().optional(),state:f().optional(),client_id:f().min(1,`client_id is required`),prompt:lme.optional(),display:f().optional(),ui_locales:f().optional(),max_age:ume.optional(),acr_values:f().optional(),login_hint:f().optional(),id_token_hint:f().optional(),code_challenge:f().optional(),code_challenge_method:f().pipe(E([`S256`])).optional(),nonce:f().optional(),claims:Bpe.optional(),dpop_jkt:dme.optional(),resource:n([Q2,_(Q2).min(1)]).optional()}).passthrough(),fme=e4.extend({redirect_uri:C2.optional(),claims:O2.optional()}),pme=D({type:ee(`authorization_code`),query:fme,sessionId:f(),userId:f(),referenceId:f().optional(),authTime:m().optional(),resource:_(f()).optional()}).passthrough(),t4=D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:f().trim().min(1).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:_(f().trim().min(1)).min(1).optional(),response_types:_(E([`code`])).optional(),application_type:E([`web`,`native`]).optional(),subject_type:E([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:T().optional(),resources:_(Q2).optional(),skip_consent:b({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),mme=t4.omit({skip_consent:!0}).extend({client_id:f().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:f().optional(),client_secret_expires_at:m().int().nonnegative().optional(),client_id_issued_at:m().int().nonnegative().optional()}).loose();function hme(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(j2))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function n4(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 gme(e){let t=e.headers?.get(`authorization`),n=eK(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new c(`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 _me(e,t){let{authorization:n}=gme(e);if(!n?.token)throw new c(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await w4(e,t,n.token);if(oK(r)&&!e.request)throw new c(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await gK({payload:r,authorization:n,proofJwt:q2(e),method:e.request?.method??`GET`,url:J2(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZG(e.context.internalAdapter)})}catch(e){throw hK(e)?new c(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new c(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=hme(o,a??[],i),l=r.client_id??r.azp,u=l&&(t.pairwiseSecret||xpe(t))?await $0(e,t,l):void 0;t.pairwiseSecret&&u&&(s.sub=await g2(o.id,u,t));let d=a?.length?await bpe(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:u??void 0,requestedClaims:i}):{},f=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...n4(d,s),...n4(f),sub:s.sub}}const vme=Object.fromEntries(M2.map(e=>[e,void 0]));function r4(e){return aK(e)?`DPoP`:`Bearer`}async function yme(e,t){let n=e.body.grant_type;if(!V0(t).includes(n))throw new c(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return Bme(e,t);case`client_credentials`:return Vme(e,t);case`refresh_token`:return Hme(e,t);default:{let r=gpe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:bme(e,t,n)});throw new c(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function bme(e,t,n){return{getClient:n=>$0(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:l}=p2(await m2(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new c(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await d2(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:l}},issueTokens:r=>{if(!n)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return g4(e,t,{...r,grantType:n})},hashToken:(e,n)=>i2(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>_4);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>_4);return i(e,t,n,r)}}}async function xme(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=q0(e.context).options,u=n?.id??r.clientId;return T0(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:X0(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:yU(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function Sme(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 cR(r.slice(0,r.length/2))}async function Cme(e,t,n,r,i,a,o,s,l,u){let d=Math.floor(Date.now()/1e3),f=d+(t.idTokenExpiresIn??36e3),p=await g2(n.id,r,t),m=s==null?void 0:Math.floor(s.getTime()/1e3),h=w2(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:f2(r.metadata)}):void 0),g=t.disableJwtPlugin?void 0:q0(e.context).options,_=!t.disableJwtPlugin&&!g?.jwt?.sign?await w0(e,g):void 0,v=t.disableJwtPlugin?`HS256`:_?.alg??g?.jwks?.keyPairConfig?.alg,y=l?await Sme(l,v):void 0,b=!!(r.enableEndSession||r.backchannelLogoutUri),x={...vme,auth_time:m,acr:`0`,...h,at_hash:y,iss:g?.jwt?.issuer??e.context.baseURL,sub:p,aud:r.clientId,nonce:a,iat:d,exp:f,sid:b?o:void 0},S=w2(u);if(Object.assign(x,n4(S,x)),t.disableJwtPlugin&&!r.clientSecret)return;let C=t.disableJwtPlugin?await new NB(x).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await n2(e,t.storeClientSecret,r.clientSecret))):await T0(e,{options:g,payload:x,resolvedKey:_??void 0});if(C&&y&&g?.jwt?.sign){let e=$B(C);if(e.alg!==v)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${v}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return C}async function i4(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function a4(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new c(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function wme(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():yU(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await i2(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 o4(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 Tme(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 s4(e,t,n,r,i,a,o,s,l,u,d,f,p){let m=s.iat??Math.floor(Date.now()/1e3),h=s?.exp??m+(t.refreshTokenExpiresIn??2592e3),g=t.generateRefreshToken?await t.generateRefreshToken():yU(32,`A-Z`,`a-z`),_=s?.sid,v={token:await i2(t.storeTokens,g,`refresh_token`),clientId:a.clientId,sessionId:_,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:u,confirmation:f,requestedUserInfoClaims:p?.length?p:void 0,scopes:o,resources:d,createdAt:/* @__PURE__ */ new Date(m*1e3),expiresAt:/* @__PURE__ */ new Date(h*1e3)};if(!l?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await i4(t,g,_)};let y=/* @__PURE__ */ new Date(m*1e3),b={revoked:y,rotatedAt:y},x=t.refreshTokenReuseInterval??0;if(x>0&&(b.rotationReplayExpiresAt=/* @__PURE__ */ new Date((m+x)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:l.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:b}))throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await i4(t,g,_)}}async function c4(e,t,n){let r=await R2(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 l4(e){throw new c(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Eme(e){let t=f2(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function u4(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=aK(n.refreshToken?.confirmation),a=i??r,o=q2(e),s=Eme(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o){s&&l4(`DPoP proof header is required`);return}try{return{jkt:(await pK({proofJwt:o,method:`POST`,url:J2(e,`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZG(e.context.internalAdapter)})).jkt}}catch(e){throw $G(e)&&l4(e.message),e}}function d4(e){return e?[...new Set(e)].sort():void 0}function f4(e,t){let n=d4(e),r=d4(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function p4(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Dme(e,t){return p4(e)===p4(t)}function Ome(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 kme(e){return e===`Bearer`||e===`DPoP`}function Ame(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`&&kme(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 jme(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||Ome(n.confirmation))&&Ame(t.response)}function m4(e){let t=d4(e.requestedResources);return{effectiveScopes:d4(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function Mme(e,t){return f4(e.effectiveScopes,t.effectiveScopes)&&f4(e.requestedResources,t.requestedResources)&&Dme(e.confirmation,t.confirmation)}async function Nme(e,t){return TW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Pme(e,t){let n=await EW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(jme(r))return r}function h4(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function Fme(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 Nme(e,{request:r,response:i})}})}async function Ime(e,t,n){if(h4(t)&&t.rotationReplayResponse)try{let r=await Pme(e,t.rotationReplayResponse);return!r||!Mme(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Lme(e,t,n){let r=Math.floor(Date.now()/1e3),i=await c4(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await u4(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return m4({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function Rme(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function g4(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]?S0(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await c4(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&&l2(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,C=a&&v.includes(`openid`),w=f2(r.metadata),T=C&&a?{...await ype(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:w}),...n.idTokenClaims??{}}:void 0,ee=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:w,verificationValue:f}):void 0,te=g.refreshResources,E=n.confirmation??await u4(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),ne=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],re=x&&a&&!S?await s4(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,te,E,ne):void 0,ie=S?await P2({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:w,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[ae,oe]=await Promise.all([S?xme(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ie,confirmation:E}):wme(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,re?.id,E,ne),re||(x&&a?s4(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,te,E,ne):void 0)]),D=C?await Cme(e,t,a,r,v,l,c,d,ae,T):void 0,se={...ee,...n.tokenResponse??{},access_token:ae,expires_in:y-p,expires_at:y,token_type:r4(E),refresh_token:oe?.token,scope:v.join(` `),id_token:D};if(u?.id&&oe?.id)try{await Fme(e,t,u,m4({effectiveScopes:v,requestedResources:n.resources,confirmation:E}),se)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(se)}async function zme(e,t,n,r,i,a){let o=await i2(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await Tme(e,o),new c(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let l;try{l=JSON.parse(s.value)}catch{throw new c(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let u=pme.safeParse(l);if(!u.success)throw new c(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let d=u.data;if(d.query.client_id!==r)throw new c(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let f=d.query.redirect_uri;if(f){if(!i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(f!==i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let p=Y0(d.resource)??Y0(d.query.resource),m=a??p;if(a&&p){let e=new Set(a),t=new Set(p);for(let n of e)if(!t.has(n))throw new c(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:d,effectiveResources:m,authorizedResources:p,authorizationCodeId:o}}async function Bme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:l,resource:u}=e.body,d=Y0(u);if(!n)throw new c(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new c(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let f=n&&r,p=n&&o&&s;if(!f&&!p&&!i)throw new c(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await zme(e,t,o,n,l,d),v=m.query.scope?.split(` `);if(!v)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});let y=await d2(e,t,n,r,v,i,`authorization_code`,a);if(x2(y,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!p)throw new c(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(p||f||i))throw new c(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let b=!!m.query?.code_challenge,x=!!s;if(b||x){if(b&&!x)throw new c(`UNAUTHORIZED`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!b&&x)throw new c(`UNAUTHORIZED`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await HW(s):void 0)!==m.query?.code_challenge)throw new c(`UNAUTHORIZED`,{error_description:`code verification failed`,error:`invalid_request`})}if(!m.userId)throw new c(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.internalAdapter.findUserById(m.userId);if(!S)throw new c(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let C=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!C||C.expiresAt</* @__PURE__ */ new Date)throw new c(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let w=m.authTime==null?wpe(C):J0(m.authTime),T=k2(m.query.claims,N2(t));return g4(e,t,{client:y,scopes:m.query.scope?.split(` `)??[],user:S,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:C.id,nonce:m.query?.nonce,authTime:w,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:T,resources:h,originalResources:g})}async function Vme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,l=Y0(s);if(!n)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let u=await d2(e,t,n,r,void 0,i,`client_credentials`,a);if(u.tokenEndpointAuthMethod===`none`)throw new c(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let d=u.clientCredentialsScopes;if(!d?.length)throw new c(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let f=o?.split(` `);if(f){let e=new Set(d),t=f.filter(t=>!e.has(t)||Y2(t));if(t.length)throw new c(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return f||=[...d],g4(e,t,{client:u,scopes:f,grantType:`client_credentials`,resources:l})}async function Hme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:l}=e.body,u=Y0(l);if(!n)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new c(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let d=await a4(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,d.token,`refresh_token`)}]});if(!f)throw new c(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(f.clientId!==n||f.expiresAt</* @__PURE__ */ new Date)throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(u&&f.resources&&!u.every(e=>f.resources?.includes(e)))throw new c(`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 c(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}let h=await d2(e,t,n,r,m??p,i,`refresh_token`,a);if(f.revoked){if(h4(f)){let n=await Ime(e,f,await Lme(e,t,{client:h,refreshToken:f,scopes:m??p,resources:u??f.resources}));if(n)return Rme(e,n);throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await o4(e,n,f.userId),new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let g=await e.context.internalAdapter.findUserById(f.userId);if(!g)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let _=f.authTime==null?void 0:J0(f.authTime);return g4(e,t,{client:h,scopes:m??p,user:g,grantType:`refresh_token`,referenceId:f.referenceId,authorizationCodeId:f.authorizationCodeId,sessionId:f.sessionId,refreshToken:f,resources:u??f.resources,authTime:_,requestedUserInfoClaims:f.requestedUserInfoClaims})}var _4=/* @__PURE__ */ k0({introspectEndpoint:()=>E4,requireActiveAccessToken:()=>Yme,requireActiveAccessTokenWithClaims:()=>w4,validateAccessToken:()=>C4});const v4=`Invalid access token`,Ume=`Bearer error="invalid_token", error_description="${v4}"`;function y4(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function Wme(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function b4(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&Qpe(e,t,r,a)}async function Gme(e,t,n,r){let i=t.disableJwtPlugin?void 0:q0(e.context),a=i?.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await OB(n,UB(await kK(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 Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new d(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return{active:!1};throw e}throw Error(e)}let l=c.aud;if(!await L2(e,t,l,[o])||!c.azp)return{active:!1};let u=await $0(e,t,c.azp);if(!u||u?.disabled||!await b4(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:Wme(l,o)}))return{active:!1};let f=c.sid;if(f){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:f}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=r4(c.cnf),c}async function Kme(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 d(`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 a2(t.storeTokens,i,`access_token`)}]});if(!a)throw new d(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_token`});if(!a.expiresAt||a.expiresAt</* @__PURE__ */ new Date||a.revoked)return y4();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await $0(e,t,a.clientId),!s||s?.disabled||!await b4(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return y4();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 y4()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await L2(e,t,o,[u]))return y4();let f=o?[...o]:void 0;f?.length&&a.scopes?.includes(`openid`)&&(f.includes(u)||f.push(u));let p=o?.length?await $pe(e,t,o):{},m=s?await P2({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:f2(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:p}):{},h=(t.disableJwtPlugin?void 0:q0(e.context))?.options;return{payload:{...m,active:!0,iss:h?.jwt?.issuer??e.context.baseURL,aud:X0(f),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:r4(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function qme(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new d(`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:q0(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:r4(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function x4(){return new d(`UNAUTHORIZED`,{error_description:v4,error:`invalid_token`},{"WWW-Authenticate":Ume})}function Jme(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function S4(e,t,n,r){try{return{payload:await Gme(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(e)}try{return await Kme(e,t,n,r)}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw x4()}async function C4(e,t,n,r){return(await S4(e,t,n,r)).payload}async function Yme(e,t,n,r){let i=await C4(e,t,n,r);if(i.active)return i;throw x4()}async function w4(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await S4(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw x4()}async function T4(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 $0(e,t,i);if(!a)return n;let o=await g2(n.sub,a,t);return{...n,sub:o}}async function E4(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}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new d(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=tK(n)),!n?.length)throw new d(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await d2(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return T4(e,t,await C4(e,t,n,c.clientId),c)}catch(e){if(e instanceof d){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 T4(e,t,await qme(e,t,(await a4(t,n)).token,c.clientId),c)}catch(e){if(e instanceof d){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof d){if(Jme(e))return{active:!1};throw e}throw e instanceof Error?(xe.error(`Introspection error:`,e.message,e.stack),new d(`INTERNAL_SERVER_ERROR`)):(xe.error(`Introspection error:`,e),new d(`INTERNAL_SERVER_ERROR`))}}function D4(e){return e?.get(`sec-fetch-mode`)===`cors`}var Xme=/* @__PURE__ */ e({a:()=>k3,c:()=>a3,d:()=>X4,f:()=>J4,h:()=>Y4,i:()=>X3,l:()=>i3,n:()=>W3,o:()=>khe,r:()=>q3,s:()=>_3,t:()=>n6,u:()=>K4});async function Zme(e,t,n){let r=await K3.get(),i=r?.query;if(!i)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `)??[],s=N2(t),l=k2(a.get(`claims`),s),u=a.get(`client_id`);if(!u)throw new c(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let d=e.body.scope?.split(` `);if(d&&!d.every(e=>o?.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let f=e.body.claims,p=f===void 0?l:k2(f,s);if(f!==void 0&&!p.every(e=>l.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});if(e.body.accept!==!0)return{redirect:!0,url:Z3(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,n6(e,t))};let m=await fH(e),h=h2(a.get(`prompt`)??``).has(`login`),g=h&&v2(m?.session.createdAt,r?.signedQueryIssuedAt);if(h&&!g)return e?.headers?.set(`accept`,`application/json`),e.query=_2(a),await n(e);let _=await t.postLogin?.consentReferenceId?.({user:m?.user,session:m?.session,scopes:d??o}),v=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:u},{field:`userId`,value:m?.user.id},..._?[{field:`referenceId`,value:_}]:[]]}),y=Math.floor(Date.now()/1e3),b=a.getAll(`resource`),x={clientId:u,userId:m?.user.id,scopes:d??o,requestedUserInfoClaims:p,createdAt:/* @__PURE__ */ new Date(y*1e3),updatedAt:/* @__PURE__ */ new Date(y*1e3),resources:b.length?b:void 0,referenceId:_};if(v?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:v.id}],update:{resources:x.resources,scopes:x.scopes,requestedUserInfoClaims:x.requestedUserInfoClaims,updatedAt:/* @__PURE__ */ new Date(y*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...x,scopes:x.scopes}}),d&&a.set(`scope`,x.scopes.join(` `)),f!==void 0){let e=Upe(a.get(`claims`),p);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let S=y2(a,`consent`);return g&&(S=y2(S,`login`),S=b2(S)),e.query=_2(S),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===m?.session.id})}async function Qme(e,t){if(e.body.selected===!0)return await $me(e,t);if(e.body.created===!0)return await ehe(e,t);if(e.body.postLogin===!0)return await the(e,t);throw new c(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function $me(e,t){let n=(await K3.get())?.query;if(!n)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=_2(y2(new URLSearchParams(n),`select_account`)),await t(e)}async function ehe(e,t){let n=(await K3.get())?.query;if(!n)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=_2(y2(r,`create`)),await t(e)}async function the(e,t){let n=await K3.get(),r=n?.query;if(!r)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=_2(i);let a=await fH(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id})}async function nhe(e,t,n,r){return T0(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function rhe(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await OI(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 g2(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 ihe(e,t){let n=/* @__PURE__ */ new Date,r=await OI(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 ahe(e,t)}async function ahe(e,t){let n=e.context.logger,r=q0(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 w0(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=yU(32,`a-z`,`A-Z`,`0-9`),d=await nhe(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 O4(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function k4(e){let t=e.request?.headers??e.headers;if(!t||D4(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 A4(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${O4(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 j4(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function ohe(e){try{return new URL(j4(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function M4(e){return A4(`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="${O4(j4(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function N4(e){return A4(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${O4(e)}`:`Logged out.`}</p></main>`)}function she(e,t){return A4(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${O4(e)}</p></main>`,t)}function P4(e,t,n,r){if(k4(e))return she(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new d(t,{error:n,error_description:r})}function F4(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function I4(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:ohe(e),sameSite:`lax`}}async function L4(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(F4(e),JSON.stringify(r),e.context.secret,I4(e,300))}async function che(e){let t=await e.getSignedCookie(F4(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 R4(e){e.setCookie(F4(e),``,I4(e,0))}async function z4(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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function lhe(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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function B4(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new d(`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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function V4(e,t,n){try{return await $0(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function H4(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function uhe(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=H4(e.aud);return t.length===1?t[0]:null}async function dhe(e,t,n,r){if(r)return V4(e,t,r);let i;try{i=eV(n)}catch{return null}let a=uhe(i);return a?V4(e,t,a):null}async function fhe(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await n2(e,t.storeClientSecret,r.clientSecret),{payload:o}=await sB(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=q0(e.context).options,{payload:r}=await sB(n,UB(await kK(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==n6(e,t)||!H4(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 U4(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 W4(e,t){return t.post_logout_redirect_uri?U4(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 phe(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await V4(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:U4(r,n.postLogoutRedirectUri,n.state)}async function G4(e,t,n={}){return t?k4(e)?(await L4(e,t.session.id,n),M4(e)):P4(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):k4(e)?(await L4(e,void 0,n),M4(e)):P4(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function mhe(e,t){let n=await che(e),r=await z4(e);if(!n||n.expiresAt<=Date.now())return P4(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await phe(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?P4(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await B4(e,r.session),lH(e),R4(e),i.uri?$3(e,i.uri):k4(e)?N4(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(R4(e),i.uri?$3(e,i.uri):k4(e)?N4(i.invalid?`The requested post-logout redirect was not registered.`:void 0):P4(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function hhe(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await z4(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await V4(e,t,i.client_id);if(!r)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return P4(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=W4(r,i)}return G4(e,a,n)}let o=await dhe(e,t,i.id_token_hint,i.client_id);if(!o)return a&&k4(e)?G4(e,a):P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return P4(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await fhe(e,t,i.id_token_hint,o);if(!s)return a&&k4(e)?G4(e,a,i.client_id?W4(o,i):{}):P4(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await lhe(e,c),u=a?.session.id===c;if(a&&!u)return G4(e,a,W4(o,i));let d=U4(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await B4(e,f),u&&lH(e),R4(e),d.uri?$3(e,d.uri):k4(e)?N4(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function ghe(e,t){return mhe(e,t)}function K4(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:t6(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:[...QW],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:[...QW],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:[...QW],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...YG],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function q4(e,t){let n=t.disableJwtPlugin?void 0:q0(e.context).options,r=B0(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:K4(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:V0(t),token_endpoint_auth_methods_supported:U0(t,{includeNone:i}),endpoint_auth_methods_supported:U0(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function J4(e,t){let{clientDiscoveries:n,authMetadata:r}=q4(e,t);return G0(e,t,`oauth-authorization-server`,{...e2(n),...r})}function Y4(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=q4(e,t),o={...a,claims_supported:N2(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 G0(e,t,`openid-configuration`,{...e2(i),...o})}function X4(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 Z4(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,...s}=t;if(!r)return J(e,{...s,onValidationError:async e=>{throw i&&await i(e),new d(`BAD_REQUEST`,{...Q4(e.issues,a,o)})}},n);let c=r,{body:l,query:u,...f}=s;async function p(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({...Q4(r.error.issues,a,o),ctx:e})})}return J(e,f,async e=>{let t=await p(e,`body`,l);if(!t.ok)return t.response;let r=await p(e,`query`,u);return r.ok?n(e):r.response})}function Q4(e,n,r=`invalid_request`){let i=e[0];if(!i)return{error:r,error_description:`Invalid request.`};let a=i.path?.[0],o=typeof a==`string`?a:void 0,s=o?n?.[o]:void 0,c=i.path?.length?t(i.path):``;return{error:_he(i,s,r),error_description:yhe(i,c)}}function _he(e,t,n){return typeof t==`string`?t:vhe(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function vhe(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function yhe(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 bhe=e=>RF(async t=>{if(!e.allowPublicClientPrelogin)throw new c(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await Q0(n,t.context.secret))throw new c(`UNAUTHORIZED`,{error:`invalid_signature`})}),$4={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},xhe=[`Ed25519`],She=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function e3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t3(e,t){return typeof e[t]==`string`&&e[t].length>0}function n3(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($4,e)}function r3(e){return xhe.some(t=>t===e)}function Che(e){switch(e.kty){case`RSA`:return t3(e,`n`)&&t3(e,`e`);case`EC`:return n3(e.crv)&&t3(e,`x`)&&t3(e,`y`);case`OKP`:return r3(e.crv)&&t3(e,`x`);default:return!1}}function whe(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!QW.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return n3(e.crv)&&$4[e.crv]===e.alg;case`OKP`:return r3(e.crv)&&e.alg===`EdDSA`;default:return!1}}function i3(e){let t=e3(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(!e3(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||She.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!Che(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!whe(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}}}const The=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})),Ehe=/* @__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(`.`),Dhe=/* @__PURE__ */ new Set([...The,...Ehe,`public`,`type`,`resources`,`client_credentials_scopes`]),Ohe=/* @__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 a3(e){return Ohe.has(e)}function o3(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!Dhe.has(e)))}async function s3(e,t,n,r){if(!t)throw new c(`UNAUTHORIZED`);if(!e.headers)throw new c(`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}))throw new c(`UNAUTHORIZED`)}var khe=/* @__PURE__ */ k0({consumeClientAssertion:()=>_3,isPrivateHostname:()=>m3,verifyClientAssertion:()=>Ihe});const c3=/* @__PURE__ */ new WeakMap,l3=65536,Ahe=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function u3(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 d3(e){let t=c3.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return c3.set(e,n),n}function f3(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const p3=[...QW];function m3(e){return!ZH(e)}function jhe(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(m3(r.hostname))throw new d(`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 d(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function Mhe(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function Nhe(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>l3)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>l3)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 h3(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||!Ahe.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await Nhe(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=i3(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function g3(){return new d(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function Phe(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new d(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?B0(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new d(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});jhe(e,n.jwksUri,n.clientDiscoveryId?Mhe(n.clientId):void 0);let i=Date.now(),a=f3(n),o=d3(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await h3(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw g3()}if(!c.valid)throw g3();return u3(o,a,c.jwks,i),c.jwks}async function Fhe(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?B0(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await h3(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(u3(d3(e),f3(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function _3(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 d(`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 d(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new d(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new d(`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 d(`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 d(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await CH(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=YV.encode(new Uint8Array(c).slice(0,24),{padding:!1});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 d(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function Ihe(e,t,n,r,i,a){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new d(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let o;try{o=$B(n)}catch{throw new d(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!o.alg||!p3.includes(o.alg))throw new d(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${o.alg}`,error:`invalid_client`});let s;try{s=eV(n)}catch{throw new d(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let c=s.sub??s.iss;if(!c)throw new d(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==c)throw new d(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let l=await $0(e,t,c);if(!l)throw new d(`BAD_REQUEST`,{error_description:`unknown client`,error:`invalid_client`});if(l.disabled)throw new d(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(l.tokenEndpointAuthMethod!==`private_key_jwt`)throw new d(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});let u=await Phe(e,t,l),f=a??`${e.context.baseURL}/oauth2/token`,p=n6(e,t),m=[.../* @__PURE__ */ new Set([f,p])],h={issuer:c,subject:c,audience:m,algorithms:p3},g;try{({payload:g}=await OB(n,UB(u),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await Fhe(t,l);if(e)try{({payload:g}=await OB(n,UB(e),h))}catch{throw new d(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new d(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new d(`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 _3(e,t,{namespace:`private_key_jwt:${c}`,payload:g,expectedAudience:_}),{clientId:c}}function v3(e,t,n){return new d(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...IF})}async function Lhe(e,t,n){let r=e.headers,i;try{i=Spe(r?.get(`authorization`))}catch{throw v3(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw v3(`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 d?e:new d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw v3(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const Rhe=[`authorization_code`];function y3(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function b3(e){let t=e.grant_types??[...Rhe];if(t.length>0)return t;throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function zhe(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function x3(e,t=`web`){let n=b3(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:zhe(e,n)}}const Bhe=/* @__PURE__ */ new Set([`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`]);function S3(e){throw new c(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function Vhe(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()}async function Hhe(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=/* @__PURE__ */ new Set([...r,...t.clientRegistrationAllowedResources??[]]);for(let e of n)if(!i.has(e))throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`});let a=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of a){let r=await H2(e,t,n);if(!r)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return a}function Uhe(e,t){let n;try{n=new URL(e)}catch{S3(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&S3(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&S3(`redirect URI localhost must not include trailing dots: ${e}`);let a=YH(n.hostname)||n.hostname===`localhost`,o=Vhe(e),s=o===`localhost`||o===`127.0.0.1`||o===`[::1]`;if(t===`web`){(!i||a)&&S3(`web clients require https redirect URIs on non-loopback hosts: ${e}`);return}if(i){a&&S3(`native clients must not use https loopback redirect URIs: ${e}`);return}if(r){s||S3(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`);return}(Bhe.has(n.protocol)||!S2(n))&&S3(`native private-use redirect URI schemes must be well-formed reverse-domain names, omit the naming authority, and must not use a reserved scheme: ${e}`)}function Whe(e){let t=i3(e);if(!t.valid)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}async function Ghe(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new c(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await fH(e),i=r?void 0:await Lhe(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new c(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...IF});if(!r&&!a&&n.grant_types?.includes(`client_credentials`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let o=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];r&&await s3(e,r,t,`create`);let s=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),l=await O3(e,t,{metadata:n,registrationSource:`dynamic`,userId:s?void 0:r?.session.userId,referenceId:s,requestedResources:o});return e.setStatus(201),e.json(l)}async function C3(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=x3(e,r?null:`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(U0(t,{includeNone:!0})).has(a))throw new c(`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 c(`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,l=i.application_type;if(l!==void 0&&l!==`web`&&l!==`native`)throw new c(`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 c(`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??[])Uhe(e,l??(r?`native`:`web`));let u=new Set(V0(t));if(r){if(!o.some(e=>u.has(e)))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${o.join(`, `)}`})}else for(let e of o)if(!u.has(e))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${e}`});if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});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 c(`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 d=(i?.scope)?.split(` `).filter(e=>e.length),f=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,p=f?y3(t):t.scopes;if(p){let e=new Set(p);for(let t of d??[])if(!e?.has(t))throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(f&&i.require_pkce===!1)throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(m3(e.hostname))throw new c(`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 c(`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 c?e:new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&Whe(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must be an absolute URL`})}if(i.backchannel_logout_uri.includes(`#`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not include a fragment component`});if(e.protocol!==`https:`)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must use https`});if(e.username||e.password)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not contain credentials`});if(m3(e.hostname))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not point to a private or reserved address`})}}const w3=Symbol(`client-registration-collision`);function T3(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[w3]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function E3(e,t,n){let r=x3(n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,n.registrationSource===`clientMetadataDocument`?null:`web`),i=r.token_endpoint_auth_method===`none`,a=r.token_endpoint_auth_method===`private_key_jwt`,o=W0(t,r.token_endpoint_auth_method);await C3(r,t,{registrationSource:n.registrationSource,ctx:e});let s=n.clientId??t.generateClientId?.()??yU(32,`a-z`,`A-Z`),l=i||a||o?void 0:t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`),u=l?await r2(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!i&&t.clientRegistrationRequirePKCE===!1,f=r.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...r,scope:y3(t).join(` `)}:r,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=M3({...h,redirect_uris:r.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?S0(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:s,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`&&r.application_type===void 0&&(_.applicationType=null);let v=await Hhe(e,t,n.registrationSource===`dynamic`?n.requestedResources??[]:[]),y=t.schema?.oauthClient?.modelName??`oauthClient`,b=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,x=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,S=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,C=await kI(e.context.adapter,async()=>{let t=await OI(e.context.adapter),r,i=!1;if(x){let e=await t.update({model:y,where:[{field:`clientId`,value:s},{field:`clientDiscoveryId`,value:S}],update:{..._,disabled:x.disabled,skipConsent:x.skipConsent,enableEndSession:x.enableEndSession,createdAt:x.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!e)throw new c(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=e}else{try{r=await t.create({model:y,data:{..._,createdAt:/* @__PURE__ */ new Date(p*1e3),updatedAt:/* @__PURE__ */ new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&A3(e)?{[w3]:!0,kind:`oauth-client-row-unique`,clientId:s,cause:e}:e}i=!0}let a=v.length===0?[]:await t.findMany({model:b,where:[{field:`clientId`,value:s}]}),o=new Set(a.map(e=>e.resourceId)),l=/* @__PURE__ */ new Date;for(let e of v)if(!o.has(e))try{await t.create({model:b,data:{clientId:s,resourceId:e,createdAt:l}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&A3(t)?{[w3]:!0,kind:`oauth-client-resource-link-unique`,clientId:s,resourceId:e,cause:t}:t}return{client:r,created:i}});return{client:C.client,clientSecret:l,resources:v,created:C.created}}function D3(e,t){let n=N3({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function Khe(e,t){return{...D3(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function O3(e,t,n){return D3(await E3(e,t,n),t)}async function qhe(e,t,n){return Khe(await E3(e,t,n),t)}function Jhe(e,t){if(e&&e.clientDiscoveryId!==t)throw new c(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}async function k3(e,t,n){if(Jhe(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new c(`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 c(`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 E3(e,t,r)}catch(i){if(!T3(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 E3(e,t,{...r,existingClient:s})}catch(e){throw T3(e)?e.cause:e}}}function A3(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 j3(e,t,n){let r=await fH(e);if(await s3(e,r,t,`create`),!r)throw new c(`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?X2(a??[]):[];Z2(s,b3(o),o.token_endpoint_auth_method,t),s.length>0&&await s3(e,r,t,`configure-client-credentials-scopes`);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s},u=n?.admin?await qhe(e,t,l):await O3(e,t,l);return e.setStatus(201),e.json(u)}function M3(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:C,response_types:w,application_type:T,disabled:ee,skip_consent:te,enable_end_session:E,require_pkce:ne,dpop_bound_access_tokens:re,subject_type:ie,reference_id:ae,metadata:oe}=e,D=r?/* @__PURE__ */ new Date(Number(r)*1e3):void 0,se=o?/* @__PURE__ */ new Date(o*1e3):void 0,ce=i?.split(` `),le=o3(oe??{}),ue=le&&Object.keys(le).length?JSON.stringify(le):void 0;return{clientId:t,clientSecret:n,disabled:ee,scopes:ce,userId:a,createdAt:se,expiresAt:D,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:C,responseTypes:w,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:T,skipConsent:te,enableEndSession:E,requirePKCE:ne,dpopBoundAccessTokens:re,subjectType:ie,referenceId:ae,metadata:ue}}function N3(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:C,responseTypes:w,applicationType:T,jwks:ee,jwksUri:te,skipConsent:E,enableEndSession:ne,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:D}=e,se=c?Math.round(new Date(c).getTime()/1e3):void 0,ce=o?Math.round(new Date(o).getTime()/1e3):void 0,le=i?.join(` `);return{...o3(f2(D)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?se??0:void 0,scope:le??void 0,user_id:a??void 0,client_id_issued_at:ce??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:ee?JSON.parse(ee):void 0,jwks_uri:te??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:C??void 0,response_types:w??void 0,application_type:T??void 0,disabled:r??void 0,skip_consent:E??void 0,enable_end_session:ne??void 0,require_pkce:re??void 0,dpop_bound_access_tokens:ie??void 0,subject_type:ae??void 0,reference_id:oe??void 0}}async function Yhe(e,t){let n=await fH(e);if(await s3(e,n,t,`read`),!n)throw new c(`UNAUTHORIZED`);let r=await $0(e,t,e.query.client_id);if(!r)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);let i=N3(r);return i.client_secret=void 0,i}async function P3(e,t,n){let r=await $0(e,t,n);if(!r||r.disabled)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return N3({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function Xhe(e,t){let n=await fH(e);if(await s3(e,n,t,`list`),!n)throw new c(`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=N3(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=N3(e);return t.client_secret=void 0,t}):null);throw new c(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function Zhe(e,t){let n=await fH(e);if(await s3(e,n,t,`delete`),!n)throw new c(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await $0(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function F3(e,t,n){let r=await fH(e);if(await s3(e,r,t,`update`),!r)throw new c(`UNAUTHORIZED`);let i=e.body.client_id;if(t.cachedTrustedClients?.has(i))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let a=await $0(e,t,i);if(!a)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,...s}=e.body.update,l=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,u=!l&&n?.admin&&o!==void 0&&Object.keys(s).length===0;if(!l&&!u)throw new c(`UNAUTHORIZED`);if(u&&await s3(e,r,t,`configure-client-credentials-scopes`),Object.keys(s).length===0&&o===void 0){let e=N3(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let d=s.grant_types??a.grantTypes??[],f=s.token_endpoint_auth_method??a.tokenEndpointAuthMethod,p=o===void 0?void 0:X2(o);p!==void 0&&(Z2(p,d,f,t),p.length>0&&!u&&await s3(e,r,t,`configure-client-credentials-scopes`)),await C3({...N3(a),...s},t,{ctx:e});let m={...M3(s)};!d.includes(`client_credentials`)||f===`none`?m.clientCredentialsScopes=[]:p!==void 0&&(m.clientCredentialsScopes=p),s.token_endpoint_auth_method&&(s.token_endpoint_auth_method===`private_key_jwt`?m.clientSecret=null:(m.jwks=null,m.jwksUri=null,m.clientSecret||=await r2(e,t,t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`))));let h=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...m,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!h)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let g=N3(h);return g.client_secret=void 0,n?.admin?{...g,client_credentials_scopes:[...h.clientCredentialsScopes??[]]}:g}async function Qhe(e,t){let n=await fH(e);if(await s3(e,n,t,`rotate`),!n)throw new c(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await $0(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new c(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`),o=a?await r2(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 c(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return N3({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}const I3=f().trim().min(1),L3=_(f().trim().min(1)).min(1),$he=e=>J(`/admin/oauth2/create-client`,{method:`POST`,body:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:I3.optional(),application_type:E([`web`,`native`]).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:L3.optional(),client_credentials_scopes:_(f().trim().min(1)).optional(),response_types:_(E([`code`])).optional(),client_secret_expires_at:n([f(),m()]).optional().default(0),skip_consent:T().optional(),enable_end_session:T().optional(),require_pkce:T().optional(),dpop_bound_access_tokens:T().optional(),subject_type:E([`public`,`pairwise`]).optional(),metadata:g(f(),se()).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=>j3(t,e,{admin:!0})),ege=e=>J(`/oauth2/create-client`,{method:`POST`,use:[mH],body:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:I3.optional(),application_type:E([`web`,`native`]).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:L3.optional(),response_types:_(E([`code`])).optional(),dpop_bound_access_tokens:T().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=>j3(t,e)),tge=e=>J(`/oauth2/get-client`,{method:`GET`,use:[mH],query:D({client_id:f()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>Yhe(t,e)),nge=e=>J(`/oauth2/public-client`,{method:`GET`,use:[mH],query:D({client_id:f()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return P3(t,e,n)}),rge=e=>J(`/oauth2/public-client-prelogin`,{method:`POST`,use:[bhe(e)],body:D({client_id:f(),oauth_query:f().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return P3(t,e,n)}),ige=e=>J(`/oauth2/get-clients`,{method:`GET`,use:[mH],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>Xhe(t,e)),age=e=>J(`/admin/oauth2/update-client`,{method:`PATCH`,body:D({client_id:f(),update:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),application_type:E([`web`,`native`]).optional(),grant_types:L3.optional(),client_credentials_scopes:_(f().trim().min(1)).optional(),response_types:_(E([`code`])).optional(),client_secret_expires_at:n([f(),m()]).optional(),skip_consent:T().optional(),enable_end_session:T().optional(),dpop_bound_access_tokens:T().optional(),metadata:g(f(),se()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>F3(t,e,{admin:!0})),oge=e=>J(`/oauth2/update-client`,{method:`POST`,use:[mH],body:D({client_id:f(),update:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),application_type:E([`web`,`native`]).optional(),grant_types:L3.optional(),response_types:_(E([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>F3(t,e)),sge=e=>J(`/oauth2/client/rotate-secret`,{method:`POST`,use:[mH],body:D({client_id:f()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Qhe(t,e)),cge=e=>J(`/oauth2/delete-client`,{method:`POST`,use:[mH],body:D({client_id:f()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>Zhe(t,e));async function R3(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function lge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);return i}async function uge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function dge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function fge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);let a=await $0(e,t,i.clientId);if(!a)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,l=s.scopes;if(l&&!l.every(e=>o?.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let u=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:/* @__PURE__ */ new Date(u*1e3)}})}const pge=e=>J(`/oauth2/get-consent`,{method:`GET`,query:D({id:f()}),use:[mH],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>lge(t,e)),mge=e=>J(`/oauth2/get-consents`,{method:`GET`,use:[mH],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>uge(t,e)),hge=e=>J(`/oauth2/update-consent`,{method:`POST`,use:[mH],body:D({id:f(),update:D({scopes:_(f())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>fge(t,e)),gge=e=>J(`/oauth2/delete-consent`,{method:`POST`,use:[mH],body:D({id:f()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>dge(t,e));async function z3(e,t,n,r,i){if(!t)throw new c(`UNAUTHORIZED`);if(!e.headers)throw new c(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new c(`UNAUTHORIZED`)}const B3=e=>e.schema?.oauthResource?.modelName??`oauthResource`,V3=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,_ge=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function H3(e){try{return decodeURIComponent(e)}catch{return e}}function vge(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 yge(e,t){await z3(e,await fH(e),t,`create`);let n=e.body;if(!n?.identifier)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await qpe(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:B3(t),data:vge(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return V2(i.identifier),e.json(i,{status:201})}async function bge(e,t){await z3(e,await fH(e),t,`list`);let n=await e.context.adapter.findMany({model:B3(t)});return e.json(n??[])}async function xge(e,t){let n=H3(e.params.identifier);await z3(e,await fH(e),t,`read`,n);let r=await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]});if(!r)throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function Sge(e,t){let n=H3(e.params.identifier);if(await z3(e,await fH(e),t,`update`,n),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]}))throw new c(`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:B3(t),where:[{field:`identifier`,value:n}],update:r}),V2(n);let i=await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]});if(!i)throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function Cge(e,t){let n=H3(e.params.identifier);if(await z3(e,await fH(e),t,`delete`,n),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:B3(t),where:[{field:`identifier`,value:n}]}),V2(n),e.json({deleted:!0})}async function wge(e,t){let n=await fH(e),r=H3(e.params.identifier),i=H3(e.params.client_id);if(await z3(e,n,t,`link`,r),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:r}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:_ge(t),where:[{field:`clientId`,value:i}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:V3(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 Tge(e,t){let n=await fH(e),r=H3(e.params.identifier),i=H3(e.params.client_id);return await z3(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:V3(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const U3=D({identifier:f().min(1).optional(),name:f().optional(),accessTokenTtl:m().int().positive().nullable().optional(),refreshTokenTtl:m().int().positive().nullable().optional(),signingAlgorithm:E(F2).nullable().optional(),signingKeyId:f().nullable().optional(),allowedScopes:_(f()).nullable().optional(),customClaims:g(f(),se()).nullable().optional(),dpopBoundAccessTokensRequired:T().optional(),disabled:T().optional(),metadata:g(f(),se()).nullable().optional()}),Ege=e=>J(`/admin/oauth2/resources`,{method:`POST`,body:U3.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>yge(t,e)),Dge=e=>J(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>bge(t,e)),Oge=e=>J(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>xge(t,e)),kge=e=>J(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:U3,metadata:{SERVER_ONLY:!0}},async t=>Sge(t,e)),Age=e=>J(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Cge(t,e)),jge=e=>J(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>wge(t,e)),Mge=e=>J(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Tge(t,e));async function Nge(e,t,n){let r=t.disableJwtPlugin?void 0:q0(e.context),i=r?.options;try{let a=await OB(n,UB(await kK(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r?.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL}),o=`${e.context.baseURL}/oauth2/userinfo`;if(!a.payload.azp||!await L2(e,t,a.payload.aud,[o]))return null}catch(e){if(e instanceof Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new d(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return null;throw e}throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function Pge(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 d(`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 a2(t.storeTokens,i,`access_token`)}]});if(!a)throw new d(`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 Fge(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`});if(i.revoked)throw await o4(e,r,i.userId),new d(`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 o4(e,r,i.userId),new d(`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 Ige(e,t,n,r){try{return await Nge(e,t,r)}catch(e){if(e instanceof d){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await Pge(e,t,r,n)}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new d(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function Lge(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}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new d(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=tK(n)),!n?.length)throw new d(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await d2(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await Ige(e,t,c.clientId,n)}catch(e){if(e instanceof d){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 Fge(e,t,(await a4(t,n)).token,c.clientId)}catch(e){if(e instanceof d){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof d){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(xe.error(`Introspection error:`,e.message,e.stack),new d(`INTERNAL_SERVER_ERROR`)):(xe.error(`Introspection error:`,e),new d(`INTERNAL_SERVER_ERROR`))}}const Rge={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}}}},W3=[`openid`,`profile`,`email`,`offline_access`],G3=D({id_token_hint:f().optional(),client_id:f().optional(),post_logout_redirect_uri:C2.optional(),state:f().optional()}),K3=EI(()=>null),q3=K3.get,J3=/* @__PURE__ */ new WeakMap,Y3=`signedQueryIssuedAtMs`;function zge(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 X3=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 r=new Set((e.scopes??W3).filter(e=>e.length));if(t){for(let e of t)if(!r.has(e))throw new l(`clientRegistrationAllowedScope ${e} not found in scopes`)}for(let t of e.advertisedMetadata?.scopes_supported??[])if(!r?.has(t))throw new l(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let i=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(!i.has(e))throw new l(`${t} resource ${e} not found in resources`);let a=/* @__PURE__ */ new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...M2.filter(e=>r.has(j2[e].scope))]),o={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(r),claims:Array.from(a),clientRegistrationAllowedScopes:t};if(R0(o.extensions),o.pairwiseSecret&&o.pairwiseSecret.length<32)throw new l(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(o.grantTypes&&o.grantTypes.includes(`refresh_token`)&&!o.grantTypes.includes(`authorization_code`))throw new l(`refresh_token grant requires authorization_code grant`);if(o.disableJwtPlugin&&(o.storeClientSecret===`hashed`||typeof o.storeClientSecret==`object`&&`hash`in o.storeClientSecret))throw new l(`unable to store hashed secrets because id tokens will be signed with secret`);if(!o.disableJwtPlugin&&(o.storeClientSecret===`encrypted`||typeof o.storeClientSecret==`object`&&(`encrypt`in o.storeClientSecret||`decrypt`in o.storeClientSecret)))throw new l(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let s=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=o.disableJwtPlugin?t.baseURL:q0(t)?.options?.jwt?.issuer??t.baseURL,a=`/`;try{a=new URL(i).pathname.replace(/\/$/,``)||``}catch{a=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let s={context:t},c=/* @__PURE__ */ new Set([`/.well-known/oauth-authorization-server${a}`,`${a}/.well-known/oauth-authorization-server`]),l=`${a}/.well-known/openid-configuration`,u=c.has(r),d=o.scopes?.includes(`openid`)&&r===l,f=t=>{let n=X4(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 o.scopes?.includes(`openid`)?{response:f(Y4(s,o))}:{response:f(J4(s,o))};if(d)return{response:f(Y4(s,o))}},u=Z4(`/oauth2/authorize`,{method:[`GET`,`POST`],body:D({}).passthrough(),redirectOnError:s6(o),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=>qge(e,o,e.authorizeSettings??{isAuthorize:!0})),d=(e,t)=>RJ(u,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.7`,options:o,onRequest:s,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new l("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(await K2(e,o),ame(o),!o.disableJwtPlugin){let t=q0(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 rhe(t,o,{sessionId:e.id,userId:e.userId});if(!n)return;let r=J3.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),J3.set(t,r)},async after(e,t){if(!t)return;let n=J3.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&J3.delete(t),!r)return;let i=ihe(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:RF(async e=>{let t=e.body.oauth_query;if(!await Q0(t,e.context.secret))throw new c(`BAD_REQUEST`,{error:`invalid_signature`});let n=ope(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(A0),r.delete(j0),await K3.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Pue({query:r.toString(),...n?{[Y3]:n.getTime()}:{}})})}],after:[{matcher(e){return gV(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:RF(async e=>{let t=gV(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await K3.get(),r=(await Mue())?.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(),c=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(c.includes(`text/html`)||c.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let l=n?.signedQueryIssuedAt??zge(r?.[Y3]),u=y2(a,`login`);return v2(o.session.createdAt,l)&&(u=b2(u)),e.query=_2(u),await d(e)})}]},endpoints:{getOAuthServerConfig:J(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>o.scopes&&o.scopes.includes(`openid`)?Y4(e,o):J4(e,o)),getOpenIdConfig:J(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(o.scopes&&!o.scopes.includes(`openid`))throw new c(`NOT_FOUND`);return Y4(e,o)}),oauth2Authorize:u,oauth2Consent:J(`/oauth2/consent`,{method:`POST`,body:D({accept:T().meta({description:`Accept or deny user consent for a set of scopes`}),scope:f().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:O2.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:f().optional().meta({description:`The redirected page's query parameters`})}),use:[mH],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=>Zme(e,o,d)),oauth2Continue:J(`/oauth2/continue`,{method:`POST`,body:D({selected:T().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:T().optional().meta({description:`Confirms an account was registered`}),postLogin:T().optional().meta({description:`Confirms organization and/or team selection.`}),oauth_query:f().optional().meta({description:`The redirected page's query parameters`})}),use:[mH],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=>Qme(e,d)),oauth2Token:Z4(`/oauth2/token`,{method:`POST`,cloneRequest:!0,body:D({grant_type:f().trim().min(1),client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),code:f().optional(),code_verifier:f().optional(),redirect_uri:C2.optional(),refresh_token:f().optional(),resource:n([Q2,_(Q2).min(1)]).optional(),scope:f().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 Ype(e.request);t&&t.length>1&&(e.body.resource=t)}return yme(e,o)}),oauth2Introspect:Z4(`/oauth2/introspect`,{method:`POST`,cloneRequest:!0,body:D({client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),token:f(),token_type_hint:f().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=>E4(e,o)),oauth2Revoke:Z4(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:D({client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),token:f(),token_type_hint:f().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=>Lge(e,o)),oauth2UserInfo:J(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:D({access_token:f().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=>_me(e,o)),oauth2EndSession:Z4(`/oauth2/end-session`,{method:[`GET`,`POST`],body:G3.optional(),query:G3.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=>hhe(e,o)),oauth2EndSessionConfirmation:Z4(`/oauth2/end-session/confirm`,{method:`POST`,body:D({action:ee(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>ghe(e,o)),registerOAuthClient:Z4(`/oauth2/register`,{method:`POST`,body:t4,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=>Ghe(e,o)),adminCreateOAuthClient:$he(o),createOAuthClient:ege(o),getOAuthClient:tge(o),getOAuthClientPublic:nge(o),getOAuthClientPublicPrelogin:rge(o),getOAuthClients:ige(o),adminUpdateOAuthClient:age(o),updateOAuthClient:oge(o),rotateClientSecret:sge(o),deleteOAuthClient:cge(o),getOAuthConsent:pge(o),getOAuthConsents:mge(o),updateOAuthConsent:hge(o),deleteOAuthConsent:gge(o),adminCreateOAuthResource:Ege(o),adminListOAuthResources:Dge(o),adminGetOAuthResource:Oge(o),adminUpdateOAuthResource:kge(o),adminDeleteOAuthResource:Age(o),adminLinkClientResource:jge(o),adminUnlinkClientResource:Mge(o)},schema:YI(structuredClone(Rge),o?.schema),rateLimit:[...o.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:o.rateLimit?.token?.window??60,max:o.rateLimit?.token?.max??20}],...o.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:o.rateLimit?.authorize?.window??60,max:o.rateLimit?.authorize?.max??30}],...o.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:o.rateLimit?.introspect?.window??60,max:o.rateLimit?.introspect?.max??100}],...o.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:o.rateLimit?.revoke?.window??60,max:o.rateLimit?.revoke?.max??30}],...o.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:o.rateLimit?.register?.window??60,max:o.rateLimit?.register?.max??5}],...o.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:o.rateLimit?.userinfo?.window??60,max:o.rateLimit?.userinfo?.max??60}]]}};function Bge(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function Vge(e){let{max_age:t,...n}=e;return n}function Z3(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()}`:iI(e,o)}function Hge(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 Uge={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function Wge(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q3(e){return typeof e==`string`?e:void 0}function Gge(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...Wge(n)?n:{}}}const $3=(e,t)=>{let n=D4(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 e6(e,t,n,r,i){return $3(e,Z3(n.redirect_uri,r,i,n.state,n6(e,t)))}function t6(e){try{let t=new URL(e);return t.protocol!==`https:`&&!XH(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function n6(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=q0(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return t6(n)}function r6(e,t,n){return Z3(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function i6(e){let t;try{t=new URL(e)}catch{return}let n=YH(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 a6(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=i6(t);return e.find(e=>e===t?!0:a?i6(e)===a:!1)}function o6(e){if(!C2.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function Kge(e,t,n,r){if(!n||!r)return null;let i;try{i=await $0(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=a6(a,r);if(t.validateRedirectUri){if(!o6(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function s6(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await Kge(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?$3(r,Z3(a,t,n,typeof i.state==`string`?i.state:void 0,n6(r,e),Hge(i))):$3(r,r6(r,t,n))}}async function qge(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new d(`NOT_FOUND`);if(!e.request)throw new d(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=Gge(e,n);e.query=i;let a=Q3(i.request),o=Q3(i.request_uri);if(a!==void 0&&o!==void 0)return s6(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return s6(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=Q3(i.client_id);if(!n)return s6(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return s6(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 s6(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=e4.safeParse(i);if(!s.success){let n=Q4(s.error.issues,Uge);return s6(t)({...n,ctx:e})}if(i=s.data,e.query=i,await K3.set({query:c6(i).toString()}),!i.response_type)return s6(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?h2(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return $3(e,r6(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return $3(e,r6(e,`unsupported_response_type`,`unsupported response type`));let u=await $0(e,t,i.client_id);if(!u)return $3(e,r6(e,`invalid_client`,`client_id is required`));if(u.disabled)return $3(e,r6(e,`client_disabled`,`client is disabled`));if(!l2(u,`authorization_code`))return $3(e,r6(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let f=u.redirectUris??[],p=!1;if(i.redirect_uri){let e=!!a6(f,i.redirect_uri);if(t.validateRedirectUri&&o6(i.redirect_uri))try{p=await t.validateRedirectUri(i.redirect_uri,f,e)}catch{p=!1}else t.validateRedirectUri||(p=e)}if(!p)return $3(e,r6(e,`invalid_redirect`,`invalid redirect uri`));let m=i.scope?.split(` `).filter(e=>e);if(m){let n=new Set(u.scopes??t.scopes),r=m.filter(e=>!n?.has(e));if(r.length)return $3(e,Z3(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,n6(e,t)))}m||(m=u.scopes??t.scopes??[],i.scope=m.join(` `));let h=m.includes(`openid`);if(i.claims!==void 0&&!h)return $3(e,Z3(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,n6(e,t)));if(h&&!Vpe(i.claims))return $3(e,Z3(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,n6(e,t)));if(h&&!Hpe(i.claims,`0`))return $3(e,Z3(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,n6(e,t)));let g=k2(i.claims,N2(t));if(i.resource!==void 0)try{await R2(e,t,{resource:i.resource,clientId:u.clientId,requestedScopes:m})}catch(n){if(n instanceof d){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return $3(e,Z3(i.redirect_uri,r,a,i.state,n6(e,t)))}throw n}let _=x2(u,{scopes:m,nonce:i.nonce});if(_&&(!i.code_challenge||!i.code_challenge_method))return $3(e,Z3(i.redirect_uri,`invalid_request`,_.valueOf(),i.state,n6(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return $3(e,Z3(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,n6(e,t)));if(![`S256`].includes(i.code_challenge_method))return $3(e,Z3(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,n6(e,t)))}let v=Y0(i.resource)??[],y=await fH(e),b=i.max_age,x=y!=null&&b!==void 0&&Bge(new Date(y.session.createdAt),b,/* @__PURE__ */ new Date);if(!y||y!=null&&b!==void 0&&!x||c?.has(`login`)||c?.has(`create`))return l?e6(e,t,i,`login_required`,`authentication required`):u6(e,t,c?.has(`create`)?`create`:`login`);if(x&&(i=Vge(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return u6(e,t,`select_account`);if(n?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m}))return l?e6(e,t,i,`account_selection_required`,`End-User account selection is required`):u6(e,t,`select_account`);if(t.signup?.shouldRedirect){let n=await t.signup.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m});if(n)return l?e6(e,t,i,`interaction_required`,`End-User interaction is required`):u6(e,t,`create`,{page:typeof n==`string`?n:void 0})}if(!n?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m}))return l?e6(e,t,i,`interaction_required`,`End-User interaction is required`):u6(e,t,`post_login`);if(c?.has(`consent`))return u6(e,t,`consent`,{sessionId:y.session.id});let S=await t.postLogin?.consentReferenceId?.({user:y.user,session:y.session,scopes:m});if(u.skipConsent)return l6(e,t,{query:i,clientId:u.clientId,userId:y.user.id,sessionId:y.session.id,authTime:new Date(y.session.createdAt).getTime(),referenceId:S,resource:v});let C=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:u.clientId},{field:`userId`,value:y.user.id},...S?[{field:`referenceId`,value:S}]:[]]});if(!C||!m.every(e=>C.scopes.includes(e))||!g.every(e=>(C.requestedUserInfoClaims??[]).includes(e)))return l?e6(e,t,i,`consent_required`,`End-User consent is required`):u6(e,t,`consent`,{sessionId:y.session.id});let w=C?.resources??[];return v.some(e=>!w.includes(e))?l?e6(e,t,i,`consent_required`,`End-User consent is required`):u6(e,t,`consent`,{sessionId:y.session.id}):l6(e,t,{query:i,clientId:u.clientId,userId:y.user.id,sessionId:y.session.id,authTime:new Date(y.session.createdAt).getTime(),referenceId:S,resource:v})}function c6(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 l6(e,t,n){let r=yU(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await i2(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`,n6(e,t)),$3(e,s.toString())}async function u6(e,t,n,r){let i=await Jge(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 d(`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 $3(e,`${r?.page??a}?${i}`)}async function Jge(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=c6(e.query);a.set(`exp`,String(i)),a.set(A0,String(r)),a.delete(`sig`),a.delete(j0),n?.postLoginClearedForSession&&a.set(j0,n.postLoginClearedForSession),ape(a);let o=await OW(N0(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const Yge=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,Xge=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function d6(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function Zge(e){if(Yge.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`:ZH(t.hostname)?null:`client_id URL must not target a private or reserved address`}function Qge(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 $ge(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||S2(t)}catch{return!1}}function e_e(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(a3(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=mme.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(Xge.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&&!i3(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=>$ge(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(!ZH(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&&S2(n);if(n.protocol!==`https:`&&n.protocol!==`http:`&&!i)return{valid:!1,error:`all values for ${e} must use HTTP(S) or an authority-free private-use scheme`};if(i)continue;let a=r&&XH(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(...Qge(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const f6=5e3,p6=5120,t_e=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,m6=`Failed to fetch metadata document (network error or redirect blocked)`,h6=`cimd`;function g6(e){return new d(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function _6(){return g6(`Metadata document exceeds ${p6/1024}KB size limit`)}async function n_e(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw _6();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(),_6();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 r_e(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 i_e(e,t,n,r){let i=Zge(t);if(i)throw g6(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw g6(`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()},f6);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw g6(c?`Metadata document fetch timed out after ${f6}ms`:m6)}if(o.redirected)throw g6(`Metadata document fetch must not follow redirects`);let i=r_e(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw g6(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw g6(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!t_e.test(l))throw g6(`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>p6)throw await o.body?.cancel(),_6()}u=await n_e(o,p6,s.signal)}catch(e){throw c?g6(`Metadata document fetch timed out after ${f6}ms`):e instanceof d?e:g6(m6)}let f;try{f=JSON.parse(u)}catch{throw g6(`Metadata document is not valid JSON`)}let p=e_e(t,f,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!p.valid)throw g6(p.error);for(let t of p.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:`modified`,metadata:p.metadata,cacheHeaders:i}}finally{clearTimeout(l)}}async function v6(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await k3(e,i,{clientId:t,clientDiscoveryId:h6,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 y6={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function a_e(e){return new d(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function b6(e){return new d(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function o_e(e,t){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw new l(`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=(S0(e,t)-t)*1e3;if(!Number.isFinite(n)||n<0)throw Error(`negative duration`);return n}catch{throw new l(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}function x6(e,t){if(!Number.isInteger(e)||e<1)throw new l(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function s_e(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:o_e(t?.minimumFetchInterval??y6.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:x6(t?.maximumConcurrentFetches??y6.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:x6(t?.maximumConcurrentFetchesPerOrigin??y6.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:x6(t?.maximumFetchesPerMinute??y6.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:x6(t?.maximumFetchesPerOriginPerMinute??y6.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function S6(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function c_e(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(S0(e,n)-n)*1e3)}function l_e(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 C6(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function u_e(e,t,n){let{directives:r,duplicates:i}=l_e(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=c_e(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=C6(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=C6(r.get(`s-maxage`)),m=r.has(`max-age`),h=C6(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 d_e(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 f_e(e,t,n,r){let i=u_e(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function p_e(e){let t=e.metadataRevalidationInterval??`60m`,n=e.maxCacheEntries??1e3;if(!Number.isInteger(n)||n<1)throw new l(`cimd maxCacheEntries must be a positive integer`);let r=s_e(e),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=[],u=0,d=e=>{let t=i.get(e);if(t)return i.delete(e),i.set(e,t),t},f=(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)},p=(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 b6(`metadata fetch client state is at capacity`)}},m=(e,t)=>{let r=s.get(e);if(r)return S6(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(S6(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw b6(`metadata fetch origin state is at capacity`)}let i={activeFetchCount:0,fetchStartTimesMs:[]};return s.set(e,i),i},h=e=>{let t=Date.now(),n=o.get(e);if(r.minimumFetchIntervalMs>0&&n!==void 0&&t-n<r.minimumFetchIntervalMs)throw b6(`metadata document fetch is within the per-client minimum interval`);p(e,t);let i=new URL(e).origin,a=m(i,t);if(S6(c,t),u>=r.maximumConcurrentFetches)throw b6(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw b6(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw b6(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw b6(`metadata fetch rate limit exceeded for client origin`);o.delete(e),o.set(e,t),c.push(t),a.fetchStartTimesMs.push(t),u+=1,a.activeFetchCount+=1;let s=!1;return()=>{s||(s=!0,--u,--a.activeFetchCount)}};return async(n,r,s)=>{if(!d6(r))return null;let c=n.context.getPlugin(`oauth-provider`);if(!c)throw new l(`cimd discovery invoked without the oauth-provider plugin installed`);let u=c.options,p=d(r),m=Date.now();if(p&&p.expiresAt>m)return s||v6(n,r,p.metadata,e,u);let g=a.get(r);if(g)return g;let _=h(r),v=(async()=>{let a=await i_e(n,r,e,p?{etag:p.etag,lastModified:p.lastModified}:void 0);if(a.status===`not-modified`&&!p)throw a_e(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:p.metadata,l=await v6(n,r,c,e,u,s??void 0),d=f_e(c,a.status===`modified`?a.cacheHeaders:d_e(p.responseCacheHeaders,a.cacheHeaders),t,Date.now());return d?f(r,d):i.delete(r),o.delete(r),l})();a.set(r,v);try{return await v}catch(e){throw o.delete(r),o.set(r,Date.now()),e}finally{a.get(r)===v&&a.delete(r),_()}}}function m_e(e){return{id:h6,matches:d6,resolve:p_e(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const h_e=e=>{let t=m_e(e);return{id:`cimd`,version:`1.7.7`,init(e){mpe(e,{clientDiscovery:t})}}},g_e=oae(U({typ:H,payload:PS(H,QC)})),__e=e=>({id:`signer`,endpoints:{signDocument:J.serverOnly({method:`POST`,body:g_e},async t=>t.json({token:await T0(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),v_e=/* @__PURE__ */ new Set([204,205,304]);function y_e(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 b_e=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 yt(r.hostname,{all:!0,verbatim:!0});if(i.length===0)throw TypeError(`metadata hostname returned no DNS addresses`);for(let e of i)if(!ZH(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=uee(r,{agent:!1,headers:o,method:n.method,servername:lt(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`||v_e.has(r)?null:at.toWeb(t);e(new Response(i,{headers:y_e(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function x_e(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)})}))}}const S_e=x_e(b_e),C_e=f1(W(U({client_id:H,resource:H,scopes:TC(W(H)),approvedAt:VS(RC),refreshedAt:VS(RC)})));function w_e(e,t){let n=V(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*L(new M$({error:`Client not found`}))}),r=V(`Clients.revoke`)(function*(e,t,r){return yield*n(e,r),yield*v1(r,{clientId:e,resource:t}),{revoked:!0}});return{revoke:(t,n)=>m1(e,e=>r(t,n,e)),delete:t=>m1(e,e=>I(function*(){return yield*n(t,e),yield*_1(e,t,null),yield*e`DELETE FROM oauthClient WHERE clientId = ${t}`,{deleted:!0}})),connections:V(`Clients.connections`)(function*(){let e=new Date(yield*ep).toISOString();return(yield*C_e(yield*t`WITH live AS (
|
|
512
|
+
Most of the features of Better Auth will not work correctly.`);let u=t.secrets??Bde(Ae.BETTER_AUTH_SECRETS),d=t.secret||Ae.BETTER_AUTH_SECRET||Ae.AUTH_SECRET||``,f,p;u?(Vde(u,o),f=u[0].value,p=Hde(u,d)):(f=d||`better-auth-secret-12345678901234567890`,cfe(f,o),p=f),t={...t,secret:f,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},VJ(t,o);let m=t.advanced?.ipAddress?.trustedProxies;if(m&&m.length>0){let e=gue(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=nH(t),g=_e(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=Fq[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:Le(n)},{publish:y}=await ofe(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),C=await eU(t),w=await aU(t),T={appName:t.appName||`Better Auth`,baseURL:c||``,version:de(),socialProviders:_,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:g,trustedOrigins:C,trustedProviders:w,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>tI(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:f,secretConfig:p,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??ue,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||_U,verify:t.emailAndPassword?.password?.verify||vU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:oJ},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:MH(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:v}),createAuthCookie:tH(t),async runMigrations(){throw new l(`runMigrations will be set by the specific init implementation`)},publishTelemetry:y,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!ke():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},ee=QH(T);return FV(ee)&&await ee,T.checkSchema=je(T.adapter),T.explicitSchemaCheck=Pe(T.adapter),T}const ufe=async e=>{let t=await lfe(await Ode(e),e,e=>We(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new l(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await A1(e);await t()},t},dfe=(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 Ie?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=HJ(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(YF(e.baseURL))a=await rU(r,t,nU(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=qF(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new l(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:JF(n)||void 0},e=a.options}a.trustedOrigins=await eU(e,t),a.trustedProviders=await aU(e,t)}let{handler:o}=UJ(a,e);return Aue(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...q}}},ffe=e=>dfe(e,ufe),X=YP({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 V1(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 pfe={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*:/},mfe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,H1={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},hfe=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function gfe(e){return e instanceof Date&&!isNaN(e.getTime())}function _fe(e){let t=hfe.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 gfe(f)?f:null}function vfe(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 H1)return H1[s];if(!mfe.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(pfe).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`);return}if(a&&typeof t==`string`){let e=_fe(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function yfe(e,t={strict:!0}){return vfe(e,t)}function U1(e){return e==null?null:typeof e==`object`?e:Ee(e)}function W1(e){return e!=null&&typeof e==`string`}async function bfe(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>W1(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=U1(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 G1(e,t,n){let r=U1(t.metadata);if(W1(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 K1(e){return`api-key:${e}`}function q1(e){return`api-key:by-id:${e}`}function J1(e){return`api-key:by-ref:${e}`}function xfe(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 Y1(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 X1(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function Z1(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 Q1(e,t,n){let r=K1(t);return Y1(await n.get(r))}async function $1(e,t,n){let r=q1(t);return Y1(await n.get(r))}const e0=/* @__PURE__ */ new Map;function Sfe(e,t){let n=(e0.get(e)??Promise.resolve()).then(t,t).finally(()=>{e0.get(e)===n&&e0.delete(e)});return e0.set(e,n),n}async function t0(e,t,n){await Sfe(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 n0(e,t,n,r,i){let a=xfe(t),o=J1(t.referenceId);if(i.fallbackToDatabase){await Promise.all([n.set(K1(t.key),a,r),n.set(q1(t.id),a,r),n.delete(o)]);return}await Promise.all([n.set(K1(t.key),a,r),n.set(q1(t.id),a,r)]),await t0(n,o,e=>e.includes(t.id)?e:[...e,t.id])}async function Cfe(e,t,n,r){let i=J1(t.referenceId);if(r.fallbackToDatabase){await Promise.all([n.delete(K1(t.key)),n.delete(q1(t.id)),n.delete(i)]);return}await Promise.all([n.delete(K1(t.key)),n.delete(q1(t.id)),t0(n,i,e=>e.filter(e=>e!==t.id))])}async function r0(e,t,n){let r=X1(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 Q1(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 n0(e,i,r,Z1(i),n),i}return n.storage===`secondary-storage`?r?await Q1(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function i0(e,t,n){let r=X1(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 $1(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 n0(e,i,r,Z1(i),n),i}return n.storage===`secondary-storage`?r?await $1(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function a0(e,t,n){let r=X1(e,n),i=Z1(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await n0(e,t,r,i,n);return}}async function o0(e,t,n){let r=X1(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 Cfe(e,t,r,n);return}}function s0(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 c0(e,t,n,r){let i=X1(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=J1(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 V1(n,t=>$1(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s0(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 V1(l,t=>n0(e,t,i,Z1(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=J1(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 V1(l,t=>$1(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:s0(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 wfe(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 l0(e,t,n,r){let i=wfe(e);if(!i){let e=X.ORGANIZATION_PLUGIN_REQUIRED;throw c.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=X.USER_NOT_MEMBER_OF_ORGANIZATION;throw c.from(`FORBIDDEN`,e)}if(!await Tfe(e,a.role,n,r,i)){let e=X.INSUFFICIENT_API_KEY_PERMISSIONS;throw c.from(`FORBIDDEN`,e)}return a}async function Tfe(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-Bz1iQbJ0.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const u0=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Efe(e){return e instanceof c||e instanceof c||e?.name===`APIError`}const Dfe=D({configId:f().meta({description:`The configuration ID to use for the API key. If not provided, the default configuration will be used.`}).optional(),name:f().meta({description:`Name of the Api Key`}).optional(),expiresIn:m().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable().default(null),prefix:f().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:m().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:ie().optional(),refillAmount:m().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:m().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:m().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:m().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:T().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:g(f(),_(f())).meta({description:`Permissions of the Api Key.`}).optional(),userId:pF().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:pF().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function Ofe({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return J(`/api-key/create`,{method:`POST`,body:Dfe,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:l,metadata:u,refillAmount:d,refillInterval:f,permissions:p,rateLimitMax:m,rateLimitTimeWindow:h,rateLimitEnabled:g}=n.body,_=m0(n.context,t,i),v=_.customKeyGenerator||e,y=await fH(n,{disableCookieCache:!0}),b=n.request||n.headers;if(b&&(d!==void 0||f!==void 0||m!==void 0||h!==void 0||g!==void 0||p!==void 0||l!==null))throw c.from(`BAD_REQUEST`,X.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);let x=_.references??`user`,S;if(x===`organization`){let e=n.body.organizationId;if(!e){let e=X.ORGANIZATION_ID_REQUIRED;throw c.from(`BAD_REQUEST`,e)}let t=y?.user.id||n.body.userId;if(!t)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);await l0(n,t,e,`create`),S=e}else if(b){if(!y?.user.id){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}S=y.user.id}else{let e=n.body.userId,t=y?.user.id;if(!t&&!e){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}if(y&&e&&t!==e){let e=X.UNAUTHORIZED_SESSION;throw c.from(`UNAUTHORIZED`,e)}S=t||e}if(u){if(_.enableMetadata===!1)throw c.from(`BAD_REQUEST`,X.METADATA_DISABLED);if(typeof u!=`object`)throw c.from(`BAD_REQUEST`,X.INVALID_METADATA_TYPE)}if(d&&!f){let e=X.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw c.from(`BAD_REQUEST`,e)}if(f&&!d){let e=X.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw c.from(`BAD_REQUEST`,e)}if(o){if(_.keyExpiration.disableCustomExpiresTime===!0){let e=X.KEY_DISABLED_EXPIRATION;throw c.from(`BAD_REQUEST`,e)}let e=o/86400;if(_.keyExpiration.minExpiresIn>e){let e=X.EXPIRES_IN_IS_TOO_SMALL;throw c.from(`BAD_REQUEST`,e)}if(_.keyExpiration.maxExpiresIn<e){let e=X.EXPIRES_IN_IS_TOO_LARGE;throw c.from(`BAD_REQUEST`,e)}}if(s&&(s.length<_.minimumPrefixLength||s.length>_.maximumPrefixLength))throw c.from(`BAD_REQUEST`,X.INVALID_PREFIX_LENGTH);if(a){if(a.length<_.minimumNameLength||a.length>_.maximumNameLength)throw c.from(`BAD_REQUEST`,X.INVALID_NAME_LENGTH)}else if(_.requireName)throw c.from(`BAD_REQUEST`,X.NAME_REQUIRED);r(n.context);let C=await v({length:_.defaultKeyLength,prefix:s||_.defaultPrefix}),w=_.disableKeyHashing?C:await y0(C),T=null;_.startingCharactersConfig.shouldStore&&(T=C.substring(0,_.startingCharactersConfig.charactersLength));let ee=_.permissions?.defaultPermissions?typeof _.permissions.defaultPermissions==`function`?await _.permissions.defaultPermissions(S,n):_.permissions.defaultPermissions:void 0,te=p?JSON.stringify(p):ee?JSON.stringify(ee):void 0,E={configId:_.configId??`default`,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,name:a??null,prefix:s??_.defaultPrefix??null,start:T,key:w,enabled:!0,expiresAt:o?u0(o,`sec`):_.keyExpiration.defaultExpiresIn?u0(_.keyExpiration.defaultExpiresIn,`sec`):null,referenceId:S,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:m??_.rateLimit.maxRequests??null,rateLimitTimeWindow:h??_.rateLimit.timeWindow??null,remaining:l===null?l:l??d??null,refillAmount:d??null,refillInterval:f??null,rateLimitEnabled:g===void 0?_.rateLimit.enabled??!0:g,requestCount:0,permissions:te};u&&(E.metadata=u);let ne;if(_.storage===`secondary-storage`&&_.fallbackToDatabase)ne=await n.context.adapter.create({model:b0,data:E}),await a0(n,ne,_);else if(_.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||Le();ne={...E,id:e},await a0(n,ne,_)}else ne=await n.context.adapter.create({model:b0,data:E});return n.json({...ne,key:C,metadata:u??null,permissions:ne.permissions?Ee(ne.permissions):null})})}function kfe({deleteAllExpiredApiKeys:e}){return J.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 Afe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:f().meta({description:`The id of the Api Key`})});function jfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/delete`,{method:`POST`,body:Afe,use:[mH],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 c.from(`UNAUTHORIZED`,X.USER_BANNED);let o=m0(t.context,e,r),s=null;if(s=await i0(t,i,o),!s||!g0(s.configId,o.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let l=m0(t.context,e,s.configId);if((l.references??`user`)===`organization`)await l0(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);try{l.storage===`secondary-storage`&&l.fallbackToDatabase?(await o0(t,s,l),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:s.id}]})):l.storage===`database`?await t.context.adapter.delete({model:b0,where:[{field:`id`,value:s.id}]}):await o0(t,s,l)}catch(e){throw c.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const Mfe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),id:f().meta({description:`The id of the Api Key`})});function Nfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/get`,{method:`GET`,query:Mfe,use:[mH],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=m0(t.context,e,r),s=null;if(s=await i0(t,i,o),!s||!g0(s.configId,o.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let l=m0(t.context,e,s.configId);if((l.references??`user`)===`organization`)await l0(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);n(t.context);let u=await G1(t,s,l),{key:d,...f}=s;return t.json({...f,metadata:u,permissions:f.permissions?Ee(f.permissions):null})})}function Pfe(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const Ffe=D({configId:f().meta({description:`Filter by configuration ID. If not provided, returns keys from all configurations.`}).optional(),organizationId:f().meta({description:`Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys.`}).optional(),limit:mF().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:mF().int().nonnegative().meta({description:`The offset to start from`}).optional(),sortBy:f().meta({description:`The field to sort by (e.g., createdAt, name, expiresAt)`}).optional(),sortDirection:E([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function Ife({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/list`,{method:`GET`,use:[mH],query:Ffe,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 l0(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await c0(t,c,m0(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=Pfe(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>c0(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=>h0(t.configId)?h0(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>g0(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:U1(e.metadata),permissions:n.permissions?Ee(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(bfe(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const Lfe=D({configId:f().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:f().meta({description:`The id of the Api Key`}),userId:pF().meta({description:`The id of the user which the api key belongs to. server-only. Eg: "some-user-id"`}).optional(),name:f().meta({description:`The name of the key`}).optional(),enabled:T().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:m().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:m().meta({description:`The refill amount`}).optional(),refillInterval:m().meta({description:`The refill interval`}).optional(),metadata:ie().optional(),expiresIn:m().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:T().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:m().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:m().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:g(f(),_(f())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function Rfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J(`/api-key/update`,{method:`POST`,body:Lfe,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:l,refillInterval:u,remaining:d,name:f,permissions:p,rateLimitEnabled:m,rateLimitTimeWindow:h,rateLimitMax:g}=t.body,_=await fH(t,{disableCookieCache:!0}),v=t.request||t.headers,y=v&&!_?null:_?.user||{id:t.body.userId};if(!y?.id||_&&t.body.userId&&_?.user.id!==t.body.userId)throw c.from(`UNAUTHORIZED`,X.UNAUTHORIZED_SESSION);if(v&&(l!==void 0||u!==void 0||g!==void 0||h!==void 0||m!==void 0||d!==void 0||p!==void 0))throw c.from(`BAD_REQUEST`,X.SERVER_ONLY_PROPERTY);let b=m0(t.context,e,r),x=null;if(x=await i0(t,i,b),!x||!g0(x.configId,b.configId))throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let S=m0(t.context,e,x.configId);if((S.references??`user`)===`organization`)await l0(t,y.id,x.referenceId,`update`);else if(x.referenceId!==y.id)throw c.from(`NOT_FOUND`,X.KEY_NOT_FOUND);let C={};if(f!==void 0){if(f.length<S.minimumNameLength||f.length>S.maximumNameLength)throw c.from(`BAD_REQUEST`,X.INVALID_NAME_LENGTH);C.name=f}if(o!==void 0&&(C.enabled=o),a!==void 0){if(S.keyExpiration.disableCustomExpiresTime===!0)throw c.from(`BAD_REQUEST`,X.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<S.keyExpiration.minExpiresIn)throw c.from(`BAD_REQUEST`,X.EXPIRES_IN_IS_TOO_SMALL);if(e>S.keyExpiration.maxExpiresIn)throw c.from(`BAD_REQUEST`,X.EXPIRES_IN_IS_TOO_LARGE)}C.expiresAt=a?u0(a,`sec`):null}if(s!==void 0&&S.enableMetadata===!0){if(typeof s!=`object`)throw c.from(`BAD_REQUEST`,X.INVALID_METADATA_TYPE);C.metadata=s}if(d!==void 0&&(C.remaining=d),l!==void 0||u!==void 0){if(l!==void 0&&u===void 0)throw c.from(`BAD_REQUEST`,X.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(u!==void 0&&l===void 0)throw c.from(`BAD_REQUEST`,X.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);C.refillAmount=l,C.refillInterval=u}if(m!==void 0&&(C.rateLimitEnabled=m),h!==void 0&&(C.rateLimitTimeWindow=h),g!==void 0&&(C.rateLimitMax=g),p!==void 0&&(C.permissions=JSON.stringify(p)),Object.keys(C).length===0)throw c.from(`BAD_REQUEST`,X.NO_VALUES_TO_UPDATE);let w=x;try{if(S.storage===`secondary-storage`&&S.fallbackToDatabase){let e=await t.context.adapter.update({model:b0,where:[{field:`id`,value:x.id}],update:C});e&&(await a0(t,e,S),w=e)}else if(S.storage===`database`){let e=await t.context.adapter.update({model:b0,where:[{field:`id`,value:x.id}],update:C});e&&(w=e)}else{let e={...x,...C,updatedAt:/* @__PURE__ */ new Date};await a0(t,e,S),w=e}}catch(e){throw c.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let T=await G1(t,w,S),{key:ee,...te}=w;return t.json({...te,metadata:T,permissions:te.permissions?Ee(te.permissions):null})})}function d0(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:X.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function f0({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let l=n.disableKeyHashing?e:await y0(e),u=await r0(t,l,n);if(!u||o!==void 0&&!g0(u.configId,o))throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);let d=m0(t.context,r,u.configId);if(s&&d.customAPIKeyValidator&&!await d.customAPIKeyValidator({ctx:t,key:e}))throw c.from(`UNAUTHORIZED`,X.KEY_NOT_FOUND);if(u.enabled===!1)throw c.from(`UNAUTHORIZED`,X.KEY_DISABLED);if(u.expiresAt&&Date.now()>new Date(u.expiresAt).getTime()){let e=async()=>{d.storage===`secondary-storage`&&d.fallbackToDatabase?(await o0(t,u,d),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})):d.storage===`secondary-storage`?await o0(t,u,d):await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})};throw d.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),c.from(`UNAUTHORIZED`,X.KEY_EXPIRED)}if(a){let e=u.permissions?Ee(u.permissions):null;if(!e||!oee(e).authorize(a).success)throw c.from(`UNAUTHORIZED`,X.KEY_NOT_FOUND)}if(u.remaining===0&&u.refillAmount===null){let e=async()=>{d.storage===`secondary-storage`&&d.fallbackToDatabase?(await o0(t,u,d),await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})):d.storage===`secondary-storage`?await o0(t,u,d):await t.context.adapter.delete({model:b0,where:[{field:`id`,value:u.id}]})};throw d.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED)}return{apiKey:d.storage===`database`||d.storage===`secondary-storage`&&d.fallbackToDatabase?await zfe({ctx:t,apiKey:u,opts:d,hashedKey:l}):await Vfe({ctx:t,apiKey:u,opts:d,hashedKey:l}),opts:d}}async function zfe({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await Bfe(e,t)),i=await p0(e,i,n);let a=await e.context.adapter.update({model:b0,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await a0(e,a,n),a}async function Bfe(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:b0,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:b0,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED);return a}async function p0(e,t,n){let r=d0(t,n);if(r.type===`deny`)throw new c(`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:b0,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:b0,where:[{field:`id`,value:t.id}]});if(!a)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return p0(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:b0,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:b0,where:[{field:`id`,value:t.id}]});if(!o)throw c.from(`UNAUTHORIZED`,X.INVALID_API_KEY);return p0(e,o,n)}async function Vfe({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 c.from(`TOO_MANY_REQUESTS`,X.USAGE_EXCEEDED);i--}let o={...Hfe(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await r0(e,r,n);if(!t)return null;let i={...t,...o};return await a0(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 l=await s();if(!l)throw c.from(`INTERNAL_SERVER_ERROR`,X.FAILED_TO_UPDATE_API_KEY);return l}function Hfe(e,t){let n=d0(e,t);switch(n.type){case`deny`:throw new c(`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 Ufe=D({configId:f().meta({description:`Configuration ID to scope verification to. When omitted, the key is validated against its own configuration.`}).optional(),key:f().meta({description:`The key to verify`}),permissions:g(f(),_(f())).meta({description:`The permissions to verify.`}).optional()});function Wfe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return J.serverOnly({method:`POST`,body:Ufe},async r=>{let{configId:i,key:a}=r.body,o=m0(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:X.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await f0({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),Efe(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:X.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 G1(r,s,c)),u.permissions=u.permissions?Ee(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function m0(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=X.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw c.from(`BAD_REQUEST`,t)}return{...n,configId:`default`}};return n?t.find(e=>e.configId===n)??r():r()}function h0(e){return!e||e==="default"}function g0(e,t){return h0(e)&&h0(t)?!0:e===t}let _0=null;async function v0(e,t=!1){_0&&!t&&(/* @__PURE__ */ new Date()).getTime()-_0.getTime()<1e4||(_0=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:b0,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 Gfe({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:Ofe({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),verifyApiKey:Wfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),getApiKey:Nfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),updateApiKey:Rfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),deleteApiKey:jfe({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),listApiKeys:Ife({configurations:t,schema:n,deleteAllExpiredApiKeys:v0}),deleteAllExpiredApiKeys:kfe({deleteAllExpiredApiKeys:v0})}}const Kfe=({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?yfe(e):null}}}}}}),y0=async e=>{let t=await CH(`SHA-256`).digest(new TextEncoder().encode(e));return YV.encode(new Uint8Array(t),{padding:!1})},b0=`apikey`;function qfe(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new l(`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 l(`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=YI(Kfe({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=yU(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 u=Gfe({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.7`,$ERROR_CODES:X,hooks:{before:[{matcher:e=>!!s(e),handler:RF(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw c.from(`BAD_REQUEST`,X.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw c.from(`FORBIDDEN`,X.INVALID_API_KEY);let{apiKey:a}=await f0({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=v0(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=X.INVALID_REFERENCE_ID_FROM_API_KEY;throw c.from(`UNAUTHORIZED`,e)}let l=await e.context.internalAdapter.findUserById(a.referenceId);if(!l){let e=X.INVALID_REFERENCE_ID_FROM_API_KEY;throw c.from(`UNAUTHORIZED`,e)}let u={user:l,session:{id:a.id,token:t,userId:a.referenceId,userAgent:e.request?.headers.get(`user-agent`)??null,ipAddress:e.request?vI(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||u0(e.context.options.session?.expiresIn||604800,`ms`)}};return e.context.session=u,e.path===`/get-session`?u:{context:e}})}]},endpoints:{createApiKey:u.createApiKey,verifyApiKey:u.verifyApiKey,getApiKey:u.getApiKey,updateApiKey:u.updateApiKey,deleteApiKey:u.deleteApiKey,listApiKeys:u.listApiKeys,deleteAllExpiredApiKeys:u.deleteAllExpiredApiKeys},schema:i}}const x0=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await OI(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 OI(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 OI(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 OI(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 OI(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function S0(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+RV(e)}async function Jfe(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await nV(t,{...n,extractable:!0});return{publicWebKey:await RB(r),privateWebKey:await RB(i),alg:t,cfg:n}}async function C0(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await Jfe(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 TW({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 x0(e.context.adapter,t).createJwk(e,d)}async function w0(e,t,n){if(t?.jwt?.sign)return null;let r=x0(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new l(`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 l(`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 C0(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new l(`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 l(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await C0(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await EW({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new l(`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 QB(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function T0(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=S0(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 w0(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new NB(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 E0(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await T0(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 D0(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 Yfe(e,t,n){let r=$B(t),i=r.kid;if(!i)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let a=await x0(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 QB(JSON.parse(o.publicKey),s)}:(e.context.logger.debug(`No JWT algorithm available for cookie-cache JWT kid: ${i}`),null)}async function Xfe(e,t,n,r){let i=await w0(e,r);if(!i)throw new l("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new NB({...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(D0(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function Zfe(e,t,n){try{if($B(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await Yfe(e,t,n);if(!r)return null;let{payload:i}=await OB(t,r.publicKey,{...UV({issuer:D0(e)}),algorithms:[r.alg]}),a=WV(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 Qfe(e){return{sign:(t,n,r)=>Xfe(t,n,r,e),verify:(t,n)=>Zfe(t,n,e)}}const $fe={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 epe(e,t){let n=PF();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(JV.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await x0(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 QB(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 OB(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 tpe=D({payload:g(f(),ie()),overrideOptions:g(f(),ie()).optional()}),npe=D({token:f(),issuer:f().optional()}),rpe=e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new l(`options.jwks.remoteUrl must be set when using options.jwt.sign`);if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new l(`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 l(`options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'`);return{id:`jwt`,version:`1.7.7`,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!==`jwt`)throw new l('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new l("`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:Qfe(e)}}}},endpoints:{getJwks:J(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 c(`NOT_FOUND`);let n=x0(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await C0(t,e),r=await n.getAllKeys(t)),!r?.length)throw new l(`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,u=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??u,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:J(`/token`,{method:`GET`,requireHeaders:!0,use:[mH],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 E0(t,e);return t.json({token:n})}),signJWT:J.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:tpe},async t=>{let n=await T0(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:n})}),verifyJWT:J.serverOnly({method:`POST`,metadata:{$Infer:{body:{},response:{}}},body:npe},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await epe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:RF(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await E0(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:YI($fe,e?.schema)}};var O0=Object.defineProperty,k0=(e,t)=>{let n={};for(var r in e)O0(n,r,{get:e[r],enumerable:!0});return t||O0(n,Symbol.toStringTag,{value:`Module`}),n};const A0=`ba_iat`,j0=`ba_pl`,M0=`ba_param`;function N0(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 ipe(e){e.delete(M0);let t=[.../* @__PURE__ */ new Set([...e.keys(),M0])].sort();for(let n of t)e.append(M0,n)}function ape(e){let t=new URLSearchParams(e).get(A0);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const ope=[`authorization_code`,`client_credentials`,`refresh_token`],P0=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],spe=[`none`,...P0],cpe=new Set(spe);function F0(e,t){if(!(t.trim().length>0))throw new l(`OAuth Provider extension ${e} cannot be empty`)}function I0(e,t){F0(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new l(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function lpe(e){I0(`grant type`,e)}function upe(e){if(F0(`token_endpoint_auth_method`,e),cpe.has(e))throw new l(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function dpe(e){if(I0(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new l(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function fpe(e){let t=Object.keys(e.grants??{});for(let e of t)lpe(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){upe(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new l(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)dpe(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)F0(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function L0(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){if(n.has(r))throw new l(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function R0(e){let t=(e??[]).map(fpe);L0(`grant type`,t.flatMap(e=>e.grantTypes)),L0(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),L0(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),L0(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function z0(e){return e.extensions??[]}function B0(e){return z0(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function ppe(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new l(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];R0(i),n.options.extensions=i}function mpe(e){return z0(e).flatMap(e=>Object.keys(e.grants??{}))}function V0(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??ope,...mpe(e)]))}function hpe(e,t){for(let n of z0(e)){let e=n.grants?.[t];if(e)return e}}function H0(e){return z0(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function U0(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...P0,...H0(e)]))}function W0(e,t){return t?H0(e).includes(t):!1}function gpe(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of z0(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 G0(e,t,n,r){let i={...r};for(let a of z0(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 K0(e,t){let n={};for(let r of z0(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e)){if(t in n){xe.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`);continue}n[t]=r}}return n}function _pe(e,t){return K0(e,e=>e.claims?.accessToken?.(t))}function vpe(e,t){return K0(e,e=>e.claims?.idToken?.(t))}function ype(e,t){return K0(e,e=>e.claims?.userInfo?.(t))}function bpe(e){return z0(e).some(e=>e.claims?.userInfo)}function xpe(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Spe(){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);return}return n}},set(t,n){e.set(t,n)}}}const q0=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new l(`jwt_config`);return t};function J0(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 Cpe(e){if(e instanceof Date||!e||typeof e!=`object`)return J0(e);let t=J0(e.createdAt)??J0(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return J0(n.createdAt)??J0(n.created_at)}function Y0(e){if(typeof e==`string`)return[e];if(e?.length)return e}function X0(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const Z0=/* @__PURE__ */ new WeakMap;function wpe(e){let t=Z0.get(e);if(t)return t;let n=Spe();return Z0.set(e,n),n}async function Q0(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 OW(N0(n).toString(),t);return i.length===1&&!!r&&fU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}async function $0(e,t,n){let r=wpe(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=B0(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 e2(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const t2=async e=>{let t=await CH(`SHA-256`).digest(new TextEncoder().encode(e));return YV.encode(new Uint8Array(t),{padding:!1})};async function n2(e,t,n){if(t===`encrypted`)return await EW({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new l(`Unsupported decryption storageMethod type '${t}'`)}async function Tpe(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 d(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await t2(r):void 0;return!!e&&fU(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&&fU(e,n)}}if(i===`encrypted`)try{let t=await n2(e,i,n);return!!r&&fU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await n2(e,i,n);return!!r&&fU(t,r)}throw new l(`Unsupported verify storageMethod type '${i}'`)}async function r2(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await TW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await t2(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 l(`Unsupported storeClientSecret type '${r}'`)}async function i2(e=`hashed`,t,n){if(e===`hashed`)return await t2(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new l(`storeToken: unsupported storageMethod type '${e}'`)}async function a2(e=`hashed`,t,n){if(e===`hashed`)return await t2(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new l(`getStoredToken: unsupported storageMethod type '${e}'`)}const o2=/^Basic +/i,Epe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Dpe(e){return e.match(Epe)?.[1]}const s2=[`client_secret`,`client_assertion`,`client_assertion_type`];function c2(e){throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Ope(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&c2(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&c2(`${e} must be a string`),r[e]=t)};for(let e of s2)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&&c2(`client_id must not be repeated`),n=r[0];for(let e of s2){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&c2(`${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)&&c2(`A request must use only one client authentication method`),t.client_id=n;for(let e of s2)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function kpe(e){if(o2.test(e))try{let{clientId:t,clientSecret:n}=ZW(e);return{client_id:t,client_secret:n}}catch{throw new d(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function l2(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 Ape(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new d(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function u2(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new d(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function d2(e,t,n,r,i,a,o,s){let c=await $0(e,t,n);c||u2(`missing client`,{method:s}),c.disabled&&u2(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&u2(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||W0(t,c.tokenEndpointAuthMethod))&&!a)throw new d(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&u2(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&u2(`public client, client secret should not be received`,{method:s}),r&&!await Tpe(e,t,c.clientSecret,r)&&u2(`invalid client_secret`,{method:s})),Ape(c,i),o&&!l2(c,o))throw new d(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function f2(e){if(e)return typeof e==`string`?JSON.parse(e):e}function p2(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 m2(e,t,n){let r={...e.body??{}};await Ope(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 d(`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=gpe(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(()=>Yme).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&&!o2.test(i)){let e=Dpe(i);if(!e)throw new d(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});u2(`unsupported authorization scheme`,{scheme:e})}if(i&&o2.test(i)){let e=kpe(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 h2(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 jpe(e){let t=e.redirectUris?.[0];if(!t)throw new l(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function Mpe(e,t,n){return OW(`${jpe(t)}.${e}`,n)}async function g2(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Mpe(e,t,n.pairwiseSecret):e}function _2(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 v2(e,t){if(!t)return!1;let n=J0(e);return n?n.getTime()>=t.getTime():!1}function y2(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 b2(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function x2(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 Npe=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;function S2(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(`//`)&&Npe.test(t)}const C2=p().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),C}if(oue.includes(n.protocol)){t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`});return}e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!XH(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`})}),Ppe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function w2(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e)){if(Ppe.has(r)){t.push(r);continue}n[r]=i}return t.length>0&&xe.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const T2=g(f(),se()).nullable(),Fpe=x({essential:T().optional(),value:f().optional(),values:_(f()).optional()}).nullable(),Ipe=D({acr:Fpe.optional()}).catchall(T2),Lpe=x({userinfo:g(f(),T2).optional(),id_token:Ipe.optional()});function Rpe(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function E2(e){let t=Rpe(e),n=Lpe.safeParse(t);return n.success?n.data:void 0}const D2=n([f(),g(f(),se())]),zpe=D2,O2=D2.refine(e=>E2(e)!==void 0,{error:`claims must be a valid Claims request object`});function Bpe(e){return e===void 0||E2(e)!==void 0}function k2(e,t){let n=E2(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 Vpe(e,t){let n=E2(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 Hpe(e,t){let n=E2(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 A2(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const j2={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>A2(e.name).given},family_name:{scope:`profile`,resolve:e=>A2(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},M2=Object.keys(j2);function N2(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const Upe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function Wpe(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e)){if(Upe.has(r)){t.push(r);continue}n[r]=i}return t.length>0&&xe.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function P2(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 _pe(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 Wpe({...p,...d??{},...m,...f})}const F2=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],Gpe=new Set(F2);async function I2(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r;try{r=new URL(t)}catch{return{ok:!1,reason:`resource identifier ${t} must be an absolute URI (RFC 8707 §2)`}}return r.hash?{ok:!1,reason:`resource identifier ${t} must not contain a URI fragment (RFC 8707 §2)`}:{ok:!0}}async function Kpe(e,t){let n=await I2(e,t);if(!n.ok)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const qpe=e=>`${e}/oauth2/userinfo`;async function Jpe(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 Ype(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 L2(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=>H2(e,t,n)))).every(Boolean)}async function R2(e,t,n){let r=Ype(n.resource),i=n.requestedScopes.includes(`openid`),a=qpe(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 H2(e,t,n);if(r){if(r.disabled)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r);continue}throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:l}=z2(t);l&&s.length>0&&await Xpe(e,t,n.clientId,s);let u=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=u.filter(e=>t.has(e));if(n.length===0)throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});u=n}let d=null,f=null;for(let e of s)e.accessTokenTtl!=null&&(d=d===null?e.accessTokenTtl:Math.min(d,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(f=f===null?e.refreshTokenTtl:Math.min(f,e.refreshTokenTtl));let p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Set;for(let e of s)e.signingAlgorithm&&p.add(e.signingAlgorithm),e.signingKeyId&&m.add(e.signingKeyId);if(p.size>1)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(m.size>1)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let h=p.values().next().value??null,g=m.values().next().value??null,_={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(_,e.customClaims);let v=s.some(e=>e.dpopBoundAccessTokensRequired===!0),y=i?[...o,a]:o,b=[...new Set(y)];return{audienceClaim:b.length===1?b[0]:b,accessTokenTtl:d,refreshTokenTtl:f,signingAlgorithm:h,signingKeyId:g,rawCustomClaims:_,dpopBoundAccessTokensRequired:v,effectiveScopes:u}}async function Xpe(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 c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function Zpe(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 Qpe(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 z2(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const B2=/* @__PURE__ */ new Map;function V2(e){if(e===void 0){B2.clear();return}B2.delete(e)}async function H2(e,t,n){if(await rme(e.context,t),t.cachedResources?.has(n)){let e=B2.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)&&B2.set(n,Object.assign({},r)),r}function $pe(e){return e.name??e.identifier}function eme(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function U2(e,t){return{identifier:e.identifier,name:$pe(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 tme(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=U2(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 W2=/no such table|relation.*does not exist|table.*does(?: not|n[''']?t) exist/i;let G2=/* @__PURE__ */ new WeakMap;function nme(e){let t=e.adapter,n=G2.get(t);if(n)return n;let r={completed:!1,promise:null};return G2.set(t,r),r}async function K2(e,t){let n=eme(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 I2(t,a.identifier);if(!n.ok){xe.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!Gpe.has(o.signingAlgorithm)){xe.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${F2.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s;try{s=await e.adapter.findOne({model:i,where:[{field:`identifier`,value:o.identifier}]})}catch(e){let t=e instanceof Error?e.message:String(e);if(W2.test(t)){xe.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`);return}throw e}let c=/* @__PURE__ */ new Date;if(!s){try{await e.adapter.create({model:i,data:U2(o,c)})}catch(e){let t=e instanceof Error?e.message:String(e);if(/unique|duplicate|UNIQUE/i.test(t)){xe.debug(`oauth-provider: resource ${o.identifier} already inserted by a concurrent process — skipping.`);continue}if(W2.test(t)){xe.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`);return}throw e}continue}r!==`insertOnly`&&await e.adapter.update({model:i,where:[{field:`identifier`,value:o.identifier}],update:tme(o,r,c)})}}async function rme(e,t){let n=nme(e);if(n.completed!==!0)return n.promise===null&&(n.promise=K2(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function ime(e){let t=z2(e);xe.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function q2(e){return e.headers?.get(`dpop`)??void 0}function J2(e,t){return e.request?.url??`${e.context.baseURL}${t}`}const ame=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function Y2(e){return ame.has(e)}function X2(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function Z2(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new c(`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)||Y2(e));if(a.length>0)throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}const ome=[`javascript:`,`data:`,`vbscript:`],Q2=f().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),C;if(e.includes(`#`)){t.addIssue({code:`custom`,message:`resource must not contain a fragment`});return}ome.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),sme=E([`none`,`consent`,`login`,`create`,`select_account`]),cme=f().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`});return}for(let e of n){let n=sme.safeParse(e);if(!n.success){t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`});continue}r.add(n.data)}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}),$2=D({keys:_(g(f(),se())).min(1)}),lme=n([m(),f().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`}),C):n}),ume=f().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),e4=D({response_type:f().pipe(E([`code`])).optional(),request:f().optional(),request_uri:f().optional(),redirect_uri:C2.optional(),scope:f().optional(),state:f().optional(),client_id:f().min(1,`client_id is required`),prompt:cme.optional(),display:f().optional(),ui_locales:f().optional(),max_age:lme.optional(),acr_values:f().optional(),login_hint:f().optional(),id_token_hint:f().optional(),code_challenge:f().optional(),code_challenge_method:f().pipe(E([`S256`])).optional(),nonce:f().optional(),claims:zpe.optional(),dpop_jkt:ume.optional(),resource:n([Q2,_(Q2).min(1)]).optional()}).passthrough(),dme=e4.extend({redirect_uri:C2.optional(),claims:O2.optional()}),fme=D({type:ee(`authorization_code`),query:dme,sessionId:f(),userId:f(),referenceId:f().optional(),authTime:m().optional(),resource:_(f()).optional()}).passthrough(),t4=D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:f().trim().min(1).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:_(f().trim().min(1)).min(1).optional(),response_types:_(E([`code`])).optional(),application_type:E([`web`,`native`]).optional(),subject_type:E([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:T().optional(),resources:_(Q2).optional(),skip_consent:b({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),pme=t4.omit({skip_consent:!0}).extend({client_id:f().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:f().optional(),client_secret_expires_at:m().int().nonnegative().optional(),client_id_issued_at:m().int().nonnegative().optional()}).loose();function mme(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(j2))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function n4(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 hme(e){let t=e.headers?.get(`authorization`),n=eK(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new c(`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 gme(e,t){let{authorization:n}=hme(e);if(!n?.token)throw new c(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await w4(e,t,n.token);if(oK(r)&&!e.request)throw new c(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await gK({payload:r,authorization:n,proofJwt:q2(e),method:e.request?.method??`GET`,url:J2(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZG(e.context.internalAdapter)})}catch(e){throw hK(e)?new c(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new c(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=mme(o,a??[],i),l=r.client_id??r.azp,u=l&&(t.pairwiseSecret||bpe(t))?await $0(e,t,l):void 0;t.pairwiseSecret&&u&&(s.sub=await g2(o.id,u,t));let d=a?.length?await ype(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:u??void 0,requestedClaims:i}):{},f=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...n4(d,s),...n4(f),sub:s.sub}}const _me=Object.fromEntries(M2.map(e=>[e,void 0]));function r4(e){return aK(e)?`DPoP`:`Bearer`}async function vme(e,t){let n=e.body.grant_type;if(!V0(t).includes(n))throw new c(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return zme(e,t);case`client_credentials`:return Bme(e,t);case`refresh_token`:return Vme(e,t);default:{let r=hpe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:yme(e,t,n)});throw new c(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function yme(e,t,n){return{getClient:n=>$0(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:l}=p2(await m2(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new c(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await d2(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:l}},issueTokens:r=>{if(!n)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return g4(e,t,{...r,grantType:n})},hashToken:(e,n)=>i2(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>_4);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>_4);return i(e,t,n,r)}}}async function bme(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=q0(e.context).options,u=n?.id??r.clientId;return T0(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:X0(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:yU(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function xme(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 cR(r.slice(0,r.length/2))}async function Sme(e,t,n,r,i,a,o,s,l,u){let d=Math.floor(Date.now()/1e3),f=d+(t.idTokenExpiresIn??36e3),p=await g2(n.id,r,t),m=s==null?void 0:Math.floor(s.getTime()/1e3),h=w2(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:f2(r.metadata)}):void 0),g=t.disableJwtPlugin?void 0:q0(e.context).options,_=!t.disableJwtPlugin&&!g?.jwt?.sign?await w0(e,g):void 0,v=t.disableJwtPlugin?`HS256`:_?.alg??g?.jwks?.keyPairConfig?.alg,y=l?await xme(l,v):void 0,b=!!(r.enableEndSession||r.backchannelLogoutUri),x={..._me,auth_time:m,acr:`0`,...h,at_hash:y,iss:g?.jwt?.issuer??e.context.baseURL,sub:p,aud:r.clientId,nonce:a,iat:d,exp:f,sid:b?o:void 0},S=w2(u);if(Object.assign(x,n4(S,x)),t.disableJwtPlugin&&!r.clientSecret)return;let C=t.disableJwtPlugin?await new NB(x).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await n2(e,t.storeClientSecret,r.clientSecret))):await T0(e,{options:g,payload:x,resolvedKey:_??void 0});if(C&&y&&g?.jwt?.sign){let e=$B(C);if(e.alg!==v)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${v}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return C}async function i4(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function a4(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new c(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function Cme(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():yU(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await i2(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 o4(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 wme(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 s4(e,t,n,r,i,a,o,s,l,u,d,f,p){let m=s.iat??Math.floor(Date.now()/1e3),h=s?.exp??m+(t.refreshTokenExpiresIn??2592e3),g=t.generateRefreshToken?await t.generateRefreshToken():yU(32,`A-Z`,`a-z`),_=s?.sid,v={token:await i2(t.storeTokens,g,`refresh_token`),clientId:a.clientId,sessionId:_,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:u,confirmation:f,requestedUserInfoClaims:p?.length?p:void 0,scopes:o,resources:d,createdAt:/* @__PURE__ */ new Date(m*1e3),expiresAt:/* @__PURE__ */ new Date(h*1e3)};if(!l?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await i4(t,g,_)};let y=/* @__PURE__ */ new Date(m*1e3),b={revoked:y,rotatedAt:y},x=t.refreshTokenReuseInterval??0;if(x>0&&(b.rotationReplayExpiresAt=/* @__PURE__ */ new Date((m+x)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:l.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:b}))throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await i4(t,g,_)}}async function c4(e,t,n){let r=await R2(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 l4(e){throw new c(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Tme(e){let t=f2(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function u4(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=aK(n.refreshToken?.confirmation),a=i??r,o=q2(e),s=Tme(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o){s&&l4(`DPoP proof header is required`);return}try{return{jkt:(await pK({proofJwt:o,method:`POST`,url:J2(e,`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZG(e.context.internalAdapter)})).jkt}}catch(e){throw $G(e)&&l4(e.message),e}}function d4(e){return e?[...new Set(e)].sort():void 0}function f4(e,t){let n=d4(e),r=d4(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function p4(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Eme(e,t){return p4(e)===p4(t)}function Dme(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 Ome(e){return e===`Bearer`||e===`DPoP`}function kme(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`&&Ome(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 Ame(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||Dme(n.confirmation))&&kme(t.response)}function m4(e){let t=d4(e.requestedResources);return{effectiveScopes:d4(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function jme(e,t){return f4(e.effectiveScopes,t.effectiveScopes)&&f4(e.requestedResources,t.requestedResources)&&Eme(e.confirmation,t.confirmation)}async function Mme(e,t){return TW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Nme(e,t){let n=await EW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(Ame(r))return r}function h4(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function Pme(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 Mme(e,{request:r,response:i})}})}async function Fme(e,t,n){if(h4(t)&&t.rotationReplayResponse)try{let r=await Nme(e,t.rotationReplayResponse);return!r||!jme(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Ime(e,t,n){let r=Math.floor(Date.now()/1e3),i=await c4(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await u4(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return m4({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function Lme(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function g4(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]?S0(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await c4(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&&l2(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,C=a&&v.includes(`openid`),w=f2(r.metadata),T=C&&a?{...await vpe(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:w}),...n.idTokenClaims??{}}:void 0,ee=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:w,verificationValue:f}):void 0,te=g.refreshResources,E=n.confirmation??await u4(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),ne=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],re=x&&a&&!S?await s4(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,te,E,ne):void 0,ie=S?await P2({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:w,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[ae,oe]=await Promise.all([S?bme(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ie,confirmation:E}):Cme(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,re?.id,E,ne),re||(x&&a?s4(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,te,E,ne):void 0)]),D=C?await Sme(e,t,a,r,v,l,c,d,ae,T):void 0,se={...ee,...n.tokenResponse??{},access_token:ae,expires_in:y-p,expires_at:y,token_type:r4(E),refresh_token:oe?.token,scope:v.join(` `),id_token:D};if(u?.id&&oe?.id)try{await Pme(e,t,u,m4({effectiveScopes:v,requestedResources:n.resources,confirmation:E}),se)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(se)}async function Rme(e,t,n,r,i,a){let o=await i2(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await wme(e,o),new c(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let l;try{l=JSON.parse(s.value)}catch{throw new c(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let u=fme.safeParse(l);if(!u.success)throw new c(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let d=u.data;if(d.query.client_id!==r)throw new c(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let f=d.query.redirect_uri;if(f){if(!i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(f!==i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new c(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let p=Y0(d.resource)??Y0(d.query.resource),m=a??p;if(a&&p){let e=new Set(a),t=new Set(p);for(let n of e)if(!t.has(n))throw new c(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:d,effectiveResources:m,authorizedResources:p,authorizationCodeId:o}}async function zme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:l,resource:u}=e.body,d=Y0(u);if(!n)throw new c(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new c(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let f=n&&r,p=n&&o&&s;if(!f&&!p&&!i)throw new c(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await Rme(e,t,o,n,l,d),v=m.query.scope?.split(` `);if(!v)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});let y=await d2(e,t,n,r,v,i,`authorization_code`,a);if(x2(y,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!p)throw new c(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(p||f||i))throw new c(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let b=!!m.query?.code_challenge,x=!!s;if(b||x){if(b&&!x)throw new c(`UNAUTHORIZED`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!b&&x)throw new c(`UNAUTHORIZED`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await HW(s):void 0)!==m.query?.code_challenge)throw new c(`UNAUTHORIZED`,{error_description:`code verification failed`,error:`invalid_request`})}if(!m.userId)throw new c(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.internalAdapter.findUserById(m.userId);if(!S)throw new c(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let C=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!C||C.expiresAt</* @__PURE__ */ new Date)throw new c(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let w=m.authTime==null?Cpe(C):J0(m.authTime),T=k2(m.query.claims,N2(t));return g4(e,t,{client:y,scopes:m.query.scope?.split(` `)??[],user:S,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:C.id,nonce:m.query?.nonce,authTime:w,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:T,resources:h,originalResources:g})}async function Bme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,l=Y0(s);if(!n)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let u=await d2(e,t,n,r,void 0,i,`client_credentials`,a);if(u.tokenEndpointAuthMethod===`none`)throw new c(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let d=u.clientCredentialsScopes;if(!d?.length)throw new c(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let f=o?.split(` `);if(f){let e=new Set(d),t=f.filter(t=>!e.has(t)||Y2(t));if(t.length)throw new c(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return f||=[...d],g4(e,t,{client:u,scopes:f,grantType:`client_credentials`,resources:l})}async function Vme(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:l}=e.body,u=Y0(l);if(!n)throw new c(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new c(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let d=await a4(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,d.token,`refresh_token`)}]});if(!f)throw new c(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(f.clientId!==n||f.expiresAt</* @__PURE__ */ new Date)throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(u&&f.resources&&!u.every(e=>f.resources?.includes(e)))throw new c(`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 c(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}let h=await d2(e,t,n,r,m??p,i,`refresh_token`,a);if(f.revoked){if(h4(f)){let n=await Fme(e,f,await Ime(e,t,{client:h,refreshToken:f,scopes:m??p,resources:u??f.resources}));if(n)return Lme(e,n);throw new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await o4(e,n,f.userId),new c(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let g=await e.context.internalAdapter.findUserById(f.userId);if(!g)throw new c(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let _=f.authTime==null?void 0:J0(f.authTime);return g4(e,t,{client:h,scopes:m??p,user:g,grantType:`refresh_token`,referenceId:f.referenceId,authorizationCodeId:f.authorizationCodeId,sessionId:f.sessionId,refreshToken:f,resources:u??f.resources,authTime:_,requestedUserInfoClaims:f.requestedUserInfoClaims})}var _4=/* @__PURE__ */ k0({introspectEndpoint:()=>E4,requireActiveAccessToken:()=>Jme,requireActiveAccessTokenWithClaims:()=>w4,validateAccessToken:()=>C4});const v4=`Invalid access token`,Hme=`Bearer error="invalid_token", error_description="${v4}"`;function y4(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function Ume(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function b4(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&Zpe(e,t,r,a)}async function Wme(e,t,n,r){let i=t.disableJwtPlugin?void 0:q0(e.context),a=i?.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await OB(n,UB(await kK(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 Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new d(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return{active:!1};throw e}throw Error(e)}let l=c.aud;if(!await L2(e,t,l,[o])||!c.azp)return{active:!1};let u=await $0(e,t,c.azp);if(!u||u?.disabled||!await b4(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:Ume(l,o)}))return{active:!1};let f=c.sid;if(f){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:f}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=r4(c.cnf),c}async function Gme(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 d(`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 a2(t.storeTokens,i,`access_token`)}]});if(!a)throw new d(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_token`});if(!a.expiresAt||a.expiresAt</* @__PURE__ */ new Date||a.revoked)return y4();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await $0(e,t,a.clientId),!s||s?.disabled||!await b4(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return y4();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 y4()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await L2(e,t,o,[u]))return y4();let f=o?[...o]:void 0;f?.length&&a.scopes?.includes(`openid`)&&(f.includes(u)||f.push(u));let p=o?.length?await Qpe(e,t,o):{},m=s?await P2({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:f2(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:p}):{},h=(t.disableJwtPlugin?void 0:q0(e.context))?.options;return{payload:{...m,active:!0,iss:h?.jwt?.issuer??e.context.baseURL,aud:X0(f),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:r4(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function Kme(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new d(`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:q0(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:r4(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function x4(){return new d(`UNAUTHORIZED`,{error_description:v4,error:`invalid_token`},{"WWW-Authenticate":Hme})}function qme(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function S4(e,t,n,r){try{return{payload:await Wme(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(e)}try{return await Gme(e,t,n,r)}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw x4()}async function C4(e,t,n,r){return(await S4(e,t,n,r)).payload}async function Jme(e,t,n,r){let i=await C4(e,t,n,r);if(i.active)return i;throw x4()}async function w4(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await S4(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw x4()}async function T4(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 $0(e,t,i);if(!a)return n;let o=await g2(n.sub,a,t);return{...n,sub:o}}async function E4(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}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new d(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=tK(n)),!n?.length)throw new d(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await d2(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return T4(e,t,await C4(e,t,n,c.clientId),c)}catch(e){if(e instanceof d){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 T4(e,t,await Kme(e,t,(await a4(t,n)).token,c.clientId),c)}catch(e){if(e instanceof d){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof d){if(qme(e))return{active:!1};throw e}throw e instanceof Error?(xe.error(`Introspection error:`,e.message,e.stack),new d(`INTERNAL_SERVER_ERROR`)):(xe.error(`Introspection error:`,e),new d(`INTERNAL_SERVER_ERROR`))}}function D4(e){return e?.get(`sec-fetch-mode`)===`cors`}var Yme=/* @__PURE__ */ e({a:()=>k3,c:()=>a3,d:()=>X4,f:()=>J4,h:()=>Y4,i:()=>X3,l:()=>i3,n:()=>W3,o:()=>Ohe,r:()=>q3,s:()=>_3,t:()=>n6,u:()=>K4});async function Xme(e,t,n){let r=await K3.get(),i=r?.query;if(!i)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `)??[],s=N2(t),l=k2(a.get(`claims`),s),u=a.get(`client_id`);if(!u)throw new c(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let d=e.body.scope?.split(` `);if(d&&!d.every(e=>o?.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let f=e.body.claims,p=f===void 0?l:k2(f,s);if(f!==void 0&&!p.every(e=>l.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});if(e.body.accept!==!0)return{redirect:!0,url:Z3(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,n6(e,t))};let m=await fH(e),h=h2(a.get(`prompt`)??``).has(`login`),g=h&&v2(m?.session.createdAt,r?.signedQueryIssuedAt);if(h&&!g)return e?.headers?.set(`accept`,`application/json`),e.query=_2(a),await n(e);let _=await t.postLogin?.consentReferenceId?.({user:m?.user,session:m?.session,scopes:d??o}),v=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:u},{field:`userId`,value:m?.user.id},..._?[{field:`referenceId`,value:_}]:[]]}),y=Math.floor(Date.now()/1e3),b=a.getAll(`resource`),x={clientId:u,userId:m?.user.id,scopes:d??o,requestedUserInfoClaims:p,createdAt:/* @__PURE__ */ new Date(y*1e3),updatedAt:/* @__PURE__ */ new Date(y*1e3),resources:b.length?b:void 0,referenceId:_};if(v?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:v.id}],update:{resources:x.resources,scopes:x.scopes,requestedUserInfoClaims:x.requestedUserInfoClaims,updatedAt:/* @__PURE__ */ new Date(y*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...x,scopes:x.scopes}}),d&&a.set(`scope`,x.scopes.join(` `)),f!==void 0){let e=Hpe(a.get(`claims`),p);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let S=y2(a,`consent`);return g&&(S=y2(S,`login`),S=b2(S)),e.query=_2(S),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===m?.session.id})}async function Zme(e,t){if(e.body.selected===!0)return await Qme(e,t);if(e.body.created===!0)return await $me(e,t);if(e.body.postLogin===!0)return await ehe(e,t);throw new c(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function Qme(e,t){let n=(await K3.get())?.query;if(!n)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=_2(y2(new URLSearchParams(n),`select_account`)),await t(e)}async function $me(e,t){let n=(await K3.get())?.query;if(!n)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=_2(y2(r,`create`)),await t(e)}async function ehe(e,t){let n=await K3.get(),r=n?.query;if(!r)throw new c(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=_2(i);let a=await fH(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id})}async function the(e,t,n,r){return T0(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function nhe(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await OI(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 g2(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 rhe(e,t){let n=/* @__PURE__ */ new Date,r=await OI(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 ihe(e,t)}async function ihe(e,t){let n=e.context.logger,r=q0(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 w0(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=yU(32,`a-z`,`A-Z`,`0-9`),d=await the(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 O4(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function k4(e){let t=e.request?.headers??e.headers;if(!t||D4(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 A4(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${O4(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 j4(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function ahe(e){try{return new URL(j4(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function M4(e){return A4(`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="${O4(j4(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function N4(e){return A4(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${O4(e)}`:`Logged out.`}</p></main>`)}function ohe(e,t){return A4(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${O4(e)}</p></main>`,t)}function P4(e,t,n,r){if(k4(e))return ohe(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new d(t,{error:n,error_description:r})}function F4(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function I4(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:ahe(e),sameSite:`lax`}}async function L4(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(F4(e),JSON.stringify(r),e.context.secret,I4(e,300))}async function she(e){let t=await e.getSignedCookie(F4(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 R4(e){e.setCookie(F4(e),``,I4(e,0))}async function z4(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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function che(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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function B4(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new d(`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 d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function V4(e,t,n){try{return await $0(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function H4(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function lhe(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=H4(e.aud);return t.length===1?t[0]:null}async function uhe(e,t,n,r){if(r)return V4(e,t,r);let i;try{i=eV(n)}catch{return null}let a=lhe(i);return a?V4(e,t,a):null}async function dhe(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await n2(e,t.storeClientSecret,r.clientSecret),{payload:o}=await sB(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=q0(e.context).options,{payload:r}=await sB(n,UB(await kK(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==n6(e,t)||!H4(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 U4(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 W4(e,t){return t.post_logout_redirect_uri?U4(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 fhe(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await V4(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:U4(r,n.postLogoutRedirectUri,n.state)}async function G4(e,t,n={}){return t?k4(e)?(await L4(e,t.session.id,n),M4(e)):P4(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):k4(e)?(await L4(e,void 0,n),M4(e)):P4(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function phe(e,t){let n=await she(e),r=await z4(e);if(!n||n.expiresAt<=Date.now())return P4(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await fhe(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?P4(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await B4(e,r.session),lH(e),R4(e),i.uri?$3(e,i.uri):k4(e)?N4(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(R4(e),i.uri?$3(e,i.uri):k4(e)?N4(i.invalid?`The requested post-logout redirect was not registered.`:void 0):P4(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function mhe(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await z4(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await V4(e,t,i.client_id);if(!r)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return P4(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=W4(r,i)}return G4(e,a,n)}let o=await uhe(e,t,i.id_token_hint,i.client_id);if(!o)return a&&k4(e)?G4(e,a):P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return P4(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return P4(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await dhe(e,t,i.id_token_hint,o);if(!s)return a&&k4(e)?G4(e,a,i.client_id?W4(o,i):{}):P4(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await che(e,c),u=a?.session.id===c;if(a&&!u)return G4(e,a,W4(o,i));let d=U4(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await B4(e,f),u&&lH(e),R4(e),d.uri?$3(e,d.uri):k4(e)?N4(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function hhe(e,t){return phe(e,t)}function K4(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:t6(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:[...QW],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:[...QW],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:[...QW],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...YG],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function q4(e,t){let n=t.disableJwtPlugin?void 0:q0(e.context).options,r=B0(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:K4(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:V0(t),token_endpoint_auth_methods_supported:U0(t,{includeNone:i}),endpoint_auth_methods_supported:U0(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function J4(e,t){let{clientDiscoveries:n,authMetadata:r}=q4(e,t);return G0(e,t,`oauth-authorization-server`,{...e2(n),...r})}function Y4(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=q4(e,t),o={...a,claims_supported:N2(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 G0(e,t,`openid-configuration`,{...e2(i),...o})}function X4(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 Z4(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,...s}=t;if(!r)return J(e,{...s,onValidationError:async e=>{throw i&&await i(e),new d(`BAD_REQUEST`,{...Q4(e.issues,a,o)})}},n);let c=r,{body:l,query:u,...f}=s;async function p(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({...Q4(r.error.issues,a,o),ctx:e})})}return J(e,f,async e=>{let t=await p(e,`body`,l);if(!t.ok)return t.response;let r=await p(e,`query`,u);return r.ok?n(e):r.response})}function Q4(e,n,r=`invalid_request`){let i=e[0];if(!i)return{error:r,error_description:`Invalid request.`};let a=i.path?.[0],o=typeof a==`string`?a:void 0,s=o?n?.[o]:void 0,c=i.path?.length?t(i.path):``;return{error:ghe(i,s,r),error_description:vhe(i,c)}}function ghe(e,t,n){return typeof t==`string`?t:_he(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function _he(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function vhe(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 yhe=e=>RF(async t=>{if(!e.allowPublicClientPrelogin)throw new c(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await Q0(n,t.context.secret))throw new c(`UNAUTHORIZED`,{error:`invalid_signature`})}),$4={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},bhe=[`Ed25519`],xhe=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function e3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t3(e,t){return typeof e[t]==`string`&&e[t].length>0}function n3(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($4,e)}function r3(e){return bhe.some(t=>t===e)}function She(e){switch(e.kty){case`RSA`:return t3(e,`n`)&&t3(e,`e`);case`EC`:return n3(e.crv)&&t3(e,`x`)&&t3(e,`y`);case`OKP`:return r3(e.crv)&&t3(e,`x`);default:return!1}}function Che(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!QW.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return n3(e.crv)&&$4[e.crv]===e.alg;case`OKP`:return r3(e.crv)&&e.alg===`EdDSA`;default:return!1}}function i3(e){let t=e3(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(!e3(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||xhe.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!She(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!Che(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}}}const whe=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})),The=/* @__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(`.`),Ehe=/* @__PURE__ */ new Set([...whe,...The,`public`,`type`,`resources`,`client_credentials_scopes`]),Dhe=/* @__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 a3(e){return Dhe.has(e)}function o3(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!Ehe.has(e)))}async function s3(e,t,n,r){if(!t)throw new c(`UNAUTHORIZED`);if(!e.headers)throw new c(`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}))throw new c(`UNAUTHORIZED`)}var Ohe=/* @__PURE__ */ k0({consumeClientAssertion:()=>_3,isPrivateHostname:()=>m3,verifyClientAssertion:()=>Fhe});const c3=/* @__PURE__ */ new WeakMap,l3=65536,khe=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function u3(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 d3(e){let t=c3.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return c3.set(e,n),n}function f3(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const p3=[...QW];function m3(e){return!ZH(e)}function Ahe(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new d(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(m3(r.hostname))throw new d(`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 d(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function jhe(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function Mhe(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>l3)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>l3)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 h3(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||!khe.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await Mhe(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=i3(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function g3(){return new d(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function Nhe(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new d(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?B0(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new d(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});Ahe(e,n.jwksUri,n.clientDiscoveryId?jhe(n.clientId):void 0);let i=Date.now(),a=f3(n),o=d3(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await h3(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw g3()}if(!c.valid)throw g3();return u3(o,a,c.jwks,i),c.jwks}async function Phe(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?B0(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await h3(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(u3(d3(e),f3(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function _3(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 d(`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 d(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new d(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new d(`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 d(`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 d(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await CH(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=YV.encode(new Uint8Array(c).slice(0,24),{padding:!1});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 d(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function Fhe(e,t,n,r,i,a){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new d(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let o;try{o=$B(n)}catch{throw new d(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!o.alg||!p3.includes(o.alg))throw new d(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${o.alg}`,error:`invalid_client`});let s;try{s=eV(n)}catch{throw new d(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let c=s.sub??s.iss;if(!c)throw new d(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==c)throw new d(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let l=await $0(e,t,c);if(!l)throw new d(`BAD_REQUEST`,{error_description:`unknown client`,error:`invalid_client`});if(l.disabled)throw new d(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(l.tokenEndpointAuthMethod!==`private_key_jwt`)throw new d(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});let u=await Nhe(e,t,l),f=a??`${e.context.baseURL}/oauth2/token`,p=n6(e,t),m=[.../* @__PURE__ */ new Set([f,p])],h={issuer:c,subject:c,audience:m,algorithms:p3},g;try{({payload:g}=await OB(n,UB(u),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await Phe(t,l);if(e)try{({payload:g}=await OB(n,UB(e),h))}catch{throw new d(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new d(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new d(`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 _3(e,t,{namespace:`private_key_jwt:${c}`,payload:g,expectedAudience:_}),{clientId:c}}function v3(e,t,n){return new d(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...IF})}async function Ihe(e,t,n){let r=e.headers,i;try{i=xpe(r?.get(`authorization`))}catch{throw v3(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw v3(`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 d?e:new d(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw v3(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const Lhe=[`authorization_code`];function y3(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function b3(e){let t=e.grant_types??[...Lhe];if(t.length>0)return t;throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function Rhe(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function x3(e,t=`web`){let n=b3(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:Rhe(e,n)}}const zhe=/* @__PURE__ */ new Set([`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`]);function S3(e){throw new c(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function Bhe(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()}async function Vhe(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=/* @__PURE__ */ new Set([...r,...t.clientRegistrationAllowedResources??[]]);for(let e of n)if(!i.has(e))throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`});let a=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of a){let r=await H2(e,t,n);if(!r)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return a}function Hhe(e,t){let n;try{n=new URL(e)}catch{S3(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&S3(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&S3(`redirect URI localhost must not include trailing dots: ${e}`);let a=YH(n.hostname)||n.hostname===`localhost`,o=Bhe(e),s=o===`localhost`||o===`127.0.0.1`||o===`[::1]`;if(t===`web`){(!i||a)&&S3(`web clients require https redirect URIs on non-loopback hosts: ${e}`);return}if(i){a&&S3(`native clients must not use https loopback redirect URIs: ${e}`);return}if(r){s||S3(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`);return}(zhe.has(n.protocol)||!S2(n))&&S3(`native private-use redirect URI schemes must be well-formed reverse-domain names, omit the naming authority, and must not use a reserved scheme: ${e}`)}function Uhe(e){let t=i3(e);if(!t.valid)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}async function Whe(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new c(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await fH(e),i=r?void 0:await Ihe(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new c(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...IF});if(!r&&!a&&n.grant_types?.includes(`client_credentials`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let o=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];r&&await s3(e,r,t,`create`);let s=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),l=await O3(e,t,{metadata:n,registrationSource:`dynamic`,userId:s?void 0:r?.session.userId,referenceId:s,requestedResources:o});return e.setStatus(201),e.json(l)}async function C3(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=x3(e,r?null:`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(U0(t,{includeNone:!0})).has(a))throw new c(`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 c(`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,l=i.application_type;if(l!==void 0&&l!==`web`&&l!==`native`)throw new c(`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 c(`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??[])Hhe(e,l??(r?`native`:`web`));let u=new Set(V0(t));if(r){if(!o.some(e=>u.has(e)))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${o.join(`, `)}`})}else for(let e of o)if(!u.has(e))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${e}`});if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});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 c(`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 d=(i?.scope)?.split(` `).filter(e=>e.length),f=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,p=f?y3(t):t.scopes;if(p){let e=new Set(p);for(let t of d??[])if(!e?.has(t))throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(f&&i.require_pkce===!1)throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(m3(e.hostname))throw new c(`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 c(`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 c?e:new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&Uhe(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new c(`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 c(`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 c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must be an absolute URL`})}if(i.backchannel_logout_uri.includes(`#`))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not include a fragment component`});if(e.protocol!==`https:`)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must use https`});if(e.username||e.password)throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not contain credentials`});if(m3(e.hostname))throw new c(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not point to a private or reserved address`})}}const w3=Symbol(`client-registration-collision`);function T3(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[w3]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function E3(e,t,n){let r=x3(n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,n.registrationSource===`clientMetadataDocument`?null:`web`),i=r.token_endpoint_auth_method===`none`,a=r.token_endpoint_auth_method===`private_key_jwt`,o=W0(t,r.token_endpoint_auth_method);await C3(r,t,{registrationSource:n.registrationSource,ctx:e});let s=n.clientId??t.generateClientId?.()??yU(32,`a-z`,`A-Z`),l=i||a||o?void 0:t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`),u=l?await r2(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!i&&t.clientRegistrationRequirePKCE===!1,f=r.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...r,scope:y3(t).join(` `)}:r,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=M3({...h,redirect_uris:r.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?S0(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:s,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`&&r.application_type===void 0&&(_.applicationType=null);let v=await Vhe(e,t,n.registrationSource===`dynamic`?n.requestedResources??[]:[]),y=t.schema?.oauthClient?.modelName??`oauthClient`,b=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,x=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,S=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,C=await kI(e.context.adapter,async()=>{let t=await OI(e.context.adapter),r,i=!1;if(x){let e=await t.update({model:y,where:[{field:`clientId`,value:s},{field:`clientDiscoveryId`,value:S}],update:{..._,disabled:x.disabled,skipConsent:x.skipConsent,enableEndSession:x.enableEndSession,createdAt:x.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!e)throw new c(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=e}else{try{r=await t.create({model:y,data:{..._,createdAt:/* @__PURE__ */ new Date(p*1e3),updatedAt:/* @__PURE__ */ new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&A3(e)?{[w3]:!0,kind:`oauth-client-row-unique`,clientId:s,cause:e}:e}i=!0}let a=v.length===0?[]:await t.findMany({model:b,where:[{field:`clientId`,value:s}]}),o=new Set(a.map(e=>e.resourceId)),l=/* @__PURE__ */ new Date;for(let e of v)if(!o.has(e))try{await t.create({model:b,data:{clientId:s,resourceId:e,createdAt:l}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&A3(t)?{[w3]:!0,kind:`oauth-client-resource-link-unique`,clientId:s,resourceId:e,cause:t}:t}return{client:r,created:i}});return{client:C.client,clientSecret:l,resources:v,created:C.created}}function D3(e,t){let n=N3({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function Ghe(e,t){return{...D3(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function O3(e,t,n){return D3(await E3(e,t,n),t)}async function Khe(e,t,n){return Ghe(await E3(e,t,n),t)}function qhe(e,t){if(e&&e.clientDiscoveryId!==t)throw new c(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}async function k3(e,t,n){if(qhe(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new c(`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 c(`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 E3(e,t,r)}catch(i){if(!T3(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 E3(e,t,{...r,existingClient:s})}catch(e){throw T3(e)?e.cause:e}}}function A3(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 j3(e,t,n){let r=await fH(e);if(await s3(e,r,t,`create`),!r)throw new c(`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?X2(a??[]):[];Z2(s,b3(o),o.token_endpoint_auth_method,t),s.length>0&&await s3(e,r,t,`configure-client-credentials-scopes`);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s},u=n?.admin?await Khe(e,t,l):await O3(e,t,l);return e.setStatus(201),e.json(u)}function M3(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:C,response_types:w,application_type:T,disabled:ee,skip_consent:te,enable_end_session:E,require_pkce:ne,dpop_bound_access_tokens:re,subject_type:ie,reference_id:ae,metadata:oe}=e,D=r?/* @__PURE__ */ new Date(Number(r)*1e3):void 0,se=o?/* @__PURE__ */ new Date(o*1e3):void 0,ce=i?.split(` `),le=o3(oe??{}),ue=le&&Object.keys(le).length?JSON.stringify(le):void 0;return{clientId:t,clientSecret:n,disabled:ee,scopes:ce,userId:a,createdAt:se,expiresAt:D,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:C,responseTypes:w,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:T,skipConsent:te,enableEndSession:E,requirePKCE:ne,dpopBoundAccessTokens:re,subjectType:ie,referenceId:ae,metadata:ue}}function N3(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:C,responseTypes:w,applicationType:T,jwks:ee,jwksUri:te,skipConsent:E,enableEndSession:ne,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:D}=e,se=c?Math.round(new Date(c).getTime()/1e3):void 0,ce=o?Math.round(new Date(o).getTime()/1e3):void 0,le=i?.join(` `);return{...o3(f2(D)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?se??0:void 0,scope:le??void 0,user_id:a??void 0,client_id_issued_at:ce??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:ee?JSON.parse(ee):void 0,jwks_uri:te??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:C??void 0,response_types:w??void 0,application_type:T??void 0,disabled:r??void 0,skip_consent:E??void 0,enable_end_session:ne??void 0,require_pkce:re??void 0,dpop_bound_access_tokens:ie??void 0,subject_type:ae??void 0,reference_id:oe??void 0}}async function Jhe(e,t){let n=await fH(e);if(await s3(e,n,t,`read`),!n)throw new c(`UNAUTHORIZED`);let r=await $0(e,t,e.query.client_id);if(!r)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);let i=N3(r);return i.client_secret=void 0,i}async function P3(e,t,n){let r=await $0(e,t,n);if(!r||r.disabled)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return N3({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function Yhe(e,t){let n=await fH(e);if(await s3(e,n,t,`list`),!n)throw new c(`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=N3(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=N3(e);return t.client_secret=void 0,t}):null);throw new c(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function Xhe(e,t){let n=await fH(e);if(await s3(e,n,t,`delete`),!n)throw new c(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await $0(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function F3(e,t,n){let r=await fH(e);if(await s3(e,r,t,`update`),!r)throw new c(`UNAUTHORIZED`);let i=e.body.client_id;if(t.cachedTrustedClients?.has(i))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let a=await $0(e,t,i);if(!a)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,...s}=e.body.update,l=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,u=!l&&n?.admin&&o!==void 0&&Object.keys(s).length===0;if(!l&&!u)throw new c(`UNAUTHORIZED`);if(u&&await s3(e,r,t,`configure-client-credentials-scopes`),Object.keys(s).length===0&&o===void 0){let e=N3(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let d=s.grant_types??a.grantTypes??[],f=s.token_endpoint_auth_method??a.tokenEndpointAuthMethod,p=o===void 0?void 0:X2(o);p!==void 0&&(Z2(p,d,f,t),p.length>0&&!u&&await s3(e,r,t,`configure-client-credentials-scopes`)),await C3({...N3(a),...s},t,{ctx:e});let m={...M3(s)};!d.includes(`client_credentials`)||f===`none`?m.clientCredentialsScopes=[]:p!==void 0&&(m.clientCredentialsScopes=p),s.token_endpoint_auth_method&&(s.token_endpoint_auth_method===`private_key_jwt`?m.clientSecret=null:(m.jwks=null,m.jwksUri=null,m.clientSecret||=await r2(e,t,t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`))));let h=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...m,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!h)throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let g=N3(h);return g.client_secret=void 0,n?.admin?{...g,client_credentials_scopes:[...h.clientCredentialsScopes??[]]}:g}async function Zhe(e,t){let n=await fH(e);if(await s3(e,n,t,`rotate`),!n)throw new c(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new c(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await $0(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new c(`UNAUTHORIZED`)}else throw new c(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new c(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||yU(32,`a-z`,`A-Z`),o=a?await r2(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 c(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return N3({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}const I3=f().trim().min(1),L3=_(f().trim().min(1)).min(1),Qhe=e=>J(`/admin/oauth2/create-client`,{method:`POST`,body:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:I3.optional(),application_type:E([`web`,`native`]).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:L3.optional(),client_credentials_scopes:_(f().trim().min(1)).optional(),response_types:_(E([`code`])).optional(),client_secret_expires_at:n([f(),m()]).optional().default(0),skip_consent:T().optional(),enable_end_session:T().optional(),require_pkce:T().optional(),dpop_bound_access_tokens:T().optional(),subject_type:E([`public`,`pairwise`]).optional(),metadata:g(f(),se()).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=>j3(t,e,{admin:!0})),$he=e=>J(`/oauth2/create-client`,{method:`POST`,use:[mH],body:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),token_endpoint_auth_method:I3.optional(),application_type:E([`web`,`native`]).optional(),jwks:$2.optional(),jwks_uri:f().optional(),grant_types:L3.optional(),response_types:_(E([`code`])).optional(),dpop_bound_access_tokens:T().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=>j3(t,e)),ege=e=>J(`/oauth2/get-client`,{method:`GET`,use:[mH],query:D({client_id:f()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>Jhe(t,e)),tge=e=>J(`/oauth2/public-client`,{method:`GET`,use:[mH],query:D({client_id:f()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return P3(t,e,n)}),nge=e=>J(`/oauth2/public-client-prelogin`,{method:`POST`,use:[yhe(e)],body:D({client_id:f(),oauth_query:f().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return P3(t,e,n)}),rge=e=>J(`/oauth2/get-clients`,{method:`GET`,use:[mH],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>Yhe(t,e)),ige=e=>J(`/admin/oauth2/update-client`,{method:`PATCH`,body:D({client_id:f(),update:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),application_type:E([`web`,`native`]).optional(),grant_types:L3.optional(),client_credentials_scopes:_(f().trim().min(1)).optional(),response_types:_(E([`code`])).optional(),client_secret_expires_at:n([f(),m()]).optional(),skip_consent:T().optional(),enable_end_session:T().optional(),dpop_bound_access_tokens:T().optional(),metadata:g(f(),se()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>F3(t,e,{admin:!0})),age=e=>J(`/oauth2/update-client`,{method:`POST`,use:[mH],body:D({client_id:f(),update:D({redirect_uris:_(C2).min(1).optional(),scope:f().optional(),client_name:f().optional(),client_uri:f().optional(),logo_uri:f().optional(),contacts:_(f().min(1)).min(1).optional(),tos_uri:f().optional(),policy_uri:f().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional(),post_logout_redirect_uris:_(C2).min(1).optional(),backchannel_logout_uri:C2.optional(),backchannel_logout_session_required:T().optional(),application_type:E([`web`,`native`]).optional(),grant_types:L3.optional(),response_types:_(E([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>F3(t,e)),oge=e=>J(`/oauth2/client/rotate-secret`,{method:`POST`,use:[mH],body:D({client_id:f()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Zhe(t,e)),sge=e=>J(`/oauth2/delete-client`,{method:`POST`,use:[mH],body:D({client_id:f()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>Xhe(t,e));async function R3(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function cge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);return i}async function lge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function uge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function dge(e,t){let n=await fH(e);if(!n)throw new c(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new c(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await R3(e,t,r);if(!i)throw new c(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new c(`UNAUTHORIZED`);let a=await $0(e,t,i.clientId);if(!a)throw new c(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,l=s.scopes;if(l&&!l.every(e=>o?.includes(e)))throw new c(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let u=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:/* @__PURE__ */ new Date(u*1e3)}})}const fge=e=>J(`/oauth2/get-consent`,{method:`GET`,query:D({id:f()}),use:[mH],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>cge(t,e)),pge=e=>J(`/oauth2/get-consents`,{method:`GET`,use:[mH],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>lge(t,e)),mge=e=>J(`/oauth2/update-consent`,{method:`POST`,use:[mH],body:D({id:f(),update:D({scopes:_(f())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>dge(t,e)),hge=e=>J(`/oauth2/delete-consent`,{method:`POST`,use:[mH],body:D({id:f()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>uge(t,e));async function z3(e,t,n,r,i){if(!t)throw new c(`UNAUTHORIZED`);if(!e.headers)throw new c(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new c(`UNAUTHORIZED`)}const B3=e=>e.schema?.oauthResource?.modelName??`oauthResource`,V3=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,gge=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function H3(e){try{return decodeURIComponent(e)}catch{return e}}function _ge(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 vge(e,t){await z3(e,await fH(e),t,`create`);let n=e.body;if(!n?.identifier)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await Kpe(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:B3(t),data:_ge(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new c(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return V2(i.identifier),e.json(i,{status:201})}async function yge(e,t){await z3(e,await fH(e),t,`list`);let n=await e.context.adapter.findMany({model:B3(t)});return e.json(n??[])}async function bge(e,t){let n=H3(e.params.identifier);await z3(e,await fH(e),t,`read`,n);let r=await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]});if(!r)throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function xge(e,t){let n=H3(e.params.identifier);if(await z3(e,await fH(e),t,`update`,n),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]}))throw new c(`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:B3(t),where:[{field:`identifier`,value:n}],update:r}),V2(n);let i=await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]});if(!i)throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function Sge(e,t){let n=H3(e.params.identifier);if(await z3(e,await fH(e),t,`delete`,n),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:n}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:B3(t),where:[{field:`identifier`,value:n}]}),V2(n),e.json({deleted:!0})}async function Cge(e,t){let n=await fH(e),r=H3(e.params.identifier),i=H3(e.params.client_id);if(await z3(e,n,t,`link`,r),!await e.context.adapter.findOne({model:B3(t),where:[{field:`identifier`,value:r}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:gge(t),where:[{field:`clientId`,value:i}]}))throw new c(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:V3(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 wge(e,t){let n=await fH(e),r=H3(e.params.identifier),i=H3(e.params.client_id);return await z3(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:V3(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const U3=D({identifier:f().min(1).optional(),name:f().optional(),accessTokenTtl:m().int().positive().nullable().optional(),refreshTokenTtl:m().int().positive().nullable().optional(),signingAlgorithm:E(F2).nullable().optional(),signingKeyId:f().nullable().optional(),allowedScopes:_(f()).nullable().optional(),customClaims:g(f(),se()).nullable().optional(),dpopBoundAccessTokensRequired:T().optional(),disabled:T().optional(),metadata:g(f(),se()).nullable().optional()}),Tge=e=>J(`/admin/oauth2/resources`,{method:`POST`,body:U3.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>vge(t,e)),Ege=e=>J(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>yge(t,e)),Dge=e=>J(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>bge(t,e)),Oge=e=>J(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:U3,metadata:{SERVER_ONLY:!0}},async t=>xge(t,e)),kge=e=>J(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Sge(t,e)),Age=e=>J(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>Cge(t,e)),jge=e=>J(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>wge(t,e));async function Mge(e,t,n){let r=t.disableJwtPlugin?void 0:q0(e.context),i=r?.options;try{let a=await OB(n,UB(await kK(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r?.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL}),o=`${e.context.baseURL}/oauth2/userinfo`;if(!a.payload.azp||!await L2(e,t,a.payload.aud,[o]))return null}catch(e){if(e instanceof Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new d(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return null;throw e}throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function Nge(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 d(`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 a2(t.storeTokens,i,`access_token`)}]});if(!a)throw new d(`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 Pge(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await a2(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`});if(i.revoked)throw await o4(e,r,i.userId),new d(`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 o4(e,r,i.userId),new d(`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 Fge(e,t,n,r){try{return await Mge(e,t,r)}catch(e){if(e instanceof d){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await Nge(e,t,r,n)}catch(e){if(!(e instanceof d))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new d(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function Ige(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}=p2(await m2(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new d(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=tK(n)),!n?.length)throw new d(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await d2(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await Fge(e,t,c.clientId,n)}catch(e){if(e instanceof d){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 Pge(e,t,(await a4(t,n)).token,c.clientId)}catch(e){if(e instanceof d){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new d(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof d){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(xe.error(`Introspection error:`,e.message,e.stack),new d(`INTERNAL_SERVER_ERROR`)):(xe.error(`Introspection error:`,e),new d(`INTERNAL_SERVER_ERROR`))}}const Lge={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}}}},W3=[`openid`,`profile`,`email`,`offline_access`],G3=D({id_token_hint:f().optional(),client_id:f().optional(),post_logout_redirect_uri:C2.optional(),state:f().optional()}),K3=EI(()=>null),q3=K3.get,J3=/* @__PURE__ */ new WeakMap,Y3=`signedQueryIssuedAtMs`;function Rge(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 X3=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 r=new Set((e.scopes??W3).filter(e=>e.length));if(t){for(let e of t)if(!r.has(e))throw new l(`clientRegistrationAllowedScope ${e} not found in scopes`)}for(let t of e.advertisedMetadata?.scopes_supported??[])if(!r?.has(t))throw new l(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let i=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(!i.has(e))throw new l(`${t} resource ${e} not found in resources`);let a=/* @__PURE__ */ new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...M2.filter(e=>r.has(j2[e].scope))]),o={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(r),claims:Array.from(a),clientRegistrationAllowedScopes:t};if(R0(o.extensions),o.pairwiseSecret&&o.pairwiseSecret.length<32)throw new l(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(o.grantTypes&&o.grantTypes.includes(`refresh_token`)&&!o.grantTypes.includes(`authorization_code`))throw new l(`refresh_token grant requires authorization_code grant`);if(o.disableJwtPlugin&&(o.storeClientSecret===`hashed`||typeof o.storeClientSecret==`object`&&`hash`in o.storeClientSecret))throw new l(`unable to store hashed secrets because id tokens will be signed with secret`);if(!o.disableJwtPlugin&&(o.storeClientSecret===`encrypted`||typeof o.storeClientSecret==`object`&&(`encrypt`in o.storeClientSecret||`decrypt`in o.storeClientSecret)))throw new l(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let s=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=o.disableJwtPlugin?t.baseURL:q0(t)?.options?.jwt?.issuer??t.baseURL,a=`/`;try{a=new URL(i).pathname.replace(/\/$/,``)||``}catch{a=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let s={context:t},c=/* @__PURE__ */ new Set([`/.well-known/oauth-authorization-server${a}`,`${a}/.well-known/oauth-authorization-server`]),l=`${a}/.well-known/openid-configuration`,u=c.has(r),d=o.scopes?.includes(`openid`)&&r===l,f=t=>{let n=X4(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 o.scopes?.includes(`openid`)?{response:f(Y4(s,o))}:{response:f(J4(s,o))};if(d)return{response:f(Y4(s,o))}},u=Z4(`/oauth2/authorize`,{method:[`GET`,`POST`],body:D({}).passthrough(),redirectOnError:s6(o),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=>Kge(e,o,e.authorizeSettings??{isAuthorize:!0})),d=(e,t)=>RJ(u,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.7`,options:o,onRequest:s,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new l("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(await K2(e,o),ime(o),!o.disableJwtPlugin){let t=q0(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 nhe(t,o,{sessionId:e.id,userId:e.userId});if(!n)return;let r=J3.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),J3.set(t,r)},async after(e,t){if(!t)return;let n=J3.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&J3.delete(t),!r)return;let i=rhe(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:RF(async e=>{let t=e.body.oauth_query;if(!await Q0(t,e.context.secret))throw new c(`BAD_REQUEST`,{error:`invalid_signature`});let n=ape(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(A0),r.delete(j0),await K3.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Pue({query:r.toString(),...n?{[Y3]:n.getTime()}:{}})})}],after:[{matcher(e){return gV(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:RF(async e=>{let t=gV(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await K3.get(),r=(await Mue())?.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(),c=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(c.includes(`text/html`)||c.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let l=n?.signedQueryIssuedAt??Rge(r?.[Y3]),u=y2(a,`login`);return v2(o.session.createdAt,l)&&(u=b2(u)),e.query=_2(u),await d(e)})}]},endpoints:{getOAuthServerConfig:J(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>o.scopes&&o.scopes.includes(`openid`)?Y4(e,o):J4(e,o)),getOpenIdConfig:J(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(o.scopes&&!o.scopes.includes(`openid`))throw new c(`NOT_FOUND`);return Y4(e,o)}),oauth2Authorize:u,oauth2Consent:J(`/oauth2/consent`,{method:`POST`,body:D({accept:T().meta({description:`Accept or deny user consent for a set of scopes`}),scope:f().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:O2.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:f().optional().meta({description:`The redirected page's query parameters`})}),use:[mH],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=>Xme(e,o,d)),oauth2Continue:J(`/oauth2/continue`,{method:`POST`,body:D({selected:T().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:T().optional().meta({description:`Confirms an account was registered`}),postLogin:T().optional().meta({description:`Confirms organization and/or team selection.`}),oauth_query:f().optional().meta({description:`The redirected page's query parameters`})}),use:[mH],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=>Zme(e,d)),oauth2Token:Z4(`/oauth2/token`,{method:`POST`,cloneRequest:!0,body:D({grant_type:f().trim().min(1),client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),code:f().optional(),code_verifier:f().optional(),redirect_uri:C2.optional(),refresh_token:f().optional(),resource:n([Q2,_(Q2).min(1)]).optional(),scope:f().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 Jpe(e.request);t&&t.length>1&&(e.body.resource=t)}return vme(e,o)}),oauth2Introspect:Z4(`/oauth2/introspect`,{method:`POST`,cloneRequest:!0,body:D({client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),token:f(),token_type_hint:f().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=>E4(e,o)),oauth2Revoke:Z4(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:D({client_id:f().optional(),client_secret:f().optional(),client_assertion:f().optional(),client_assertion_type:f().optional(),token:f(),token_type_hint:f().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=>Ige(e,o)),oauth2UserInfo:J(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:D({access_token:f().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=>gme(e,o)),oauth2EndSession:Z4(`/oauth2/end-session`,{method:[`GET`,`POST`],body:G3.optional(),query:G3.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=>mhe(e,o)),oauth2EndSessionConfirmation:Z4(`/oauth2/end-session/confirm`,{method:`POST`,body:D({action:ee(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>hhe(e,o)),registerOAuthClient:Z4(`/oauth2/register`,{method:`POST`,body:t4,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=>Whe(e,o)),adminCreateOAuthClient:Qhe(o),createOAuthClient:$he(o),getOAuthClient:ege(o),getOAuthClientPublic:tge(o),getOAuthClientPublicPrelogin:nge(o),getOAuthClients:rge(o),adminUpdateOAuthClient:ige(o),updateOAuthClient:age(o),rotateClientSecret:oge(o),deleteOAuthClient:sge(o),getOAuthConsent:fge(o),getOAuthConsents:pge(o),updateOAuthConsent:mge(o),deleteOAuthConsent:hge(o),adminCreateOAuthResource:Tge(o),adminListOAuthResources:Ege(o),adminGetOAuthResource:Dge(o),adminUpdateOAuthResource:Oge(o),adminDeleteOAuthResource:kge(o),adminLinkClientResource:Age(o),adminUnlinkClientResource:jge(o)},schema:YI(structuredClone(Lge),o?.schema),rateLimit:[...o.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:o.rateLimit?.token?.window??60,max:o.rateLimit?.token?.max??20}],...o.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:o.rateLimit?.authorize?.window??60,max:o.rateLimit?.authorize?.max??30}],...o.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:o.rateLimit?.introspect?.window??60,max:o.rateLimit?.introspect?.max??100}],...o.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:o.rateLimit?.revoke?.window??60,max:o.rateLimit?.revoke?.max??30}],...o.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:o.rateLimit?.register?.window??60,max:o.rateLimit?.register?.max??5}],...o.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:o.rateLimit?.userinfo?.window??60,max:o.rateLimit?.userinfo?.max??60}]]}};function zge(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function Bge(e){let{max_age:t,...n}=e;return n}function Z3(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()}`:iI(e,o)}function Vge(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 Hge={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function Uge(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q3(e){return typeof e==`string`?e:void 0}function Wge(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...Uge(n)?n:{}}}const $3=(e,t)=>{let n=D4(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 e6(e,t,n,r,i){return $3(e,Z3(n.redirect_uri,r,i,n.state,n6(e,t)))}function t6(e){try{let t=new URL(e);return t.protocol!==`https:`&&!XH(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function n6(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=q0(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return t6(n)}function r6(e,t,n){return Z3(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function i6(e){let t;try{t=new URL(e)}catch{return}let n=YH(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 a6(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=i6(t);return e.find(e=>e===t?!0:a?i6(e)===a:!1)}function o6(e){if(!C2.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function Gge(e,t,n,r){if(!n||!r)return null;let i;try{i=await $0(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=a6(a,r);if(t.validateRedirectUri){if(!o6(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function s6(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await Gge(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?$3(r,Z3(a,t,n,typeof i.state==`string`?i.state:void 0,n6(r,e),Vge(i))):$3(r,r6(r,t,n))}}async function Kge(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new d(`NOT_FOUND`);if(!e.request)throw new d(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=Wge(e,n);e.query=i;let a=Q3(i.request),o=Q3(i.request_uri);if(a!==void 0&&o!==void 0)return s6(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return s6(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=Q3(i.client_id);if(!n)return s6(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return s6(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 s6(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=e4.safeParse(i);if(!s.success){let n=Q4(s.error.issues,Hge);return s6(t)({...n,ctx:e})}if(i=s.data,e.query=i,await K3.set({query:c6(i).toString()}),!i.response_type)return s6(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?h2(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return $3(e,r6(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return $3(e,r6(e,`unsupported_response_type`,`unsupported response type`));let u=await $0(e,t,i.client_id);if(!u)return $3(e,r6(e,`invalid_client`,`client_id is required`));if(u.disabled)return $3(e,r6(e,`client_disabled`,`client is disabled`));if(!l2(u,`authorization_code`))return $3(e,r6(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let f=u.redirectUris??[],p=!1;if(i.redirect_uri){let e=!!a6(f,i.redirect_uri);if(t.validateRedirectUri&&o6(i.redirect_uri))try{p=await t.validateRedirectUri(i.redirect_uri,f,e)}catch{p=!1}else t.validateRedirectUri||(p=e)}if(!p)return $3(e,r6(e,`invalid_redirect`,`invalid redirect uri`));let m=i.scope?.split(` `).filter(e=>e);if(m){let n=new Set(u.scopes??t.scopes),r=m.filter(e=>!n?.has(e));if(r.length)return $3(e,Z3(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,n6(e,t)))}m||(m=u.scopes??t.scopes??[],i.scope=m.join(` `));let h=m.includes(`openid`);if(i.claims!==void 0&&!h)return $3(e,Z3(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,n6(e,t)));if(h&&!Bpe(i.claims))return $3(e,Z3(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,n6(e,t)));if(h&&!Vpe(i.claims,`0`))return $3(e,Z3(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,n6(e,t)));let g=k2(i.claims,N2(t));if(i.resource!==void 0)try{await R2(e,t,{resource:i.resource,clientId:u.clientId,requestedScopes:m})}catch(n){if(n instanceof d){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return $3(e,Z3(i.redirect_uri,r,a,i.state,n6(e,t)))}throw n}let _=x2(u,{scopes:m,nonce:i.nonce});if(_&&(!i.code_challenge||!i.code_challenge_method))return $3(e,Z3(i.redirect_uri,`invalid_request`,_.valueOf(),i.state,n6(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return $3(e,Z3(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,n6(e,t)));if(![`S256`].includes(i.code_challenge_method))return $3(e,Z3(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,n6(e,t)))}let v=Y0(i.resource)??[],y=await fH(e),b=i.max_age,x=y!=null&&b!==void 0&&zge(new Date(y.session.createdAt),b,/* @__PURE__ */ new Date);if(!y||y!=null&&b!==void 0&&!x||c?.has(`login`)||c?.has(`create`))return l?e6(e,t,i,`login_required`,`authentication required`):u6(e,t,c?.has(`create`)?`create`:`login`);if(x&&(i=Bge(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return u6(e,t,`select_account`);if(n?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m}))return l?e6(e,t,i,`account_selection_required`,`End-User account selection is required`):u6(e,t,`select_account`);if(t.signup?.shouldRedirect){let n=await t.signup.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m});if(n)return l?e6(e,t,i,`interaction_required`,`End-User interaction is required`):u6(e,t,`create`,{page:typeof n==`string`?n:void 0})}if(!n?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:r.headers,user:y.user,session:y.session,scopes:m}))return l?e6(e,t,i,`interaction_required`,`End-User interaction is required`):u6(e,t,`post_login`);if(c?.has(`consent`))return u6(e,t,`consent`,{sessionId:y.session.id});let S=await t.postLogin?.consentReferenceId?.({user:y.user,session:y.session,scopes:m});if(u.skipConsent)return l6(e,t,{query:i,clientId:u.clientId,userId:y.user.id,sessionId:y.session.id,authTime:new Date(y.session.createdAt).getTime(),referenceId:S,resource:v});let C=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:u.clientId},{field:`userId`,value:y.user.id},...S?[{field:`referenceId`,value:S}]:[]]});if(!C||!m.every(e=>C.scopes.includes(e))||!g.every(e=>(C.requestedUserInfoClaims??[]).includes(e)))return l?e6(e,t,i,`consent_required`,`End-User consent is required`):u6(e,t,`consent`,{sessionId:y.session.id});let w=C?.resources??[];return v.some(e=>!w.includes(e))?l?e6(e,t,i,`consent_required`,`End-User consent is required`):u6(e,t,`consent`,{sessionId:y.session.id}):l6(e,t,{query:i,clientId:u.clientId,userId:y.user.id,sessionId:y.session.id,authTime:new Date(y.session.createdAt).getTime(),referenceId:S,resource:v})}function c6(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 l6(e,t,n){let r=yU(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await i2(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`,n6(e,t)),$3(e,s.toString())}async function u6(e,t,n,r){let i=await qge(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 d(`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 $3(e,`${r?.page??a}?${i}`)}async function qge(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=c6(e.query);a.set(`exp`,String(i)),a.set(A0,String(r)),a.delete(`sig`),a.delete(j0),n?.postLoginClearedForSession&&a.set(j0,n.postLoginClearedForSession),ipe(a);let o=await OW(N0(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const Jge=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,Yge=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function d6(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function Xge(e){if(Jge.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`:ZH(t.hostname)?null:`client_id URL must not target a private or reserved address`}function Zge(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 Qge(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||S2(t)}catch{return!1}}function $ge(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(a3(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=pme.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(Yge.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&&!i3(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=>Qge(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(!ZH(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&&S2(n);if(n.protocol!==`https:`&&n.protocol!==`http:`&&!i)return{valid:!1,error:`all values for ${e} must use HTTP(S) or an authority-free private-use scheme`};if(i)continue;let a=r&&XH(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(...Zge(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const f6=5e3,p6=5120,e_e=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,m6=`Failed to fetch metadata document (network error or redirect blocked)`,h6=`cimd`;function g6(e){return new d(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function _6(){return g6(`Metadata document exceeds ${p6/1024}KB size limit`)}async function t_e(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw _6();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(),_6();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 n_e(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 r_e(e,t,n,r){let i=Xge(t);if(i)throw g6(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw g6(`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()},f6);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw g6(c?`Metadata document fetch timed out after ${f6}ms`:m6)}if(o.redirected)throw g6(`Metadata document fetch must not follow redirects`);let i=n_e(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw g6(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw g6(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!e_e.test(l))throw g6(`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>p6)throw await o.body?.cancel(),_6()}u=await t_e(o,p6,s.signal)}catch(e){throw c?g6(`Metadata document fetch timed out after ${f6}ms`):e instanceof d?e:g6(m6)}let f;try{f=JSON.parse(u)}catch{throw g6(`Metadata document is not valid JSON`)}let p=$ge(t,f,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!p.valid)throw g6(p.error);for(let t of p.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:`modified`,metadata:p.metadata,cacheHeaders:i}}finally{clearTimeout(l)}}async function v6(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await k3(e,i,{clientId:t,clientDiscoveryId:h6,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 y6={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function i_e(e){return new d(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function b6(e){return new d(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function a_e(e,t){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw new l(`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=(S0(e,t)-t)*1e3;if(!Number.isFinite(n)||n<0)throw Error(`negative duration`);return n}catch{throw new l(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}function x6(e,t){if(!Number.isInteger(e)||e<1)throw new l(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function o_e(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:a_e(t?.minimumFetchInterval??y6.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:x6(t?.maximumConcurrentFetches??y6.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:x6(t?.maximumConcurrentFetchesPerOrigin??y6.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:x6(t?.maximumFetchesPerMinute??y6.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:x6(t?.maximumFetchesPerOriginPerMinute??y6.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function S6(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function s_e(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(S0(e,n)-n)*1e3)}function c_e(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 C6(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function l_e(e,t,n){let{directives:r,duplicates:i}=c_e(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=s_e(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=C6(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=C6(r.get(`s-maxage`)),m=r.has(`max-age`),h=C6(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 u_e(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 d_e(e,t,n,r){let i=l_e(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function f_e(e){let t=e.metadataRevalidationInterval??`60m`,n=e.maxCacheEntries??1e3;if(!Number.isInteger(n)||n<1)throw new l(`cimd maxCacheEntries must be a positive integer`);let r=o_e(e),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=[],u=0,d=e=>{let t=i.get(e);if(t)return i.delete(e),i.set(e,t),t},f=(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)},p=(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 b6(`metadata fetch client state is at capacity`)}},m=(e,t)=>{let r=s.get(e);if(r)return S6(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(S6(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw b6(`metadata fetch origin state is at capacity`)}let i={activeFetchCount:0,fetchStartTimesMs:[]};return s.set(e,i),i},h=e=>{let t=Date.now(),n=o.get(e);if(r.minimumFetchIntervalMs>0&&n!==void 0&&t-n<r.minimumFetchIntervalMs)throw b6(`metadata document fetch is within the per-client minimum interval`);p(e,t);let i=new URL(e).origin,a=m(i,t);if(S6(c,t),u>=r.maximumConcurrentFetches)throw b6(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw b6(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw b6(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw b6(`metadata fetch rate limit exceeded for client origin`);o.delete(e),o.set(e,t),c.push(t),a.fetchStartTimesMs.push(t),u+=1,a.activeFetchCount+=1;let s=!1;return()=>{s||(s=!0,--u,--a.activeFetchCount)}};return async(n,r,s)=>{if(!d6(r))return null;let c=n.context.getPlugin(`oauth-provider`);if(!c)throw new l(`cimd discovery invoked without the oauth-provider plugin installed`);let u=c.options,p=d(r),m=Date.now();if(p&&p.expiresAt>m)return s||v6(n,r,p.metadata,e,u);let g=a.get(r);if(g)return g;let _=h(r),v=(async()=>{let a=await r_e(n,r,e,p?{etag:p.etag,lastModified:p.lastModified}:void 0);if(a.status===`not-modified`&&!p)throw i_e(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:p.metadata,l=await v6(n,r,c,e,u,s??void 0),d=d_e(c,a.status===`modified`?a.cacheHeaders:u_e(p.responseCacheHeaders,a.cacheHeaders),t,Date.now());return d?f(r,d):i.delete(r),o.delete(r),l})();a.set(r,v);try{return await v}catch(e){throw o.delete(r),o.set(r,Date.now()),e}finally{a.get(r)===v&&a.delete(r),_()}}}function p_e(e){return{id:h6,matches:d6,resolve:f_e(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const m_e=e=>{let t=p_e(e);return{id:`cimd`,version:`1.7.7`,init(e){ppe(e,{clientDiscovery:t})}}},h_e=cae(U({typ:H,payload:MS(H,ZC)})),g_e=e=>({id:`signer`,endpoints:{signDocument:J.serverOnly({method:`POST`,body:h_e},async t=>t.json({token:await T0(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),__e=/* @__PURE__ */ new Set([204,205,304]);function v_e(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 y_e=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 yt(r.hostname,{all:!0,verbatim:!0});if(i.length===0)throw TypeError(`metadata hostname returned no DNS addresses`);for(let e of i)if(!ZH(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=uee(r,{agent:!1,headers:o,method:n.method,servername:lt(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`||__e.has(r)?null:at.toWeb(t);e(new Response(i,{headers:v_e(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function b_e(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)})}))}}const x_e=b_e(y_e),S_e=f1(W(U({client_id:H,resource:H,scopes:wC(W(H)),approvedAt:zS(LC),refreshedAt:zS(LC)})));function C_e(e,t){let n=V(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*L(new M$({error:`Client not found`}))}),r=V(`Clients.revoke`)(function*(e,t,r){return yield*n(e,r),yield*v1(r,{clientId:e,resource:t}),{revoked:!0}});return{revoke:(t,n)=>m1(e,e=>r(t,n,e)),delete:t=>m1(e,e=>I(function*(){return yield*n(t,e),yield*_1(e,t,null),yield*e`DELETE FROM oauthClient WHERE clientId = ${t}`,{deleted:!0}})),connections:V(`Clients.connections`)(function*(){let e=new Date(yield*ep).toISOString();return(yield*S_e(yield*t`WITH live AS (
|
|
513
513
|
SELECT clientId, referenceId, scopes, createdAt FROM oauthRefreshToken
|
|
514
514
|
WHERE revoked IS NULL AND expiresAt > ${e}
|
|
515
515
|
), held AS (
|
|
@@ -524,16 +524,16 @@ Most of the features of Better Auth will not work correctly.`);let u=t.secrets??
|
|
|
524
524
|
FROM held h
|
|
525
525
|
JOIN oauthResource r ON h.referenceId = ${g1} || r.identifier
|
|
526
526
|
LEFT JOIN oauthConsent c ON c.clientId = h.clientId AND c.referenceId = h.referenceId
|
|
527
|
-
ORDER BY client_id, resource`)).map(e=>({...e,scopes:e.scopes.filter(e=>!x1.includes(e))}))}),block:(t,i)=>m1(e,e=>I(function*(){return i?yield*r(t,void 0,e):yield*n(t,e),yield*e`UPDATE oauthClient SET disabled = ${+!!i}, updatedAt = ${yield*ep} WHERE clientId = ${t}`,{blocked:i}}))}}const
|
|
527
|
+
ORDER BY client_id, resource`)).map(e=>({...e,scopes:e.scopes.filter(e=>!x1.includes(e))}))}),block:(t,i)=>m1(e,e=>I(function*(){return i?yield*r(t,void 0,e):yield*n(t,e),yield*e`UPDATE oauthClient SET disabled = ${+!!i}, updatedAt = ${yield*ep} WHERE clientId = ${t}`,{blocked:i}}))}}const w_e=f1(FS([U({user_version:ES})])),T_e=[e=>I(function*(){yield*v1(e,{}),yield*e`DELETE FROM oauthClientResource WHERE clientId IN (SELECT clientId FROM oauthClient WHERE userId IS NULL)`,yield*e`PRAGMA user_version = 1`}),(e,t)=>I(function*(){let n=`${t}/mcp`,r=b1(t),i=t=>z(e`SELECT 1 FROM oauthResource WHERE identifier = ${t}`,e=>e.length>0);if((yield*i(n))&&(yield*i(r)))return yield*Dp(/* @__PURE__ */ Error(`A resource is registered at ${r}, which administration now takes: delete it and start again`));yield*v1(e,{resource:n}),yield*e`PRAGMA defer_foreign_keys = ON`,yield*e`UPDATE oauthResource SET identifier = ${r} WHERE identifier = ${n}`,yield*e`UPDATE oauthClientResource SET resourceId = ${r} WHERE resourceId = ${n}`,yield*e`PRAGMA user_version = 2`})],E_e=V(`Database.upgrade`)(function*(e,t,n){let r=e=>z(R(e`PRAGMA user_version`,w_e),([e])=>e.user_version),i=yield*r(t);for(let[t,a]of T_e.entries())t>=i&&(yield*m1(e,e=>I(function*(){if(yield*a(e,n),(yield*r(e))!==t+1)return yield*Dp(/* @__PURE__ */ Error(`Upgrade step ${t} must set user_version = ${t+1}`))})))}),D_e=e=>typeof e==`string`,O_e=f1(U({id:H})),k_e=V(`Auth.open`)(function*(e,t){let n={disableSettingJwtHeader:!0,jwt:{issuer:`${e.baseURL}/api/auth`},jwks:{keyPairConfig:{alg:`EdDSA`,crv:`Ed25519`}}},r=Lm(yield*em());yield*Op(()=>ft(lee(e.database),{recursive:!0,mode:448}));let i=yield*fm(bp(()=>bde(e.database)),e=>yp(()=>e.close())),{sql:a}=i,o=C_e(i.kysely,a),s=V(`Auth.owner`)(function*(){let e=yield*a`SELECT id FROM user LIMIT 1`;if(e.length)return(yield*O_e(e[0])).id}),l=X3({loginPage:`/login`,consentPage:`/consent`,scopes:[...x1],resources:[{identifier:b1(e.baseURL),name:`clankerauth administration`,allowedScopes:[...x1,y1.read,y1.write]}],resourceSeedMode:`merge`,rateLimit:{register:{window:60,max:10}},postLogin:{page:`/consent`,shouldRedirect:()=>!1,consentReferenceId:async({scopes:e})=>{let t=await q3(),n=new URLSearchParams(t?.query),i=n.getAll(`resource`);if(i.length!==1||!await r(u.get(i[0])))throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`Choose exactly one Resource`});let a=n.get(`client_id`);if(!a||!await r(u.hasAccess(a,i[0])))throw new c(`BAD_REQUEST`,{error:`invalid_target`,error_description:`Client access is required`});let o=await r(u.scopesFor(i));if(e.some(e=>!o.includes(e)))throw new c(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`Resource scopes changed; start authorization again`});return h1(i[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}),u=yield*Tde(i.kysely,a,()=>f,e=>{l.options.scopes=e},b1(e.baseURL)),d={appName:`clankerauth`,baseURL:e.baseURL,secret:Lg(e.secret),database:{db:i.kysely,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(await OI((await f.$context).adapter)).count({model:`user`}))throw new c(`CONFLICT`,{message:`Setup already completed`})}}}},hooks:{before:RF(async e=>{if(e.path===`/oauth2/register`){let t=e.body.redirect_uris;!e.body.application_type&&Array.isArray(t)&&t.some(e=>{if(!D_e(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:[`x-clankerauth-peer`]}},rateLimit:{enabled:!0,storage:`database`,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:5}}},plugins:[qfe({defaultPrefix:`clankerauth_`,maximumNameLength:100,enableSessionForAPIKeys:!1,keyExpiration:{defaultExpiresIn:null,minExpiresIn:0},rateLimit:{enabled:!1}}),rpe(n),g_e(n),l,m_e({fetchClientMetadataResource:(e,n)=>(t.cimdTransport??x_e)(e,n),metadataProfile:`mcp-2026-07-28`,metadataRevalidationInterval:300,maxCacheEntries:1e3,metadataFetchPolicy:{maximumConcurrentFetches:8,maximumConcurrentFetchesPerOrigin:2,maximumFetchesPerMinute:60,maximumFetchesPerOriginPerMinute:15}})]},{auth:f,context:p}=yield*V(`Auth.initialize`)(function*(){let t=yield*bp(()=>A1(d));if(t.schemaProblems.length)return yield*L(/* @__PURE__ */ Error(`Database schema requires manual repair`));yield*bp(()=>t.runMigrations()),yield*E_e(i.kysely,a,e.baseURL);let n=ffe(d);return{auth:n,context:yield*bp(()=>n.$context)}},Cm)();return yield*u.synchronize(),{auth:f,context:p,sql:a,database:i.kysely,owner:s,settings:e,resources:u,clients:o,setup:yield*LT(1)}});var w6=class e extends j()(`clankerauth/Auth`){static layer=(t,n={})=>Hf(e,k_e(t,n))};const T6=V(`Auth.createOwner`)(function*(e,t){if(yield*e.owner())return yield*L(new N$({error:`Setup already completed`}));let{headers:n}=yield*l1(()=>e.auth.api.signUpEmail({body:{name:`Owner`,email:t.email.trim(),password:t.password},returnHeaders:!0}));return n.getSetCookie()},(e,t)=>t.setup.withPermit(e)),A_e=f1(W(U({clientId:H,name:zS(H),redirectUris:wC(W(H)),tokenEndpointAuthMethod:zS(H),applicationType:zS(H),scopes:zS(wC(W(H))),grantTypes:zS(wC(W(H))),disabled:zS(ES),clientDiscoveryId:zS(H),userId:zS(H)}))),E6=z(w6,e=>{let{auth:t,settings:n}=e;return{setup:V(`Administration.setup`)(function*(t){let n=yield*T6(e,t);return yield*(yield*w1).add(n),{created:!0}}),list:V(`Administration.list`)(function*(){let{email:t}=yield*z$,r=yield*e.sql`
|
|
528
528
|
SELECT clientId, name, redirectUris, tokenEndpointAuthMethod, applicationType, scopes,
|
|
529
529
|
grantTypes, disabled, clientDiscoveryId, userId
|
|
530
530
|
FROM oauthClient ORDER BY createdAt, clientId
|
|
531
|
-
`,i=(yield*j_e(r)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?e.userId===null?`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})),a=yield*gp({resources:e.resources.list(),clientAccess:e.resources.access(),connections:e.clients.connections()});return{clients:i,resources:a.resources.map(e=>({...e,builtIn:e.identifier===b1(n.baseURL)})),clientAccess:a.clientAccess,connections:a.connections,email:t,issuer:`${n.baseURL}/api/auth`}}),create:V(`Administration.create`)(function*(n){let{providerHeaders:r}=yield*z$,i=yield*e.resources.scopesFor(n.resources),a=yield*r,o=yield*l1(()=>t.api.adminCreateOAuthClient({headers:a,body:{client_name:n.client_name,redirect_uris:[...n.redirect_uris],token_endpoint_auth_method:n.token_endpoint_auth_method,application_type:n.application_type,grant_types:[`authorization_code`,`refresh_token`],scope:i.join(` `),skip_consent:!0}}));return yield*e.resources.setAccess(o.client_id,n.resources).pipe(Wp(()=>l1(()=>t.api.deleteOAuthClient({headers:a,body:{client_id:o.client_id}})))),o}),update:V(`Administration.update`)(function*(e){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>t.api.updateOAuthClient({headers:r,body:{client_id:e.client_id,update:{client_name:e.client_name,redirect_uris:[...e.redirect_uris],application_type:e.application_type}}}))}),access:V(`Administration.access`)(function*(t){return yield*z$,{clientAccess:yield*e.resources.setAccess(t.client_id,t.resources)}}),createResource:V(`Administration.createResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.create(t,r)}),updateResource:V(`Administration.updateResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.update(t,r)}),deleteResource:V(`Administration.deleteResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.delete(t.identifier,r)}),delete:V(`Administration.delete`)(function*(t){return yield*z$,yield*e.clients.delete(t.client_id)}),revoke:V(`Administration.revoke`)(function*(t){return yield*z$,yield*e.clients.revoke(t.client_id,t.resource)}),block:V(`Administration.block`)(function*(t){return yield*z$,yield*e.clients.block(t.client_id,t.blocked)}),rotate:V(`Administration.rotate`)(function*(e){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>t.api.rotateClientSecret({headers:r,body:e}))})}}),D6=/*#__PURE__*/ U({method:BS([`GET`,`POST`,`PATCH`,`PUT`,`DELETE`,`HEAD`,`OPTIONS`,`TRACE`,`QUERY`]),url:H,urlParams:W(LS([H,H])),hash:yS(H),headers:PS(H,G([H,VC(H)]))}).annotate({identifier:`HttpRequestDetails`}),M_e=/*#__PURE__*/ U({status:dC,headers:PS(H,G([H,VC(H)]))}).annotate({identifier:`HttpResponseDetails`}),O6=`~effect/ai/AiError/Reason`,k6=()=>F_e.pipe(YS(N({})),fae(N({}))),N_e=e=>{let t=Pn(e),n={};for(let e in t){let r=t[e];ar(n,e,Fg(r)?r.toString():r)}return n};var P_e=class e extends (/*#__PURE__*/ qC(`effect/ai/AiError/NetworkError`)({_tag:/*#__PURE__*/ ZS(`NetworkError`),reason:/*#__PURE__*/ BS([`TransportError`,`EncodeError`,`InvalidUrlError`]),request:D6,description:/*#__PURE__*/ yS(H)})){[O6]=O6;get isRetryable(){return this.reason===`TransportError`}static fromRequestError(t){return new e({description:t.description,reason:t._tag,request:{hash:Li(t.request.hash),headers:N_e(t.request.headers),method:t.request.method,url:t.request.url,urlParams:Array.from(t.request.urlParams)}})}get message(){let e=`${this.request.method} ${this.request.url}`,t=this.description?`${this.reason}: ${this.description}`:`${this.reason}: A network error occurred.`;t+=` (${e})`;let n=``;switch(this.reason){case`EncodeError`:n+=`Check that the request body data is properly formatted and matches the expected content type.`;break;case`InvalidUrlError`:n+=`Verify that the URL format is correct and that all required parameters have been provided.`,n+=` Check for any special characters that may need encoding.`;break;case`TransportError`:n+=`Check your network connection and verify that the requested URL is accessible.`}return t+=`\n\n${n}`,t}};const F_e=/*#__PURE__*/ PS(H,/*#__PURE__*/ VS(yae)),A6=/*#__PURE__*/ U({promptTokens:yS(dC),completionTokens:yS(dC),totalTokens:yS(dC)}).annotate({identifier:`UsageInfo`}),j6=/*#__PURE__*/ U({request:D6,response:yS(M_e),body:yS(H)}).annotate({identifier:`HttpContext`});var I_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/RateLimitError`)({_tag:/*#__PURE__*/ ZS(`RateLimitError`),retryAfter:/*#__PURE__*/ yS(zC),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!0}get message(){let e=`Rate limit exceeded`;return this.retryAfter&&(e+=`. Retry after ${Eo(this.retryAfter)}`),e}},L_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/QuotaExhaustedError`)({_tag:/*#__PURE__*/ ZS(`QuotaExhaustedError`),resetAt:/*#__PURE__*/ yS(LC),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`Quota exhausted`;return this.resetAt&&(e+=`. Resets at ${this.resetAt}`),`${e}. Check your account billing and usage limits.`}},R_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/AuthenticationError`)({_tag:/*#__PURE__*/ ZS(`AuthenticationError`),kind:/*#__PURE__*/ BS([`InvalidKey`,`ExpiredKey`,`MissingKey`,`InsufficientPermissions`,`Unknown`]),description:/*#__PURE__*/ yS(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`${this.kind}: ${{InvalidKey:`Verify your API key is correct`,ExpiredKey:`Your API key has expired. Generate a new one`,MissingKey:`No API key provided. Set the appropriate environment variable`,InsufficientPermissions:`Your API key lacks required permissions`,Unknown:`Authentication failed. Check your credentials`}[this.kind]}`;return this.description&&(e+=`. ${this.description}`),e}},z_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ContentPolicyError`)({_tag:/*#__PURE__*/ ZS(`ContentPolicyError`),description:H,metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){return`Content policy violation: ${this.description}`}},B_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/InvalidRequestError`)({_tag:/*#__PURE__*/ ZS(`InvalidRequestError`),parameter:/*#__PURE__*/ yS(H),constraint:/*#__PURE__*/ yS(H),description:/*#__PURE__*/ yS(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`Invalid request`;return this.parameter&&(e+=`: parameter '${this.parameter}'`),this.constraint&&(e+=` ${this.constraint}`),this.description&&(e+=`. ${this.description}`),e}},V_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/InternalProviderError`)({_tag:/*#__PURE__*/ ZS(`InternalProviderError`),description:H,metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!0}get message(){return`Internal provider error: ${this.description}`}},H_e=class e extends (/*#__PURE__*/ qC(`effect/ai/AiError/InvalidOutputError`)({_tag:/*#__PURE__*/ ZS(`InvalidOutputError`),description:H,metadata:/*#__PURE__*/ k6(),usage:/*#__PURE__*/ yS(A6)})){[O6]=O6;get isRetryable(){return!0}static fromSchemaError(t){return new e({description:t.message})}get message(){return`Invalid output: ${this.description}`}},U_e=class e extends (/*#__PURE__*/ qC(`effect/ai/AiError/StructuredOutputError`)({_tag:/*#__PURE__*/ ZS(`StructuredOutputError`),description:H,responseText:H,metadata:/*#__PURE__*/ k6(),usage:/*#__PURE__*/ yS(A6)})){[O6]=O6;get isRetryable(){return!0}static fromSchemaError(t,n){return new e({description:t.message,responseText:n})}get message(){return`Structured output validation failed: ${this.description}`}},W_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/UnsupportedSchemaError`)({_tag:/*#__PURE__*/ ZS(`UnsupportedSchemaError`),description:H,metadata:/*#__PURE__*/ k6()})){[O6]=O6;get isRetryable(){return!1}get message(){return`Unsupported schema: ${this.description}`}},G_e=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/UnknownError`)({_tag:/*#__PURE__*/ ZS(`UnknownError`),description:/*#__PURE__*/ yS(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ yS(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){return this.description??`Unknown error`}},M6=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ToolNotFoundError`)({_tag:/*#__PURE__*/ ZS(`ToolNotFoundError`),toolName:H,availableTools:/*#__PURE__*/ W(H)})){[O6]=O6;get isRetryable(){return!0}get message(){let e=this.availableTools.length>0?this.availableTools.join(`, `):`none`;return`Tool '${this.toolName}' not found. Available tools: ${e}`}},N6=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ ZS(`ToolParameterValidationError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}},P6=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/InvalidToolResultError`)({_tag:/*#__PURE__*/ ZS(`InvalidToolResultError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Tool '${this.toolName}' returned invalid result: ${this.description}`}},F6=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ToolResultEncodingError`)({_tag:/*#__PURE__*/ ZS(`ToolResultEncodingError`),toolName:H,toolResult:ES,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Failed to encode result for tool '${this.toolName}': ${this.description}`}};const K_e=/*#__PURE__*/ G([I_e,L_e,R_e,z_e,B_e,V_e,P_e,H_e,U_e,W_e,G_e,M6,N6,P6,F6,class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ToolConfigurationError`)({_tag:/*#__PURE__*/ ZS(`ToolConfigurationError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Invalid configuration for tool '${this.toolName}': ${this.description}`}},class extends (/*#__PURE__*/ qC(`effect/ai/AiError/ToolkitRequiredError`)({_tag:/*#__PURE__*/ ZS(`ToolkitRequiredError`),pendingApprovals:/*#__PURE__*/ W(H),description:/*#__PURE__*/ yS(H)})){[O6]=O6;get isRetryable(){return!1}get message(){return`Toolkit required to resolve pending tool approvals: ${this.pendingApprovals.join(`, `)}`}},class extends (/*#__PURE__*/ qC(`effect/ai/AiError/InvalidUserInputError`)({_tag:/*#__PURE__*/ ZS(`InvalidUserInputError`),description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Invalid user input: ${this.description}`}}]),I6=`~effect/ai/AiError`;var L6=class extends (/*#__PURE__*/ qC(`effect/ai/AiError/AiError`)({_tag:/*#__PURE__*/ ZS(`AiError`),module:H,method:H,reason:K_e})){[I6]=I6;cause=this.reason;get isRetryable(){return this.reason.isRetryable}get retryAfter(){return`retryAfter`in this.reason?this.reason.retryAfter:void 0}get message(){return`${this.module}.${this.method}: ${this.reason.message}`}};const q_e=e=>A(e,I6),J_e=e=>A(e,O6),R6=e=>new L6(e),z6=(e,t)=>Object.assign(Object.create(Object.getPrototypeOf(e)),e,t),B6={"~effect/ai/Tool":{_Requirements:k},pipe(){return bt(this,arguments)},addDependency(){return z6(this)},setParameters(e){return z6(this,{parametersSchema:e,jsonSchema:void 0})},setSuccess(e){return z6(this,{successSchema:e})},setFailure(e){return z6(this,{failureSchema:e})},setNeedsApproval(e){return z6(this,{needsApproval:e})},annotate(e,t){return z6(this,{annotations:aa(this.annotations,e,t)})},annotateMerge(e){return z6(this,{annotations:ga(this.annotations,e)})}};({...B6}),{...B6};const Y_e=e=>{let t=Object.assign(Object.create(B6),e);return t.id=`effect/ai/Tool/${e.name}`,t},X_e=(e,t)=>{let n=t?.success??jS,r=t?.failure??wS;return Y_e({name:e,description:t?.description,parametersSchema:t?.parameters??tve,successSchema:n,failureSchema:r,failureMode:t?.failureMode??`error`,annotations:na(),needsApproval:t?.needsApproval})},Z_e=e=>{if(e.description!==void 0)return e.description;if(_S(e.parametersSchema))return Gb(e.parametersSchema.ast)};var V6=class extends (/*#__PURE__*/ j()(`effect/ai/Tool/Title`)){},H6=class extends (/*#__PURE__*/ j()(`effect/ai/Tool/Meta`)){};const U6=/*#__PURE__*/ ya(`effect/ai/Tool/Readonly`,{defaultValue:Tt}),W6=/*#__PURE__*/ ya(`effect/ai/Tool/Destructive`,{defaultValue:wt}),G6=/*#__PURE__*/ ya(`effect/ai/Tool/Idempotent`,{defaultValue:Tt}),K6=/*#__PURE__*/ ya(`effect/ai/Tool/OpenWorld`,{defaultValue:wt}),q6=/*#__PURE__*/ ya(`effect/ai/Tool/Strict`,{defaultValue:()=>void 0}),Q_e=e=>da(e.annotations,q6),$_e=/*#__PURE__*/ U({type:BS([`execution-denied`,`execution-interrupted`]),reason:H}).annotate({identifier:`ToolExecutionFailure`}),eve=e=>G([L6,e.failureSchema,$_e]),tve=/*#__PURE__*/ PS(H,wS),J6=`~effect/ai/Toolkit`,Y6=/*#__PURE__*/ ya(`effect/ai/Toolkit/FailureOrigin`,{defaultValue:()=>`result`}),X6=(e,t)=>Id(hd(e),ia(Y6,t)),nve={.../*#__PURE__*/ si({label:`Toolkit`,evaluate:/*#__PURE__*/ B(function*(e){let t=this.tools,n=e.context,r=/* @__PURE__ */ new WeakMap,i=e=>{let t=r.get(e);if(Ht(t)){let i=n.mapUnsafe.get(e.id),a=_S(e.parametersSchema)?lS(e.parametersSchema):e=>N(e),o=fS(e.successSchema),s=fS(eve(e));t={context:i.context,handler:i.handler,decodeParameters:a,encodeResult:(e,t)=>t?s(e):o(e)},r.set(e,t)}return t};return{tools:t,handle:B(function*(e,n,r,a){let o=Object.hasOwn(t,e)?t[e]:void 0;if(yield*Dm({tool:e,parameters:n}),Ht(o))return yield*R6({module:`Toolkit`,method:`${e}.handle`,reason:new M6({toolName:e,availableTools:Object.keys(t)})});let s=i(o),c=(t,n)=>s.encodeResult(t,n).pipe(Hp(n=>R6({module:`Toolkit`,method:`${e}.handle`,reason:new F6({toolName:e,toolResult:t,description:n.message})}))),l=yield*Np(s.decodeParameters(n,a));if(Ea(l)){let t=R6({module:`Toolkit`,method:`${e}.handle`,reason:new N6({toolName:e,description:l.failure.message})});return o.failureMode===`error`?yield*Tp(X6(t,`parameters`)):HE(z(c(t,!0),e=>({result:t,isFailure:!0,failureOrigin:`parameters`,preliminary:!1,encodedResult:e})))}let u=l.success,d=yield*$w(),f={toolCallId:r,preliminary:e=>Ip(nT(d,{result:e,isFailure:!1,preliminary:!0}))},p=yield*s.handler(u,f).pipe(R(e=>nT(d,{result:e,isFailure:!1,preliminary:!1})),cm(e=>ga(s.context,e)),$p({onFailure:e=>oT(d,e),onSuccess:()=>cT(d)}),Mm),m=t=>aS(t)?R6({module:`Toolkit`,method:`${e}.handle`,reason:new P6({toolName:e,description:`Tool handler returned invalid result: ${t.message}`})}):J_e(t)?R6({module:`Toolkit`,method:`${e}.handle`,reason:t}):t;return JE(d).pipe(Coe(e=>{let t=m(e),n=aS(e)?`result`:`handler`;return o.failureMode===`error`?hoe(X6(t,n)):poe({result:t,isFailure:!0,failureOrigin:n,preliminary:!1})}),_oe(B(function*(e){let t=yield*c(e.result,e.isFailure);return{...e,encodedResult:t}})),Aoe(aw(p)))})}})}),[J6]:J6,of:k,toHandlers(e){return I({self:this},function*(){let t=yield*tm(),n=hp(e)?yield*e:e,r=/* @__PURE__ */ new Map;for(let[e,i]of Object.entries(n)){let n=Object.hasOwn(this.tools,e)?this.tools[e]:void 0;n!==void 0&&r.set(n.id,{name:e,handler:i,context:t})}return Qi(r)})},toLayer(e){return Wf(this.toHandlers(e))},toJSON(){return{_id:`effect/ai/Toolkit`,tools:Array.from(Object.values(this.tools)).map(e=>e.name)}}},rve=e=>Object.assign(function(){},nve,{tools:e}),ive=(...e)=>{let t={};for(let n of e)ar(t,n.name,n);return t},ave=(...e)=>rve(ive(...e)),Z6=`~effect/rpc/RpcMiddleware`,ove=()=>(e,t)=>{let n=tr(),r;n!==0&&(nr(2),r=new globalThis.Error,nr(n));function i(){}let a=i;return Object.setPrototypeOf(i,Object.getPrototypeOf(j(e))),i.key=e,Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[Z6]=Z6,a.error=t?.error??wS,a.requiredForClient=t?.requiredForClient??!1,i},Q6=(e,t)=>{let n=P(t);return vS(e).pipe(JS({decode:wv(n),encode:vv()}),YS(n))},Z=e=>vS(e).pipe(US(bS(yS(e)),{decode:vv(),encode:xv(Bi(Ii))})),sve=/*#__PURE__*/ G([H,iC]),$6=/*#__PURE__*/ G([H,iC]);var e8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ FS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ Z($6)}),[K]))}))){},t8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(K)}))){},n8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(K)}))){};const cve=H;({...e8.fields});var r8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({...t8.fields,nextCursor:/*#__PURE__*/ Z(cve)}))){};const lve=/*#__PURE__*/ BS([`user`,`assistant`]);var i8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({audience:/*#__PURE__*/ Z(/*#__PURE__*/ W(lve)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(H)}))){},a8=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/Icon`)({src:H,mimeType:/*#__PURE__*/ Z(H),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ W(H)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ BS([`light`,`dark`]))})){},o8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ Z(H),version:H,icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),description:/*#__PURE__*/ Z(H),websiteUrl:/*#__PURE__*/ Z(H)}))){},uve=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ PS(H,/*#__PURE__*/ U({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ PS(/*#__PURE__*/ CS([H,`/`,H]),QC)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(kS)})),sampling:/*#__PURE__*/ Z(/*#__PURE__*/ U({context:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ U({}))})),elicitation:/*#__PURE__*/ Z(/*#__PURE__*/ U({form:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),url:/*#__PURE__*/ Z(/*#__PURE__*/ U({}))}))})){},dve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ PS(H,/*#__PURE__*/ U({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ PS(/*#__PURE__*/ CS([H,`/`,H]),QC)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(kS)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ Z(kS),listChanged:/*#__PURE__*/ Z(kS)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(kS)}))}))){},s8=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/McpErrorBase`)({code:dC,message:H,data:/*#__PURE__*/ Z(TS)})){};const c8=-32601,l8=-32602,u8=-32603,d8=-32020;var f8=class extends (/*#__PURE__*/ qC(`effect/ai/McpSchema/ParseError`)({...s8.fields,_tag:/*#__PURE__*/ ZS(`ParseError`),code:/*#__PURE__*/ ZS(-32700)})){},p8=class extends (/*#__PURE__*/ qC(`effect/ai/McpSchema/InvalidRequest`)({...s8.fields,_tag:/*#__PURE__*/ ZS(`InvalidRequest`),code:/*#__PURE__*/ ZS(-32600)})){},m8=class extends (/*#__PURE__*/ qC(`effect/ai/McpSchema/MethodNotFound`)({...s8.fields,_tag:/*#__PURE__*/ ZS(`MethodNotFound`),code:/*#__PURE__*/ ZS(c8)})){},h8=class extends (/*#__PURE__*/ qC(`effect/ai/McpSchema/InvalidParams`)({...s8.fields,_tag:/*#__PURE__*/ ZS(`InvalidParams`),code:/*#__PURE__*/ ZS(l8)})){},g8=class e extends (/*#__PURE__*/ qC(`effect/ai/McpSchema/InternalError`)({...s8.fields,_tag:/*#__PURE__*/ ZS(`InternalError`),code:/*#__PURE__*/ ZS(u8)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const _8=/*#__PURE__*/ G([f8,p8,m8,h8,g8,s8]);var fve=class extends (/*#__PURE__*/ sP(`ping`,{success:/*#__PURE__*/ U({}),error:_8,payload:/*#__PURE__*/ HS(e8)})){},pve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({...t8.fields,protocolVersion:H,capabilities:dve,serverInfo:o8,instructions:/*#__PURE__*/ Z(H)}))){},mve=class extends (/*#__PURE__*/ sP(`initialize`,{success:pve,error:_8,payload:{...e8.fields,protocolVersion:H,capabilities:uve,clientInfo:o8}})){},v8=class extends (/*#__PURE__*/ sP(`notifications/cancelled`,{payload:{...n8.fields,requestId:sve,reason:/*#__PURE__*/ Z(H)}})){},y8=class extends (/*#__PURE__*/ sP(`notifications/progress`,{payload:{...n8.fields,progressToken:$6,progress:iC,total:/*#__PURE__*/ Z(iC),message:/*#__PURE__*/ Z(H)}})){},hve=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/Resource`)({uri:H,name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),mimeType:/*#__PURE__*/ Z(H),annotations:/*#__PURE__*/ Z(i8),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),size:/*#__PURE__*/ Z(dC),_meta:/*#__PURE__*/ Z(K)})){},b8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ Z(H),_meta:/*#__PURE__*/ Z(K)}))){},gve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({...b8.fields,text:H}))){},_ve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({...b8.fields,blob:jC}))){};({...r8.fields}),{...r8.fields},{...t8.fields},{...e8.fields};var x8=class extends (/*#__PURE__*/ sP(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ HS(n8)})){};({...e8.fields}),{...e8.fields};var S8=class extends (/*#__PURE__*/ sP(`notifications/resources/updated`,{payload:{...n8.fields,uri:H}})){},vve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),required:/*#__PURE__*/ Z(kS)}))){},yve=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/Prompt`)({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ W(vve)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),_meta:/*#__PURE__*/ Z(K)})){},C8=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({type:/*#__PURE__*/ ZS(`text`),text:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){};const bve=/*#__PURE__*/ G([C8,class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({type:/*#__PURE__*/ ZS(`image`),data:jC,mimeType:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({type:/*#__PURE__*/ ZS(`audio`),data:jC,mimeType:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({type:/*#__PURE__*/ ZS(`resource`),resource:/*#__PURE__*/ G([gve,_ve]),annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({...hve.fields,type:/*#__PURE__*/ ZS(`resource_link`)}))){}]);({...r8.fields}),{...t8.fields},{...e8.fields};var w8=class extends (/*#__PURE__*/ sP(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ HS(n8)})){},xve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({title:/*#__PURE__*/ Z(H),readOnlyHint:/*#__PURE__*/ Q6(kS,Tt),destructiveHint:/*#__PURE__*/ Q6(kS,wt),idempotentHint:/*#__PURE__*/ Q6(kS,Tt),openWorldHint:/*#__PURE__*/ Q6(kS,wt)}))){};const T8=/*#__PURE__*/ FS(/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ PS(H,K)),required:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))}),[K]),E8=K;var D8=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/Tool`)({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),inputSchema:T8,outputSchema:/*#__PURE__*/ Z(E8),annotations:/*#__PURE__*/ Z(xve),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),_meta:/*#__PURE__*/ Z(K)})){};({...r8.fields});var O8=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/CallToolResult`)({...t8.fields,content:/*#__PURE__*/ W(bve),structuredContent:/*#__PURE__*/ Z(QC),isError:/*#__PURE__*/ Z(kS)})){};({...e8.fields});var k8=class extends (/*#__PURE__*/ sP(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ HS(n8)})){};const A8=/*#__PURE__*/ BS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({...e8.fields});var j8=class extends (/*#__PURE__*/ sP(`notifications/message`,{payload:/*#__PURE__*/ U({...n8.fields,level:A8,logger:/*#__PURE__*/ Z(H),data:TS})})){},Sve=class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ BS([`auto`,`required`,`none`]))})){},Cve=class extends (/*#__PURE__*/ $S()(/*#__PURE__*/ U({name:/*#__PURE__*/ Z(H)}))){};(class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ W(Cve)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1})))})){}).fields,D8.fields,Sve.fields,{...t8.fields};const wve=/*#__PURE__*/ U({$schema:/*#__PURE__*/ Z(H),type:/*#__PURE__*/ ZS(`object`),properties:/*#__PURE__*/ PS(H,/* @__PURE__ */ G([/* @__PURE__ */ G([class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ ZS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),enum:/*#__PURE__*/ W(H),enumNames:/*#__PURE__*/ Z(/*#__PURE__*/ W(H)),default:/*#__PURE__*/ Z(H)})){},/* @__PURE__ */ G([class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/UntitledSingleSelectEnum`)({type:/*#__PURE__*/ ZS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),enum:/*#__PURE__*/ W(H),default:/*#__PURE__*/ Z(H)})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/TitledSingleSelectEnum`)({type:/*#__PURE__*/ ZS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),oneOf:/*#__PURE__*/ W(/*#__PURE__*/ U({const:H,title:H})),default:/*#__PURE__*/ Z(H)})){}]),/* @__PURE__ */ G([class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/UntitledMultiSelectEnum`)({type:/*#__PURE__*/ ZS(`array`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minItems:/*#__PURE__*/ Z(dC),maxItems:/*#__PURE__*/ Z(dC),items:/*#__PURE__*/ U({type:/*#__PURE__*/ ZS(`string`),enum:/*#__PURE__*/ W(H)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ ZS(`array`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minItems:/*#__PURE__*/ Z(dC),maxItems:/*#__PURE__*/ Z(dC),items:/*#__PURE__*/ U({anyOf:/*#__PURE__*/ W(/*#__PURE__*/ U({const:H,title:H}))}),default:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))})){}])]),class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitationString`)({type:/*#__PURE__*/ ZS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minLength:/*#__PURE__*/ Z(dC),maxLength:/*#__PURE__*/ Z(dC),format:/*#__PURE__*/ Z(/*#__PURE__*/ BS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(H)})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ BS([`number`,`integer`]),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minimum:/*#__PURE__*/ Z(iC),maximum:/*#__PURE__*/ Z(iC),default:/*#__PURE__*/ Z(iC)})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ ZS(`boolean`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),default:/*#__PURE__*/ Z(kS)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))}),Tve=/*#__PURE__*/ G([class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitRequestFormParams`)({...e8.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ SS(`form`)),message:H,requestedSchema:wve})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitRequestURLParams`)({...e8.fields,mode:/*#__PURE__*/ SS(`url`),message:H,elicitationId:H,url:H})){}]),Eve=/*#__PURE__*/ G([class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitAcceptResult`)({...t8.fields,action:/*#__PURE__*/ SS(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ PS(H,/*#__PURE__*/ G([H,iC,kS,/*#__PURE__*/ W(H)])))})){},class extends (/*#__PURE__*/ KC(`@effect/ai/McpSchema/ElicitDeclineResult`)({...t8.fields,action:/*#__PURE__*/ BS([`cancel`,`decline`])})){}]);var Dve=class extends (/*#__PURE__*/ sP(`elicitation/create`,{success:Eve,error:_8,payload:Tve})){},Ove=class extends (/*#__PURE__*/ sP(`notifications/elicitation/complete`,{payload:{elicitationId:H}})){};Dve.payloadSchema;var kve=class extends (/*#__PURE__*/ Vo(`McpReverseOperationUnsupported`)){},M8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/McpRequestContext`)){},N8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/McpServerClient`)){},P8=class extends (/*#__PURE__*/ ove()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},Ave=class extends (/*#__PURE__*/ wP(v8,y8,j8,S8,x8,k8,w8,Ove)){},F8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/EnabledWhen`)){};const I8={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var jve=class extends (/*#__PURE__*/ Vo(`ResourceNotFound`)){},Mve=class extends (/*#__PURE__*/ Vo(`ToolNotFound`)){},Nve=class extends (/*#__PURE__*/ Vo(`InvalidToolInput`)){},Pve=class extends (/*#__PURE__*/ Vo(`InvalidToolContinuation`)){},Fve=class extends (/*#__PURE__*/ Vo(`ToolExecutionError`)){},Ive=class extends (/*#__PURE__*/ Vo(`PromptNotFound`)){};const L8=/*#__PURE__*/ Ro(),Lve=/*#__PURE__*/ P(()=>{let e=/* @__PURE__ */ new Map,t=[],n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{tools:{register:t=>P(()=>{e.set(t.descriptor.name,t)}),list:t=>P(()=>{let n=[];for(let r of e.values())r.isVisible(t)&&n.push(r.descriptor);return n}),call:(t,n)=>Sp(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new Mve({name:t.name}):r.handle(t,n)})},resources:{register:e=>P(()=>{let n=t.findIndex(t=>t.descriptor.uri===e.descriptor.uri);n===-1?t.push(e):t[n]=e}),registerTemplate:e=>P(()=>{let t=n.findIndex(t=>t.descriptor.uriTemplate===e.descriptor.uriTemplate);t===-1?n.push(e):n[t]=e}),list:e=>P(()=>t.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),listTemplates:e=>P(()=>n.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),read:B(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 jve({uri:e})})},prompts:{register:e=>P(()=>{r.set(e.descriptor.name,e)}),list:e=>P(()=>Array.from(r.values()).filter(t=>t.isVisible(e)).map(e=>e.descriptor)),get:B(function*(e,t,n){let i=r.get(e);return i===void 0||!i.isVisible(n.protocol)?yield*new Ive({name:e}):yield*i.get(t,n)})},completions:{register:(e,t)=>P(()=>{i.set(e,t)}),complete:B(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 h8({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=Jee(a.values,100);return{...a,values:o,hasMore:a.hasMore===!0||o.length<a.values.length}})},registrationPresence:P(()=>({tools:e.size>0,resources:t.length>0||n.length>0,prompts:r.size>0}))}}),Rve=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),R8={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}},z8=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=Yh(e.slice(9,-2));if(!Ea(r))try{return Rve.decode(r.success)}catch{return}},zve=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),B8=e=>({clientId:e.clientId,protocol:zve(e),requestContext:M8.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),V8=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),H8=e=>Yt(e)&&(e.type===`tool_use`||e.type===`tool_result`),Bve=e=>Yt(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!Yt(e))return!1;let t=e.content;return Array.isArray(t)?t.some(H8):H8(t)}):!1:!1;var U8=class e extends (/*#__PURE__*/ Vo(`ProtocolError`)){static fromTool(t){let n=TO(t).pipe(DO(`ToolNotFound`,e=>`Tool '${e.name}' not found`),DO(`UnsupportedByProtocol`,e=>`${e.feature} is not supported by MCP ${e.protocolVersion}`),OO({InvalidToolInput:e=>e.message,InvalidToolContinuation:e=>e.message,ToolExecutionError:e=>e.message}),PO);return new e({code:t._tag===`ToolExecutionError`?u8:l8,message:n})}static fromFeature(t){if(A(t,`_tag`)){if(t._tag===`PromptNotFound`&&A(t,`name`)&&It(t.name))return new e({code:l8,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&A(t,`uri`)&&It(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=Vve(t);return Da(n)?new e(n.success):new e({code:u8,message:`MCP feature handler failed`})}};const Vve=/*#__PURE__*/ cae(/* @__PURE__ */ U({code:iC,message:H,data:/*#__PURE__*/ vS(ES)})),W8=(e,t,n)=>pS(e)(n).pipe(R(lS(t))),Hve=/*#__PURE__*/ V(function*(e,t){return L8.$match(t,{Cancelled:e=>({tag:v8._tag,payload:v8.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:y8._tag,payload:y8.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:j8._tag,payload:j8.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:S8._tag,payload:S8.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:x8._tag,payload:x8.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:k8._tag,payload:k8.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:w8._tag,payload:w8.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),G8=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},Uve=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=YC(e.payloadSchema);n={decode:lS(r),encode:fS(r)},t.set(e,n)}return n},r=(t,n,r)=>e.handlerRpcs===void 0||e.makeHandlers===void 0?F:n===void 0&&e.runtime._tag===`Stateful`?Dp(`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=>nce(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(z(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},K8=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,Wve=/*#__PURE__*/ B(function*(e){if(e.length===0)return yield*new Nd(`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 Nd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(K8(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(K8(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(K8(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${K8(e)}${t.tag}`}),handlerTarget:(e,t)=>({context:t,install:B(function*(t,n,i){let a=yield*n.toHandlers(i);for(let i of n.requests.values()){let n=r.requests.get(`${K8(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*Dp(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),q8=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),Gve=()=>{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=q8(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=q8(n);return t.set(e,r),r},resolve:r,resolveSessionId:t=>e.get(t),terminateSession:t=>e.delete(t),setLogLevel:(e,t,n)=>P(()=>{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?L(new U8({code:c8,message:`Resource subscriptions are not supported`})):P(()=>i.add(e)).pipe(Ip)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?L(new U8({code:c8,message:`Resource subscriptions are not supported`})):P(()=>i.delete(e)).pipe(Ip)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?R8[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`?R8[n.level].order>=R8[e.level].order:vD(R8[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)}}},J8=`mcp-session-id`,Y8=`mcp-protocol-version`,X8=`io.modelcontextprotocol/protocolVersion`,Z8=`io.modelcontextprotocol/clientCapabilities`,Q8=-32022,$8=e=>typeof e==`object`&&e?e:void 0,e5=e=>{let t=$8(e);return t!==void 0&&X8 in t?{present:!0,value:t[X8]}:{present:!1,value:void 0}},Kve=e=>e5($8($8(e)?.params)?._meta).present,qve=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},t5=e=>({_tag:`Rejected`,status:400,error:{code:d8,message:e}}),n5=/*#__PURE__*/ wP(fve);var r5=class extends (/*#__PURE__*/ j()(`effect/ai/McpRuntime/ServerRuntime`)){};const i5=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),Jve=/*#__PURE__*/ B(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:Gve(),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 Nd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*Wve(e),o=/* @__PURE__ */ new Set,s=e=>({code:Q8,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[Y8],a=e[J8],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 t5(`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[Y8],a=$8(n),o=$8($8(a?.params)?._meta),l=e5(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 t5(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:l8,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return t5(`MCP-Protocol-Version header does not match request metadata`);if(!f&&$8(o?.[Z8])===void 0)return{_tag:`Rejected`,status:400,error:{code:l8,message:`${Z8} 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 t5(`Mcp-Method header does not match request method`);let n=qve(t);if(n!==void 0){let t=$8(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||z8(r)!==t)return t5(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return r5.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:B(function*(e,n,o){let c=$8(o.payload)?._meta,l=e5(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=i5(a.protocols,e);if(t===void 0)return yield*new U8({code:Q8,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?i5(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*Dp(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new U8(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=M8.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?tM({status:e}):sM({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(Ea(r)){let t=e[Y8];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 f8({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new p8({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(Kve)||a.some(e=>A(e,`method`)&&e.method===`initialize`)||t.binding?.protocol.runtime.transport.jsonRpc.acceptsBatches!==!0?i(400):{_tag:`Accepted`,acknowledge:!a.some(e=>A(e,`method`)&&A(e,`id`)),isSubscription:!1}}let o=A(a,`id`),c=o&&(typeof a.id==`string`||typeof a.id==`number`)?a.id:null,u=A(a,`jsonrpc`)&&a.jsonrpc===`2.0`,d=!o||typeof a.id==`string`||typeof a.id==`number`,f=u&&d&&A(a,`method`)&&typeof a.method==`string`,p=o&&(typeof a.id==`string`||typeof a.id==`number`||a.id===null),m=A(a,`result`),h=A(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 p8({message:`Invalid Request`}),c);let v=A(a,`method`)&&a.method===`initialize`,y=e[J8]!==void 0;return v&&y?i(400,new p8({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 p8({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 m8({message:`Method not found: ${a.method}`}),c):{_tag:`Accepted`,acknowledge:!f||!o,isSubscription:A(a,`method`)&&a.method===`subscriptions/listen`}},effectLogLevel:(e,n,r)=>t?.effectLogLevel(e,n,r)??r,disconnect:e=>t?.disconnect(e),terminateHttpSession:e=>Sp(()=>{let n=e[J8];if(n===void 0)return N(tM({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return N(tM({status:r.status}));let i=r.binding;return t.terminateSession(n),Fp(_p(o,e=>e(i),{discard:!0}),tM({status:204}))}),onSessionTerminated:e=>pm(P(()=>{o.add(e)}),()=>P(()=>{o.delete(e)})),deliveryClientIds:()=>t?.initializedClientIds()??[],canDeliver:(e,n,r,i)=>t?.canDeliver(e,n,r,i)??!0,installHandlers:B(function*(e){let r=/* @__PURE__ */ new Map,i={subscribeServerNotifications:e.subscribeServerNotifications,...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*Dp(`MCP sessionful runtime invariant failed`);yield*o.install(n,n5,n5.of({ping:()=>N({})}));let r={initialize:B(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*kp(s=>{let c=ca(s.context,DN),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:mve.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),FN(c,(t,r)=>N(pM(r,{[J8]:e,[Y8]:n.protocolVersion})))}else t.registerConnection(a,u);return N({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:o8.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:B(function*(e,n){e._tag===`Initialized`&&t.markInitialized(n)})};yield*n.installHandlers(e.core,r,o)}return Qi(r)})})}),Yve=e=>Hf(r5)(Jve(e)),a5=e=>vS(e).pipe(US(bS(yS(e)),{decode:vv(),encode:xv(Bi(Ii))})),o5=K,Xve=/*#__PURE__*/ G([H,iC]),s5=/*#__PURE__*/ BS([`user`,`assistant`]),Zve=/*#__PURE__*/ BS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),c5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(/*#__PURE__*/ FS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ a5(Xve)}),[K]))}),l5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(o5)}),u5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(o5)});({...c5.fields});const d5=/*#__PURE__*/ U({...u5.fields,nextCursor:/*#__PURE__*/ a5(H)}),Qve=/*#__PURE__*/ U({extensions:/*#__PURE__*/ a5(/*#__PURE__*/ PS(/*#__PURE__*/ CS([H,`/`,H]),QC)),experimental:/*#__PURE__*/ a5(/*#__PURE__*/ PS(H,o5)),roots:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(kS)})),sampling:/*#__PURE__*/ a5(o5)}),$ve=/*#__PURE__*/ U({extensions:/*#__PURE__*/ a5(/*#__PURE__*/ PS(/*#__PURE__*/ CS([H,`/`,H]),QC)),experimental:/*#__PURE__*/ a5(/*#__PURE__*/ PS(H,o5)),logging:/*#__PURE__*/ a5(o5),prompts:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(kS)})),resources:/*#__PURE__*/ a5(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ a5(kS),listChanged:/*#__PURE__*/ a5(kS)})),tools:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(kS)}))}),f5=/*#__PURE__*/ U({code:dC,message:H,data:/*#__PURE__*/ a5(TS)}),p5=/*#__PURE__*/ U({audience:/*#__PURE__*/ a5(/*#__PURE__*/ W(s5)),priority:/*#__PURE__*/ a5(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1})))}),eye=/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ a5(H),text:H}),tye=/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ a5(H),blob:H}),nye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`text`),text:H,annotations:/*#__PURE__*/ a5(p5)}),rye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`image`),data:H,mimeType:H,annotations:/*#__PURE__*/ a5(p5)}),iye=/*#__PURE__*/ U({uri:H,name:H,description:/*#__PURE__*/ a5(H),mimeType:/*#__PURE__*/ a5(H),size:/*#__PURE__*/ a5(iC),annotations:/*#__PURE__*/ a5(p5)}),aye=/*#__PURE__*/ U({uriTemplate:H,name:H,description:/*#__PURE__*/ a5(H),mimeType:/*#__PURE__*/ a5(H),annotations:/*#__PURE__*/ a5(p5)}),m5=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),required:/*#__PURE__*/ a5(kS)}),oye=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),arguments:/*#__PURE__*/ a5(/*#__PURE__*/ W(m5))}),sye=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),inputSchema:/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`object`),properties:/*#__PURE__*/ a5(/*#__PURE__*/ PS(H,o5)),required:/*#__PURE__*/ a5(/*#__PURE__*/ W(H))})}),h5=/*#__PURE__*/ U({hints:/*#__PURE__*/ a5(/*#__PURE__*/ W(/* @__PURE__ */ U({name:/*#__PURE__*/ a5(H)}))),costPriority:/*#__PURE__*/ a5(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ a5(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ a5(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1})))}),cye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`ref/prompt`),name:H}),lye=/*#__PURE__*/ U({uri:H,name:/*#__PURE__*/ a5(H)});({...u5.fields}),{...d5.fields},{...d5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...u5.fields},{...u5.fields},{...u5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...l5.fields},{...l5.fields},{...l5.fields},{...l5.fields};const g5=a5,uye=/*#__PURE__*/ U({...$ve.fields,completions:/*#__PURE__*/ g5(/*#__PURE__*/ U({}))}),dye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`audio`),data:H,mimeType:H,annotations:/*#__PURE__*/ g5(p5)}),_5=/*#__PURE__*/ U({title:/*#__PURE__*/ g5(H),readOnlyHint:/*#__PURE__*/ g5(kS),destructiveHint:/*#__PURE__*/ g5(kS),idempotentHint:/*#__PURE__*/ g5(kS),openWorldHint:/*#__PURE__*/ g5(kS)});({...sye.fields}),{...u5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...u5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...l5.fields};const v5=a5,y5=K,b5=/*#__PURE__*/ v5(y5),x5=/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ v5(H),version:H}),S5=/*#__PURE__*/ U({...Qve.fields,elicitation:/*#__PURE__*/ v5(/*#__PURE__*/ U({}))}),C5=/*#__PURE__*/ U({audience:/*#__PURE__*/ v5(/*#__PURE__*/ W(s5)),priority:/*#__PURE__*/ v5(/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1})))}),w5=/*#__PURE__*/ U({...iye.fields,title:/*#__PURE__*/ v5(H),annotations:/*#__PURE__*/ v5(C5),_meta:b5}),fye=/*#__PURE__*/ U({...aye.fields,title:/*#__PURE__*/ v5(H),annotations:/*#__PURE__*/ v5(C5),_meta:b5}),T5=/*#__PURE__*/ G([/* @__PURE__ */ U({...eye.fields,_meta:b5}),/* @__PURE__ */ U({...tye.fields,_meta:b5})]),pye=/*#__PURE__*/ U({...m5.fields,title:/*#__PURE__*/ v5(H)}),mye=/*#__PURE__*/ U({...oye.fields,title:/*#__PURE__*/ v5(H),arguments:/*#__PURE__*/ v5(/*#__PURE__*/ W(pye)),_meta:b5}),E5=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`resource`),resource:T5,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),hye=/*#__PURE__*/ U({...w5.fields,type:/*#__PURE__*/ SS(`resource_link`)}),D5=/*#__PURE__*/ U({...nye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),O5=/*#__PURE__*/ U({...rye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),k5=/*#__PURE__*/ U({...dye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),A5=/*#__PURE__*/ G([D5,O5,k5,E5,hye]),j5=/*#__PURE__*/ G([D5,O5,k5]),gye=/*#__PURE__*/ U({role:s5,content:A5}),_ye=/*#__PURE__*/ U({role:s5,content:j5}),vye=/*#__PURE__*/ U({...uye.fields}),M5=/*#__PURE__*/ U({...u5.fields,protocolVersion:H,capabilities:vye,serverInfo:x5,instructions:/*#__PURE__*/ v5(H)});var yye=class extends (/*#__PURE__*/ sP(`initialize`,{success:M5,error:f5,payload:{...c5.fields,protocolVersion:H,capabilities:S5,clientInfo:x5}})){};const N5=/*#__PURE__*/ FS(/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`object`),properties:/*#__PURE__*/ v5(/*#__PURE__*/ PS(H,y5)),required:/*#__PURE__*/ v5(/*#__PURE__*/ W(H))}),[K]),bye=/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ v5(H),description:/*#__PURE__*/ v5(H),inputSchema:N5,outputSchema:/*#__PURE__*/ v5(N5),annotations:/*#__PURE__*/ v5(_5),_meta:b5}),P5=/*#__PURE__*/ U({...u5.fields,content:/*#__PURE__*/ W(A5),structuredContent:/*#__PURE__*/ v5(y5),isError:/*#__PURE__*/ v5(kS)}),xye=/*#__PURE__*/ U({...u5.fields,role:s5,content:j5,model:H,stopReason:/*#__PURE__*/ v5(H)});var Sye=class extends (/*#__PURE__*/ sP(`sampling/createMessage`,{success:xye,error:f5,payload:{...c5.fields,messages:/*#__PURE__*/ W(_ye),modelPreferences:/*#__PURE__*/ v5(h5),systemPrompt:/*#__PURE__*/ v5(H),includeContext:/*#__PURE__*/ v5(/*#__PURE__*/ BS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ v5(iC),maxTokens:iC,stopSequences:/*#__PURE__*/ v5(/*#__PURE__*/ W(H)),metadata:/*#__PURE__*/ v5(y5)}})){};const Cye=/*#__PURE__*/ U({...cye.fields,title:/*#__PURE__*/ v5(H)}),wye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`ref/resource`),uri:H});({...c5.fields}),{...d5.fields},{...d5.fields},{...u5.fields},{...d5.fields};const Tye=/*#__PURE__*/ U({...u5.fields,description:/*#__PURE__*/ v5(H),messages:/*#__PURE__*/ W(gye)});({...d5.fields}),{...c5.fields},{...c5.fields};var Eye=class extends (/*#__PURE__*/ sP(`tools/call`,{success:P5,error:f5,payload:{...c5.fields,name:H,arguments:/*#__PURE__*/ v5(y5)}})){};({...u5.fields}),{...c5.fields};const Q=a5,F5=K,I5=/*#__PURE__*/ Q(F5),L5=/*#__PURE__*/ U({src:H,mimeType:/*#__PURE__*/ Q(H),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ W(H)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ BS([`light`,`dark`]))}),Dye=/*#__PURE__*/ U({...x5.fields,description:/*#__PURE__*/ Q(H),websiteUrl:/*#__PURE__*/ Q(H),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))});({...S5.fields});const R5=/*#__PURE__*/ U({...C5.fields,lastModified:/*#__PURE__*/ Q(H)}),z5=/*#__PURE__*/ U({...w5.fields,annotations:/*#__PURE__*/ Q(R5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),Oye=/*#__PURE__*/ U({...fye.fields,annotations:/*#__PURE__*/ Q(R5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),kye=/*#__PURE__*/ U({...mye.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),B5=/*#__PURE__*/ U({...D5.fields,annotations:/*#__PURE__*/ Q(R5)}),V5=/*#__PURE__*/ U({...O5.fields,annotations:/*#__PURE__*/ Q(R5)}),H5=/*#__PURE__*/ U({...k5.fields,annotations:/*#__PURE__*/ Q(R5)}),U5=/*#__PURE__*/ U({...E5.fields,annotations:/*#__PURE__*/ Q(R5)}),Aye=/*#__PURE__*/ G([B5,V5,H5,/* @__PURE__ */ U({...z5.fields,type:/*#__PURE__*/ SS(`resource_link`)}),U5]),jye=/*#__PURE__*/ U({...bye.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))});({...P5.fields}),Eye.payloadSchema;const W5=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`tool_use`),id:H,name:H,input:F5,_meta:I5}),G5=/*#__PURE__*/ G([B5,V5,H5,W5,/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`tool_result`),toolUseId:H,content:/*#__PURE__*/ W(Aye),structuredContent:/*#__PURE__*/ Q(F5),isError:/*#__PURE__*/ Q(kS),_meta:I5})]),Mye=/*#__PURE__*/ U({role:s5,content:/*#__PURE__*/ G([G5,/*#__PURE__*/ W(G5)]),_meta:I5}),Nye=/*#__PURE__*/ U({mode:/*#__PURE__*/ Q(/*#__PURE__*/ BS([`auto`,`required`,`none`]))});({...u5.fields,...Mye.fields}),{...Sye.payloadSchema.fields};const Pye=/*#__PURE__*/ U({...lye.fields,_meta:I5});({...u5.fields});const Fye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minLength:/*#__PURE__*/ Q(dC),maxLength:/*#__PURE__*/ Q(dC),format:/*#__PURE__*/ Q(/*#__PURE__*/ BS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(H)}),Iye=/*#__PURE__*/ U({type:/*#__PURE__*/ BS([`number`,`integer`]),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minimum:/*#__PURE__*/ Q(iC),maximum:/*#__PURE__*/ Q(iC),default:/*#__PURE__*/ Q(iC)}),Lye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`boolean`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),default:/*#__PURE__*/ Q(kS)}),K5=/*#__PURE__*/ U({const:H,title:H}),Rye=/*#__PURE__*/ G([/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),enum:/*#__PURE__*/ W(H),default:/*#__PURE__*/ Q(H)}),/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),oneOf:/*#__PURE__*/ W(K5),default:/*#__PURE__*/ Q(H)})]),zye=/*#__PURE__*/ G([/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`array`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minItems:/*#__PURE__*/ Q(dC),maxItems:/*#__PURE__*/ Q(dC),items:/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`string`),enum:/*#__PURE__*/ W(H)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ W(H))}),/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`array`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minItems:/*#__PURE__*/ Q(dC),maxItems:/*#__PURE__*/ Q(dC),items:/*#__PURE__*/ U({anyOf:/*#__PURE__*/ W(K5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ W(H))})]),Bye=/*#__PURE__*/ U({type:/*#__PURE__*/ SS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),enum:/*#__PURE__*/ W(H),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ W(H)),default:/*#__PURE__*/ Q(H)});({...c5.fields}),{...c5.fields},{...u5.fields},{...M5.fields},{...yye.payloadSchema.fields},{...d5.fields},{...d5.fields},{...d5.fields},{...Tye.fields},{...d5.fields},{...c5.fields};const q5=`2026-07-28`,$=a5,J5=/*#__PURE__*/ $(K),Y5=/*#__PURE__*/ G([H,dC]),X5=Y5,Z5=s5,Q5=Zve,$5=Dye,Vye=/*#__PURE__*/ FS(/*#__PURE__*/ U({experimental:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,K)),roots:/*#__PURE__*/ $(/*#__PURE__*/ U({})),sampling:/*#__PURE__*/ $(/*#__PURE__*/ U({context:/*#__PURE__*/ $(K),tools:/*#__PURE__*/ $(K)})),elicitation:/*#__PURE__*/ $(/*#__PURE__*/ U({form:/*#__PURE__*/ $(K),url:/*#__PURE__*/ $(K)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,K))}),[K]),Hye=/*#__PURE__*/ FS(/*#__PURE__*/ U({experimental:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,K)),logging:/*#__PURE__*/ $(K),completions:/*#__PURE__*/ $(K),prompts:/*#__PURE__*/ $(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ $(kS)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ $(kS),listChanged:/*#__PURE__*/ $(kS)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ $(kS)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,K))}),[K]),e7=/*#__PURE__*/ FS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ $(X5),"io.modelcontextprotocol/protocolVersion":H,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $($5),"io.modelcontextprotocol/clientCapabilities":Vye,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(Q5)}),[K]),t7=/*#__PURE__*/ U({_meta:e7}),n7=/*#__PURE__*/ U({_meta:/*#__PURE__*/ $(/* @__PURE__ */ FS(/*#__PURE__*/ U({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $(Y5)}),[K]))}),r7=/*#__PURE__*/ FS(/*#__PURE__*/ U({"io.modelcontextprotocol/serverInfo":$5}),[K]),i7={_meta:r7,resultType:/*#__PURE__*/ SS(`complete`)},a7=/*#__PURE__*/ U({code:dC,message:H,data:/*#__PURE__*/ $(QC)}),Uye=R5,o7=/*#__PURE__*/ U({...z5.fields,size:/*#__PURE__*/ $(dC),annotations:/*#__PURE__*/ $(Uye)}),s7=Oye,Wye=T5,c7=B5,l7=V5,u7=H5,d7=/*#__PURE__*/ G([c7,l7,u7,/* @__PURE__ */ U({...o7.fields,type:/*#__PURE__*/ SS(`resource_link`)}),U5]),f7=kye,Gye=/*#__PURE__*/ U({role:Z5,content:d7}),Kye=/*#__PURE__*/ FS(/*#__PURE__*/ U({$schema:/*#__PURE__*/ $(H),type:/*#__PURE__*/ SS(`object`)}),[K]),qye=/*#__PURE__*/ FS(/*#__PURE__*/ U({$schema:/*#__PURE__*/ $(H)}),[K]),Jye=_5,p7=/*#__PURE__*/ U({...jye.fields,inputSchema:Kye,outputSchema:/*#__PURE__*/ $(qye),annotations:/*#__PURE__*/ $(Jye)}),m7=/*#__PURE__*/ G([c7,l7,u7,W5,/* @__PURE__ */ U({type:/*#__PURE__*/ SS(`tool_result`),toolUseId:H,content:/*#__PURE__*/ W(d7),structuredContent:/*#__PURE__*/ $(QC),isError:/*#__PURE__*/ $(kS),_meta:J5})]),h7=/*#__PURE__*/ U({role:Z5,content:/*#__PURE__*/ G([m7,/*#__PURE__*/ W(m7)]),_meta:J5}),Yye=/*#__PURE__*/ FS(/*#__PURE__*/ U({name:/*#__PURE__*/ $(H)}),[K]),g7=/*#__PURE__*/ iC.check(/*#__PURE__*/ lC({minimum:0,maximum:1})),Xye=/*#__PURE__*/ U({...h5.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ W(Yye)),costPriority:/*#__PURE__*/ $(g7),speedPriority:/*#__PURE__*/ $(g7),intelligencePriority:/*#__PURE__*/ $(g7)}),Zye=/*#__PURE__*/ U({method:/*#__PURE__*/ SS(`sampling/createMessage`),params:/*#__PURE__*/ U({messages:/*#__PURE__*/ W(h7),modelPreferences:/*#__PURE__*/ $(Xye),systemPrompt:/*#__PURE__*/ $(H),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ BS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(iC),maxTokens:dC,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ W(H)),metadata:/*#__PURE__*/ $(K),tools:/*#__PURE__*/ $(/*#__PURE__*/ W(p7)),toolChoice:/*#__PURE__*/ $(Nye)})}),Qye=/*#__PURE__*/ U({...h7.fields,model:H,stopReason:/*#__PURE__*/ $(H)}),$ye=Pye,ebe=/*#__PURE__*/ U({method:/*#__PURE__*/ SS(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ U({_meta:J5}))}),tbe=/*#__PURE__*/ U({roots:/*#__PURE__*/ W($ye)}),nbe=/*#__PURE__*/ U({method:/*#__PURE__*/ SS(`elicitation/create`),params:/* @__PURE__ */ G([/* @__PURE__ */ U({mode:/*#__PURE__*/ $(/*#__PURE__*/ SS(`form`)),message:H,requestedSchema:/* @__PURE__ */ U({$schema:/*#__PURE__*/ $(H),type:/*#__PURE__*/ SS(`object`),properties:/*#__PURE__*/ PS(H,/* @__PURE__ */ G([/* @__PURE__ */ G([Bye,Rye,zye]),Fye,Iye,Lye])),required:/*#__PURE__*/ $(/*#__PURE__*/ W(H))})}),/* @__PURE__ */ U({mode:/*#__PURE__*/ SS(`url`),message:H,url:H})])}),rbe=/*#__PURE__*/ U({action:/*#__PURE__*/ BS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,/*#__PURE__*/ G([H,iC,kS,/*#__PURE__*/ W(H)])))}),ibe=/*#__PURE__*/ G([Zye,ebe,nbe]),abe=/*#__PURE__*/ G([Qye,tbe,rbe]),_7=/*#__PURE__*/ PS(H,ibe),obe=/*#__PURE__*/ PS(H,abe),v7={_meta:r7,resultType:/*#__PURE__*/ SS(`input_required`)},y7=/*#__PURE__*/ G([/*#__PURE__*/ FS(/*#__PURE__*/ U({...v7,inputRequests:_7,requestState:/*#__PURE__*/ $(H)}),[K]),/*#__PURE__*/ FS(/*#__PURE__*/ U({...v7,inputRequests:/*#__PURE__*/ $(_7),requestState:H}),[K])]),b7={...t7.fields,inputResponses:/*#__PURE__*/ $(obe),requestState:/*#__PURE__*/ $(H)},x7={...i7,ttlMs:/*#__PURE__*/ dC.check(/*#__PURE__*/ cC(0)),cacheScope:/*#__PURE__*/ BS([`public`,`private`])},S7={...t7.fields,cursor:/*#__PURE__*/ $(H)},C7={...i7,nextCursor:/*#__PURE__*/ $(H)},w7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...x7,supportedVersions:/*#__PURE__*/ W(H),capabilities:Hye,instructions:/*#__PURE__*/ $(H)}),[K]);var sbe=class extends (/*#__PURE__*/ sP(`server/discover`,{success:w7,error:a7,payload:t7})){};const T7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...C7,...x7,resources:/*#__PURE__*/ W(o7)}),[K]);var cbe=class extends (/*#__PURE__*/ sP(`resources/list`,{success:T7,error:a7,payload:S7})){};const E7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...C7,...x7,resourceTemplates:/*#__PURE__*/ W(s7)}),[K]);var lbe=class extends (/*#__PURE__*/ sP(`resources/templates/list`,{success:E7,error:a7,payload:S7})){};const D7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...x7,contents:/*#__PURE__*/ W(Wye)}),[K]);var ube=class extends (/*#__PURE__*/ sP(`resources/read`,{success:/*#__PURE__*/ G([D7,y7]),error:a7,payload:{...b7,uri:H}})){};const O7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...C7,...x7,prompts:/*#__PURE__*/ W(f7)}),[K]);var dbe=class extends (/*#__PURE__*/ sP(`prompts/list`,{success:O7,error:a7,payload:S7})){};const k7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...i7,description:/*#__PURE__*/ $(H),messages:/*#__PURE__*/ W(Gye)}),[K]);var fbe=class extends (/*#__PURE__*/ sP(`prompts/get`,{success:/*#__PURE__*/ G([k7,y7]),error:a7,payload:{...b7,name:H,arguments:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,H))}})){};const A7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...C7,...x7,tools:/*#__PURE__*/ W(p7)}),[K]);var pbe=class extends (/*#__PURE__*/ sP(`tools/list`,{success:A7,error:a7,payload:S7})){};const j7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...i7,content:/*#__PURE__*/ W(d7),structuredContent:/*#__PURE__*/ $(QC),isError:/*#__PURE__*/ $(kS)}),[K]);var mbe=class extends (/*#__PURE__*/ sP(`tools/call`,{success:/*#__PURE__*/ G([j7,y7]),error:a7,payload:{...b7,name:H,arguments:/*#__PURE__*/ $(K)}})){};const hbe=Cye,gbe=wye,M7=/*#__PURE__*/ FS(/*#__PURE__*/ U({...i7,completion:/*#__PURE__*/ U({values:/*#__PURE__*/ W(H).check(/*#__PURE__*/ hC(100)),total:/*#__PURE__*/ $(dC),hasMore:/*#__PURE__*/ $(kS)})}),[K]);var _be=class extends (/*#__PURE__*/ sP(`completion/complete`,{success:M7,error:a7,payload:{...t7.fields,ref:/*#__PURE__*/ G([hbe,gbe]),argument:/*#__PURE__*/ U({name:H,value:H}),context:/*#__PURE__*/ $(/*#__PURE__*/ U({arguments:/*#__PURE__*/ $(/*#__PURE__*/ PS(H,H))}))}})){};const N7=/*#__PURE__*/ U({toolsListChanged:/*#__PURE__*/ $(kS),promptsListChanged:/*#__PURE__*/ $(kS),resourcesListChanged:/*#__PURE__*/ $(kS),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ W(H))}),P7=/*#__PURE__*/ FS(/*#__PURE__*/ U({_meta:/* @__PURE__ */ FS(/*#__PURE__*/ U({"io.modelcontextprotocol/serverInfo":$5,"io.modelcontextprotocol/subscriptionId":Y5}),[K]),resultType:/*#__PURE__*/ SS(`complete`)}),[K]);var vbe=class extends (/*#__PURE__*/ sP(`subscriptions/listen`,{success:P7,error:a7,payload:{...t7.fields,notifications:N7}})){},F7=class extends (/*#__PURE__*/ sP(`notifications/cancelled`,{payload:{...n7.fields,requestId:Y5,reason:/*#__PURE__*/ $(H)}})){},ybe=class extends (/*#__PURE__*/ sP(`notifications/progress`,{payload:{...n7.fields,progressToken:X5,progress:iC,total:/*#__PURE__*/ $(iC),message:/*#__PURE__*/ $(H)}})){},bbe=class extends (/*#__PURE__*/ sP(`notifications/message`,{payload:{...n7.fields,level:Q5,logger:/*#__PURE__*/ $(H),data:QC}})){},I7=class extends (/*#__PURE__*/ sP(`notifications/resources/updated`,{payload:{...n7.fields,uri:H}})){},L7=class extends (/*#__PURE__*/ sP(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ HS(n7)})){},R7=class extends (/*#__PURE__*/ sP(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ HS(n7)})){},z7=class extends (/*#__PURE__*/ sP(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ HS(n7)})){},B7=class extends (/*#__PURE__*/ sP(`notifications/subscriptions/acknowledged`,{payload:{...n7.fields,notifications:N7}})){},V7=class extends (/*#__PURE__*/ wP(sbe,_be,fbe,dbe,cbe,lbe,ube,vbe,mbe,pbe)){},H7=class extends (/*#__PURE__*/ wP(F7)){},xbe=class extends (/*#__PURE__*/ V7.merge(H7)){},Sbe=class extends (/*#__PURE__*/ wP()){},Cbe=class extends (/*#__PURE__*/ wP(F7,ybe,bbe,I7,L7,R7,z7,B7)){};const wbe=/*#__PURE__*/ PS(H,K),Tbe=/*#__PURE__*/ lS(e7),Ebe=/*#__PURE__*/ lS(F7.payloadSchema),Dbe=/*#__PURE__*/ cS(QC),U7=/*#__PURE__*/ pS($5),W7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},Obe=(e,t)=>{if(Gt(t))return e===void 0;if(e===void 0)return!1;let n=z8(e);return n!==void 0&&TO(t).pipe(EO(AO,e=>n===e),EO(MO,e=>n===String(e)),EO(jO,e=>Number.isSafeInteger(e)&&n.trim().length>0&&Number(n)===e),NO(()=>!1))},kbe=/*#__PURE__*/ B(function*(e){let t=yield*Tbe(e);return{protocolVersion:q5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),G7=(e,t)=>{let n=e._meta;return{...Yt(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},K7=(e,t)=>W7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),q7=/*#__PURE__*/ lS(/*#__PURE__*/ G([j7,y7])),J7=/*#__PURE__*/ B(function*(e,t){let n=yield*U7(t);return e._tag===`Complete`?yield*q7({...W7(e.value),_meta:G7(e.value,n),resultType:`complete`}):yield*q7(K7(e,n))}),Abe=(e,t)=>{let n={};for(let r of Object.values(e??{}))TO(r).pipe(EO({method:`roots/list`},()=>{t.roots===void 0&&(n.roots={})}),EO({method:`sampling/createMessage`},e=>{let r=n.sampling??{};Bve(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)}),EO({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]={})}),PO);return n},Y7=e=>W7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:Jh(e.blob)}}),X7=/*#__PURE__*/ wO().pipe(/*#__PURE__*/ EO({type:/*#__PURE__*/ kO(`text`,`resource_link`)},e=>e),/*#__PURE__*/ EO({type:/*#__PURE__*/ kO(`image`,`audio`)},e=>W7({type:e.type,mimeType:e.mimeType,data:Jh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ EO({type:`resource`},e=>W7({type:`resource`,resource:Y7(e.resource),annotations:e.annotations,_meta:e._meta})),PO),jbe=e=>o7.make(e),Mbe=e=>s7.make(e),Nbe=e=>W8(yve,f7,e),Pbe=e=>W8(D8,p7,e),Z7={ttlMs:0,cacheScope:`private`},Q7=/*#__PURE__*/ B(function*(e,t){let n=yield*U7(t);return{...W7(e),_meta:G7(e,n),resultType:`complete`}}),Fbe=/*#__PURE__*/ wO().pipe(/*#__PURE__*/ DO(`ResourceNotFound`,e=>new U8({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ DO(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,U8.fromTool),/*#__PURE__*/ NO(U8.fromFeature)),$7=e=>{let t=Fbe(e);return a7.make({code:t.code,message:t.message,...Dbe(t.data)?{data:t.data}:{}})},e9=/*#__PURE__*/ B(function*(e,t){let n=yield*sm(DN);return Mi(n)&&FN(n.value,(t,n)=>N(_M(n,e))),yield*t}),Ibe=e=>Ebe(e).pipe(z(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),t9=e=>new kve({operation:e,protocolVersion:q5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),Lbe=/* @__PURE__ */ Uve({protocolVersion:q5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:kbe},clientRpcs:xbe,clientNotificationRpcs:H7,serverRequestRpcs:Sbe,serverNotificationRpcs:Cbe,handlerRpcs:/* @__PURE__ */ V7.merge(H7),makeHandlers:(e,t,n)=>{let r=lS(wbe),i=lS(w7),a=lS(T7),o=lS(E7),s=lS(D7),c=lS(O7),l=lS(k7),u=lS(G([k7,y7])),d=lS(M7),f=lS(A7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:Ra(n.serverInfo.extensions,e=>Yt(e)),g=z(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}}),_=M8.useSync(V8),v=B(function*(e){let t=yield*M8,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(Up);return V8(M8.of({...t,inputResponses:n,requestState:e.requestState}))}),y=B(function*(e,t){let n=Abe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*e9(400,new U8({code:-32021,message:`The request requires client capabilities that were not declared`,data:{requiredCapabilities:n}}))});return{"subscriptions/listen":B(function*(e,{client:t,requestId:r}){if(p===void 0)return yield*new U8({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*bf(yield*um),o=yield*_f(n.subscribeServerNotifications,a),s={...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}:{}},c={"io.modelcontextprotocol/subscriptionId":r},l=new Set(s.resourceSubscriptions),u=yield*tT(64),d=yield*tf();yield*I(function*(){for(;;){let e=yield*Pw(o);if(e.targetClientId!==void 0&&e.targetClientId!==t.id)continue;let n=e.notification,r=TO(n).pipe(OO({ToolsChanged:()=>s.toolsListChanged===!0?R7:void 0,PromptsChanged:()=>s.promptsListChanged===!0?z7:void 0,ResourcesChanged:()=>s.resourcesListChanged===!0?L7:void 0,ResourceUpdated:e=>l.has(e.uri)?I7:void 0}),PO);if(r===void 0)continue;let i={tag:r._tag,payload:r.payloadSchema.make({_meta:{...n.metadata,...c},...n._tag===`ResourceUpdated`?{uri:n.uri}:{}})};if(!(yield*nT(u,i)))break}}).pipe(wf(a),jp(Sp(()=>n.markSubscriptionCancelled?.(t.id,r)??F)),jp(lf(d,void 0)),Pm),yield*p(q5,t.id,{tag:B7._tag,payload:B7.payloadSchema.make({_meta:c,notifications:s})});let f=Em(hT(u).pipe(R(e=>p(q5,t.id,e))));yield*pre(f,nf(d)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??F;let m=yield*U7(n.serverInfo);return P7.make({_meta:{...c,"io.modelcontextprotocol/serverInfo":m},resultType:`complete`})},Hp($7)),"server/discover":B(function*(e){let t=yield*g,r=yield*Q7({...Z7,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},Hp($7)),"resources/list":B(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*Q7({...Z7,resources:i.map(jbe)},n.serverInfo);return yield*a(o)},Hp($7)),"resources/templates/list":B(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*Q7({...Z7,resourceTemplates:i.map(Mbe)},n.serverInfo);return yield*o(a)},Hp($7)),"resources/read":B(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map(Y7),o=yield*Q7({...Z7,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},Hp($7)),"prompts/list":B(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*e9(404,new U8({code:c8,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*_p(i,Nbe),o=yield*Q7({...Z7,prompts:a},n.serverInfo);return yield*c(o)},Hp($7)),"prompts/get":B(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*U7(n.serverInfo);return yield*u(K7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:X7(e.content)})),s=yield*Q7({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},Hp($7)),"completion/complete":B(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*Q7({completion:W7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},Hp($7)),"tools/list":B(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*_p(i,Pbe),o=yield*Q7({...Z7,tools:a},n.serverInfo);return yield*f(o)},Hp($7)),"tools/call":B(function*(t){let r=yield*v(t),i=(yield*e.tools.list(r.protocol)).find(e=>e.name===t.name),a=yield*sm(DN);if(i!==void 0&&Mi(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!Yt(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!Obe(a.value.headers[e],n))return yield*e9(400,new U8({code:d8,message:`${e} does not match argument '${r}'`}))}if(Yt(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:Yt(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(Rp([`ToolExecutionError`,`InvalidToolInput`],e=>N(I8.Complete(O8.make({content:[C8.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*J7(o,n.serverInfo);let s=o.value,c=s.content.map(X7);return yield*J7(I8.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},Hp($7)),"notifications/cancelled":B(function*(e){return yield*F})}},toReverseClient:()=>({listRoots:()=>L(t9(`roots/list`)),createMessage:()=>L(t9(`sampling/createMessage`)),elicit:()=>L(t9(`elicitation/create`))}),projectNotification:e=>G8(e)?N(void 0):Hve({supportsProgressMessage:!0},e),normalizeCancellation:Ibe}),n9=/*#__PURE__*/ new WeakMap,Rbe=/*#__PURE__*/ Ave.omit(`notifications/elicitation/complete`),r9=/*#__PURE__*/ cS(A8),zbe=e=>{switch(e.tag){case`notifications/cancelled`:return L8.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return L8.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 L8.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return L8.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return L8.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return L8.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return L8.PromptsChanged({metadata:e.payload?._meta});default:return}},i9=(e,t)=>{let n=lm(e,M8,t.requestContext),r=t.requestContext.requestMetadata,i=A(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return r9(i)&&(n=lm(n,ff,R8[i].effect)),t.serverClient===void 0?n:lm(n,N8,t.serverClient)};var a9=class e extends (/*#__PURE__*/ j()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ I(function*(){let t=yield*Lve,n=Ka(),r=[],i=[],a=[],o=yield*$w(),s={consumers:0},c=/* @__PURE__ */ new Set,l=(yield*Do).makeDispatcher(),u=yield*vP(Rbe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>tf().pipe(R(t=>kp(n=>{let r=e.message;if(r._tag!==`Request`)return F;let i=zbe(r);if(i===void 0)return F;let a={notification:i,delivered:t,requestContext:ca(n.context,M8),requestHeaders:ca(n.context,DN)?.headers},d=!1;if(r.tag.includes(`list_changed`)){if(!c.has(r.tag)){d=!0;let e=r.tag;l.scheduleTask(()=>{rT(o,a),c.delete(r.tag)},0),c.add(e)}}else d=!0,rT(o,a);let f=Sp(()=>u.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Gd}));return d&&a.requestContext!==void 0&&s.consumers>0?jp(nf(t),f):f})))}),d=e.of({notifications:u.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>tf().pipe(R(n=>nT(o,{notification:L8.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(jp(Sp(()=>s.consumers>0?nf(n):F))))),get tools(){return n},addTool:e=>I(function*(){let r=n.findIndex(({tool:t})=>t.name===e.tool.name);r===-1?n.push(e):n[r]=e;let i=ca(e.annotations,F8);yield*t.tools.register({descriptor:new D8({...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)=>i9(e.handle(t.arguments),n).pipe(cre({InternalError:t=>L(new Fve({name:e.tool.name,message:t.message})),InvalidParams:t=>L(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?Nve:Pve)({name:e.tool.name,message:t.message}))}),z(e=>Zt(e,`InputRequired`)?I8.InputRequired(e):I8.Complete(e)))}),yield*u.client[`notifications/tools/list_changed`]({})}),callTool:e=>I(function*(){let n=yield*N8,r=yield*t.tools.call(e,B8(n)).pipe(Hp(e=>new h8({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new h8({message:`Client input is not supported by this MCP protocol`}):r.value}),get resources(){return r},get resourceTemplates(){return i},addResource:e=>I(function*(){let n=r.findIndex(({resource:t})=>t.uri===e.resource.uri);n===-1?r.push(e):r[n]=e,yield*t.resources.register({descriptor:e.resource,isVisible:t=>{let n=ca(e.annotations,F8);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>i9(e.handle,t)}),yield*u.client[`notifications/resources/list_changed`]({})}),addResourceTemplate:({annotations:e,completions:n,handle:r,routerPath:a,template:o})=>I(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=Jbe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=ca(e,F8);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)=>i9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>i9(r(e.argument.value,e.context),t).pipe(z(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*u.client[`notifications/resources/list_changed`]({})}),findResource:e=>I(function*(){let n=yield*N8;return yield*t.resources.read(e,B8(n)).pipe(Rp(`ResourceNotFound`,e=>L(new h8({message:`Resource '${e.uri}' not found`}))))}),get prompts(){return a},addPrompt:e=>I(function*(){let n=a.findIndex(({prompt:t})=>t.name===e.prompt.name);n===-1?a.push(e):a[n]=e,yield*t.prompts.register({descriptor:e.prompt,isVisible:t=>{let n=ca(e.annotations,F8);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>i9(e.handle(t),n).pipe(z(e=>Zt(e,`InputRequired`)?I8.InputRequired(e):I8.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>i9(r(e.argument.value,e.context),t).pipe(z(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*u.client[`notifications/prompts/list_changed`]({})}),getPromptResult:B(function*({arguments:e,name:n}){let r=yield*N8,i=yield*t.prompts.get(n,e??{},B8(r)).pipe(Rp(`PromptNotFound`,()=>new h8({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new h8({message:`Client input is not supported by this MCP protocol`})}),completion:B(function*(e){let n=yield*N8,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},B8(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return n9.set(d,{core:t,notifications:o,notificationDelivery:s}),d});static layer=/*#__PURE__*/ Hf(e)(e.make)};const o9=`mcp-session-id`,s9=/*#__PURE__*/ new WeakMap,c9=e=>`${typeof e}:${e}`;var l9=class extends Io{};const Bbe=/*#__PURE__*/ B(function*(e,t,n){let r=yield*SP,i=yield*a9,a=yield*ff,o=n===`http`,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=e=>{c.delete(e),s.delete(e),t.disconnect(e)},d=(e,t,n)=>r.send(e,{_tag:`Exit`,requestId:t,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:n}]}}),f=(e,t)=>{let n=l.get(e);if(n===void 0)return;let r=n.filter(e=>e!==t);r.length===0?l.delete(e):l.set(e,r)},p=yield*kw(),m=(e,n,i)=>Sp(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(i.tag);return o===void 0?Dp(`MCP protocol ${e} does not define server notification ${i.tag}`):a.payloadCodecs(o).encode(i.payload).pipe(Up,R(e=>r.send(n,{_tag:`Request`,id:``,tag:i.tag,payload:e,headers:[],isNotification:!0})))}),h=(e,t)=>{let n=c.get(e),r=c9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},g=(e,t,n,i)=>Sp(()=>h(t,n)?o?r.end(t):m(e,t,{tag:`notifications/cancelled`,payload:{requestId:n,reason:i}}):F),_,v=yield*t.installHandlers({core:n9.get(i).core,subscribeServerNotifications:Mw(p),...r.supportsNotifications?{sendNotification:m,markSubscriptionCancelled:(e,t)=>P(()=>{h(e,t)}),terminateSubscription:g}:{},defaultLogLevel:a,serverInfo:e}),y=yield*toe({lookup:B(function*(e){let n=t.selectProtocol(e.profile.protocolVersion),i,a=yield*bP.make(B(function*(t){let n=0;return i=e=>t(n,e),{send(t,i,a){if(n=t,i._tag===`Request`){let t=c9(i.id),n=l.get(t)??[];return n.push(e),l.set(t,n),r.send(e.clientId,{_tag:`Request`,id:i.id,tag:i.tag,payload:i.payload,headers:[]}).pipe(gm(()=>P(()=>f(t,e))))}return i._tag===`Interrupt`&&f(c9(i.requestId),e),r.send(e.clientId,i)},supportsAck:!0,supportsTransferables:!1,supportsStructuredClone:!1,codecFor:r.codecFor}}));return{client:yield*n.makeReverseClient(e.profile).pipe(lm(bP,a)),write:i}}),idleTimeToLive:1e4}),b=P8.of((e,{client:n,headers:r,payload:i,rpc:o})=>{let c=t.resolveRequest(n.id,r);if(!o._tag.endsWith(`/initialize`)&&!c){let e=ow(),t=ca(e.context,DN);return t&&FN(t,()=>N(tM({status:r[o9]===void 0?400:404}))),Dp(/* @__PURE__ */ Error(`Mcp-Session-Id does not exist`))}let l=c?.initializePayload??i,u=s.get(n.id),d=c?.protocol??u?.protocol??t.protocolForInternalTag(o._tag);if(!Ybe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return Dp(`Unsupported selected MCP protocol version: ${d.protocolVersion}`);let f=c?.negotiatedProfile??{protocolVersion:d.protocolVersion,clientCapabilities:l.capabilities,clientInfo:l.clientInfo};u!==void 0&&(u.profile=f);let p=M8.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return lm(lm(lm(e,N8,N8.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:Yt(i)&&Yt(i._meta)?i._meta:void 0,getClient:PE(y,new l9({clientId:n.id,profile:f})).pipe(z(({client:e})=>e))})),M8,p),ff,t.effectLogLevel(n.id,r,a))}),x=SP.of({...r,send:(e,t)=>{if(t._tag===`Exit`){let i=c.get(e),a=c9(t.requestId),o=i?.get(a)?.cancelled;if(i!==void 0&&i.delete(a)&&i.size===0&&c.delete(e),o===!0)return n===`custom`?F:(s9.set(t,t.requestId),r.send(e,t));if(t.exit._tag===`Failure`&&!t.exit.cause.some(e=>e._tag===`Fail`))return r.send(e,{_tag:`Exit`,requestId:t.requestId,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:new g8({message:`Internal error`})}]}})}return r.send(e,t)},run:e=>(_=e,r.run((n,r)=>{let i=ow(),a=r,p=o?ca(i.context,DN):void 0;switch(p!==void 0&&a._tag!==`Eof`&&FN(p,(e,t)=>N(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?tM({headers:Xg(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{let r=o?ua(ow().context,DN).headers:Gg(a.headers),l=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`)?c.get(n)?.get(c9(a.payload.requestId)):void 0,f=l===void 0?t.prepareRequest(n,r,a):N(l.prepared);return I(function*(){let l=yield*f,m=s.get(n);o&&m===void 0&&(yield*yf(ua(i.context,mf),P(()=>u(n))));let g=l.binding,_=l.protocol;if(s.set(n,{protocol:_,profile:l.profile??m?.profile,sessionHeaders:o&&r[o9]!==void 0?Gg({[o9]:r[o9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*d(n,a.id,new p8({message:`JSON-RPC batches are not supported`}));p!==void 0&&g!==void 0&&FN(p,(e,i)=>N(t.resolveRequest(n,r)===void 0?tM({status:404}):dM(i,`mcp-protocol-version`,g.protocol.protocolVersion)));let y=t.routeClientRequest(_,a),b=t.clientRpcs.requests.get(y.tag),x=_.clientNotificationRpcs.requests.has(a.tag);if(b&&x&&a.isNotification){if(!g&&_.runtime._tag===`Stateful`){p&&FN(p,()=>N(tM({status:r[o9]===void 0?400:404})));return}let t=_.payloadCodecs(b).decode(a.payload);return yield*I(function*(){let i=yield*t;if(a.tag===`notifications/cancelled`){let t=yield*_.normalizeCancellation(i),r=c9(t.requestId),a=n;if(o){if(g===void 0)return;let e=Array.from(c).find(([,e])=>e.get(r)?.prepared.binding===g);if(e===void 0)return;a=e[0]}return h(a,t.requestId)?yield*e(a,{_tag:`Interrupt`,requestId:t.requestId}):void 0}let s=v.mapUnsafe.get(b.key),u=s?s.handler(i,{rpc:b,requestId:dP(a.id),client:new aP(n),headers:r}):F;return yield*l.requestContext===void 0?u:lm(u,M8,l.requestContext)}).pipe(qp)}if(!b||x)return a.isNotification?void 0:yield*d(n,a.id,new m8({message:`Method not found: ${a.tag}`}));let S=yield*Np(_.payloadCodecs(b).decode(a.payload));if(Ea(S))return yield*a.isNotification?F:d(n,a.id,new h8({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=c.get(n)??/* @__PURE__ */ new Map;e.set(c9(a.id),{requestId:dP(a.id),prepared:l,cancelled:!1}),c.set(n,e)}let C=e(n,y);return yield*l.requestContext===void 0?C:lm(C,M8,l.requestContext)}).pipe(Lp(e=>a.isNotification?F:d(n,a.id,Zt(e,`ProtocolError`)?U8.fromFeature(e):new h8({message:`Invalid request metadata`}))))}case`Ping`:case`Ack`:case`Interrupt`:return e(n,a);case`Eof`:return o||u(n),e(n,a);case`Pong`:case`Exit`:case`Chunk`:case`ClientProtocolError`:case`Defect`:{let e=a._tag===`Exit`?c9(a.requestId):void 0,r=o?t.resolveRequest(n,ua(ow().context,DN).headers):void 0,i=(e===void 0?void 0:l.get(e))?.find(e=>o?e.profile===r?.negotiatedProfile:e.clientId===n);if(a._tag===`Exit`&&i===void 0)return F;i!==void 0&&e!==void 0&&f(e,i);let c=i?.clientId??n,u=s.get(c),d=u?.protocol??t.protocols[0],p=i?.profile??u?.profile??{protocolVersion:d.protocolVersion,clientCapabilities:{},clientInfo:{name:`unknown`,version:`unknown`}};return PE(y,new l9({clientId:c,profile:p})).pipe(R(({write:e})=>e(a)),dm)}}}))});o&&(yield*t.onSessionTerminated(e=>{let t=[];for(let[n,r]of c)for(let{prepared:i,requestId:a}of r.values())i.binding===e&&h(n,a)&&t.push(_(n,{_tag:`Interrupt`,requestId:a}));return gp(t,{discard:!0})}));let{notificationDelivery:S,notifications:C}=n9.get(i);yield*pm(P(()=>{S.consumers++}),()=>P(()=>{S.consumers--}));let w=/* @__PURE__ */ new Map;return yield*hT(C).pipe(R(B(function*(e){let{delivered:n,notification:r,targetClientId:i,requestContext:c,requestHeaders:l}=e;G8(r)&&(yield*jw(p,{notification:r,targetClientId:i}));let u=yield*x.clientIds;for(let e of s.keys())u.has(e)||(s.delete(e),t.disconnect(e));let d=r._tag===`LoggingMessage`||r._tag===`Progress`,f=d&&c!==void 0?[c.clientId]:i===void 0?o?s.keys():t.deliveryClientIds():[i],m=[],h=!1;for(let e of f){if(i!==void 0&&e!==i)continue;if(!u.has(e)){t.disconnect(e);continue}if(!x.supportsNotifications)continue;let o=d&&c!==void 0?t.selectProtocol(c.protocolVersion):s.get(e)?.protocol;if(!o)continue;let f=w.get(e),p=e===(i??c?.clientId);h||=p;let g=p?n:ef();w.set(e,g);let _=I(function*(){f!==void 0&&(yield*nf(f));let n=yield*o.projectNotification(r);if(n===void 0||r._tag===`Progress`&&o.runtime._tag===`Stateless`&&c?.requestMetadata?.progressToken!==r.progressToken)return;if(r._tag===`LoggingMessage`&&o.runtime._tag===`Stateless`){let t=c?.requestMetadata,n=A(t,`io.modelcontextprotocol/logLevel`)?t[`io.modelcontextprotocol/logLevel`]:void 0;if(c?.clientId!==e||!r9(n)||A8.literals.indexOf(r.level)<A8.literals.indexOf(n))return}else if(!t.canDeliver(e,(c?.clientId===e?l:void 0)??s.get(e)?.sessionHeaders??Wg,r,a))return;let i=o.serverNotificationRpcs.requests.get(n.tag);if(!i)return;let u=yield*o.payloadCodecs(i).encode(n.payload);yield*x.send(e,{_tag:`Request`,id:``,tag:n.tag,payload:u,headers:[],isNotification:!0})}).pipe(qp,hm(P(()=>{uf(g,Gd),w.get(e)===g&&w.delete(e)})));m.push(_)}h||(yield*lf(n,void 0)),yield*gp(m,{concurrency:`unbounded`,discard:!0}).pipe(Pm({startImmediately:!0}))})),qp,Em,Pm),yield*sce(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(lm(SP,x),lm(P8,b),rm(v))},dm),Vbe=(e,t)=>Gf(I(function*(){let n=yield*r5;yield*Pm(Bbe(e,n,t))})).pipe(Qf(a9.layer)),Hbe=e=>{let t=Yve(e.protocols);return Vbe(e,`http`).pipe(Zf(Ube(e)),Zf(t),Zf(Zse()))},Ube=e=>Hf(SP)(I(function*(){let t=yield*r5,{httpEffect:n,protocol:r}=yield*cce().pipe(lm(pP,Wbe)),i=yield*LN,a=e.allowSessionTermination===!0&&t.protocols.some(e=>e.runtime._tag===`Stateful`),o=N(tM({status:403})),s=t=>n=>d9(n,e.allowedOrigins)?t(n):o,c=N(tM({status:405,headers:{allow:a?`POST, DELETE`:`POST`}})),l=s(()=>c);for(let t of[`GET`,`PUT`,`PATCH`,`OPTIONS`])yield*i.add(t,e.path,l);return yield*i.add(`DELETE`,e.path,a?s(e=>t.terminateHttpSession(e.headers)):l),yield*i.add(`POST`,e.path,r=>{if(!d9(r,e.allowedOrigins))return N(tM({status:403}));if(f9(r.headers[`content-type`])[0]!==`application/json`)return N(tM({status:415}));let i=f9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?N(tM({status:406})):I(function*(){let e=yield*Np(R(r.text,uS(EC))),i=t.admitHttp(r.headers,e);if(i._tag===`Rejected`)return i.response;let a=z(n,e=>{let t=e.body._tag===`Uint8Array`&&e.body.body.subarray(0,-1).includes(10);return i.isSubscription||e.body._tag===`Stream`||t?qbe(e,i.isSubscription):e});return yield*i.acknowledge?zp(a,()=>N(tM({status:202}))):a})}),r})),Wbe=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Kbe();return pP.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}}}})})(),Gbe=/*#__PURE__*/ cS(/*#__PURE__*/ QS(`Cause`,{data:/*#__PURE__*/ LS([/*#__PURE__*/ QS(`Fail`,{error:/*#__PURE__*/ xS(_8)})])})),u9=e=>Array.isArray(e)?e.map(u9):!Yt(e)||!A(e,`error`)?e:Gbe(e.error)?{...e,error:e.error.data[0].error}:e;function Kbe(e){let t=mP(e);return pP.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(Yt(t)){let e=s9.get(t);e!==void 0&&(s9.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=>!(Yt(e)&&!A(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(u9(i))}}}})}const qbe=(e,t)=>{let n=new TextEncoder,r=new TextDecoder,i=e=>n.encode(r.decode(e).trimEnd().split(`
|
|
532
|
-
`).map(e=>`data: ${e}\n\n`).join(``)),a={status:e.status,statusText:e.statusText,headers:
|
|
531
|
+
`,i=(yield*A_e(r)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?e.userId===null?`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})),a=yield*gp({resources:e.resources.list(),clientAccess:e.resources.access(),connections:e.clients.connections()});return{clients:i,resources:a.resources.map(e=>({...e,builtIn:e.identifier===b1(n.baseURL)})),clientAccess:a.clientAccess,connections:a.connections,email:t,issuer:`${n.baseURL}/api/auth`}}),create:V(`Administration.create`)(function*(n){let{providerHeaders:r}=yield*z$,i=yield*e.resources.scopesFor(n.resources),a=yield*r,o=yield*l1(()=>t.api.adminCreateOAuthClient({headers:a,body:{client_name:n.client_name,redirect_uris:[...n.redirect_uris],token_endpoint_auth_method:n.token_endpoint_auth_method,application_type:n.application_type,grant_types:[`authorization_code`,`refresh_token`],scope:i.join(` `),skip_consent:!0}}));return yield*e.resources.setAccess(o.client_id,n.resources).pipe(Wp(()=>l1(()=>t.api.deleteOAuthClient({headers:a,body:{client_id:o.client_id}})))),o}),update:V(`Administration.update`)(function*(e){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>t.api.updateOAuthClient({headers:r,body:{client_id:e.client_id,update:{client_name:e.client_name,redirect_uris:[...e.redirect_uris],application_type:e.application_type}}}))}),access:V(`Administration.access`)(function*(t){return yield*z$,{clientAccess:yield*e.resources.setAccess(t.client_id,t.resources)}}),createResource:V(`Administration.createResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.create(t,r)}),updateResource:V(`Administration.updateResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.update(t,r)}),deleteResource:V(`Administration.deleteResource`)(function*(t){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*e.resources.delete(t.identifier,r)}),delete:V(`Administration.delete`)(function*(t){return yield*z$,yield*e.clients.delete(t.client_id)}),revoke:V(`Administration.revoke`)(function*(t){return yield*z$,yield*e.clients.revoke(t.client_id,t.resource)}),block:V(`Administration.block`)(function*(t){return yield*z$,yield*e.clients.block(t.client_id,t.blocked)}),rotate:V(`Administration.rotate`)(function*(e){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>t.api.rotateClientSecret({headers:r,body:e}))})}}),D6=/*#__PURE__*/ U({method:RS([`GET`,`POST`,`PATCH`,`PUT`,`DELETE`,`HEAD`,`OPTIONS`,`TRACE`,`QUERY`]),url:H,urlParams:W(FS([H,H])),hash:_S(H),headers:MS(H,G([H,BC(H)]))}).annotate({identifier:`HttpRequestDetails`}),j_e=/*#__PURE__*/ U({status:uC,headers:MS(H,G([H,BC(H)]))}).annotate({identifier:`HttpResponseDetails`}),O6=`~effect/ai/AiError/Reason`,k6=()=>P_e.pipe(qS(N({})),mae(N({}))),M_e=e=>{let t=Nn(e),n={};for(let e in t){let r=t[e];ir(n,e,Pg(r)?r.toString():r)}return n};var N_e=class e extends (/*#__PURE__*/ KC(`effect/ai/AiError/NetworkError`)({_tag:/*#__PURE__*/ YS(`NetworkError`),reason:/*#__PURE__*/ RS([`TransportError`,`EncodeError`,`InvalidUrlError`]),request:D6,description:/*#__PURE__*/ _S(H)})){[O6]=O6;get isRetryable(){return this.reason===`TransportError`}static fromRequestError(t){return new e({description:t.description,reason:t._tag,request:{hash:Fi(t.request.hash),headers:M_e(t.request.headers),method:t.request.method,url:t.request.url,urlParams:Array.from(t.request.urlParams)}})}get message(){let e=`${this.request.method} ${this.request.url}`,t=this.description?`${this.reason}: ${this.description}`:`${this.reason}: A network error occurred.`;t+=` (${e})`;let n=``;switch(this.reason){case`EncodeError`:n+=`Check that the request body data is properly formatted and matches the expected content type.`;break;case`InvalidUrlError`:n+=`Verify that the URL format is correct and that all required parameters have been provided.`,n+=` Check for any special characters that may need encoding.`;break;case`TransportError`:n+=`Check your network connection and verify that the requested URL is accessible.`}return t+=`\n\n${n}`,t}};const P_e=/*#__PURE__*/ MS(H,/*#__PURE__*/ zS(bae)),A6=/*#__PURE__*/ U({promptTokens:_S(uC),completionTokens:_S(uC),totalTokens:_S(uC)}).annotate({identifier:`UsageInfo`}),j6=/*#__PURE__*/ U({request:D6,response:_S(j_e),body:_S(H)}).annotate({identifier:`HttpContext`});var F_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/RateLimitError`)({_tag:/*#__PURE__*/ YS(`RateLimitError`),retryAfter:/*#__PURE__*/ _S(RC),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!0}get message(){let e=`Rate limit exceeded`;return this.retryAfter&&(e+=`. Retry after ${To(this.retryAfter)}`),e}},I_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/QuotaExhaustedError`)({_tag:/*#__PURE__*/ YS(`QuotaExhaustedError`),resetAt:/*#__PURE__*/ _S(IC),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`Quota exhausted`;return this.resetAt&&(e+=`. Resets at ${this.resetAt}`),`${e}. Check your account billing and usage limits.`}},L_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/AuthenticationError`)({_tag:/*#__PURE__*/ YS(`AuthenticationError`),kind:/*#__PURE__*/ RS([`InvalidKey`,`ExpiredKey`,`MissingKey`,`InsufficientPermissions`,`Unknown`]),description:/*#__PURE__*/ _S(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`${this.kind}: ${{InvalidKey:`Verify your API key is correct`,ExpiredKey:`Your API key has expired. Generate a new one`,MissingKey:`No API key provided. Set the appropriate environment variable`,InsufficientPermissions:`Your API key lacks required permissions`,Unknown:`Authentication failed. Check your credentials`}[this.kind]}`;return this.description&&(e+=`. ${this.description}`),e}},R_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ContentPolicyError`)({_tag:/*#__PURE__*/ YS(`ContentPolicyError`),description:H,metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){return`Content policy violation: ${this.description}`}},z_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/InvalidRequestError`)({_tag:/*#__PURE__*/ YS(`InvalidRequestError`),parameter:/*#__PURE__*/ _S(H),constraint:/*#__PURE__*/ _S(H),description:/*#__PURE__*/ _S(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){let e=`Invalid request`;return this.parameter&&(e+=`: parameter '${this.parameter}'`),this.constraint&&(e+=` ${this.constraint}`),this.description&&(e+=`. ${this.description}`),e}},B_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/InternalProviderError`)({_tag:/*#__PURE__*/ YS(`InternalProviderError`),description:H,metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!0}get message(){return`Internal provider error: ${this.description}`}},V_e=class e extends (/*#__PURE__*/ KC(`effect/ai/AiError/InvalidOutputError`)({_tag:/*#__PURE__*/ YS(`InvalidOutputError`),description:H,metadata:/*#__PURE__*/ k6(),usage:/*#__PURE__*/ _S(A6)})){[O6]=O6;get isRetryable(){return!0}static fromSchemaError(t){return new e({description:t.message})}get message(){return`Invalid output: ${this.description}`}},H_e=class e extends (/*#__PURE__*/ KC(`effect/ai/AiError/StructuredOutputError`)({_tag:/*#__PURE__*/ YS(`StructuredOutputError`),description:H,responseText:H,metadata:/*#__PURE__*/ k6(),usage:/*#__PURE__*/ _S(A6)})){[O6]=O6;get isRetryable(){return!0}static fromSchemaError(t,n){return new e({description:t.message,responseText:n})}get message(){return`Structured output validation failed: ${this.description}`}},U_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/UnsupportedSchemaError`)({_tag:/*#__PURE__*/ YS(`UnsupportedSchemaError`),description:H,metadata:/*#__PURE__*/ k6()})){[O6]=O6;get isRetryable(){return!1}get message(){return`Unsupported schema: ${this.description}`}},W_e=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/UnknownError`)({_tag:/*#__PURE__*/ YS(`UnknownError`),description:/*#__PURE__*/ _S(H),metadata:/*#__PURE__*/ k6(),http:/*#__PURE__*/ _S(j6)})){[O6]=O6;get isRetryable(){return!1}get message(){return this.description??`Unknown error`}},M6=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ToolNotFoundError`)({_tag:/*#__PURE__*/ YS(`ToolNotFoundError`),toolName:H,availableTools:/*#__PURE__*/ W(H)})){[O6]=O6;get isRetryable(){return!0}get message(){let e=this.availableTools.length>0?this.availableTools.join(`, `):`none`;return`Tool '${this.toolName}' not found. Available tools: ${e}`}},N6=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ YS(`ToolParameterValidationError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}},P6=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/InvalidToolResultError`)({_tag:/*#__PURE__*/ YS(`InvalidToolResultError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Tool '${this.toolName}' returned invalid result: ${this.description}`}},F6=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ToolResultEncodingError`)({_tag:/*#__PURE__*/ YS(`ToolResultEncodingError`),toolName:H,toolResult:wS,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Failed to encode result for tool '${this.toolName}': ${this.description}`}};const G_e=/*#__PURE__*/ G([F_e,I_e,L_e,R_e,z_e,B_e,N_e,V_e,H_e,U_e,W_e,M6,N6,P6,F6,class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ToolConfigurationError`)({_tag:/*#__PURE__*/ YS(`ToolConfigurationError`),toolName:H,description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Invalid configuration for tool '${this.toolName}': ${this.description}`}},class extends (/*#__PURE__*/ KC(`effect/ai/AiError/ToolkitRequiredError`)({_tag:/*#__PURE__*/ YS(`ToolkitRequiredError`),pendingApprovals:/*#__PURE__*/ W(H),description:/*#__PURE__*/ _S(H)})){[O6]=O6;get isRetryable(){return!1}get message(){return`Toolkit required to resolve pending tool approvals: ${this.pendingApprovals.join(`, `)}`}},class extends (/*#__PURE__*/ KC(`effect/ai/AiError/InvalidUserInputError`)({_tag:/*#__PURE__*/ YS(`InvalidUserInputError`),description:H})){[O6]=O6;get isRetryable(){return!1}get message(){return`Invalid user input: ${this.description}`}}]),I6=`~effect/ai/AiError`;var L6=class extends (/*#__PURE__*/ KC(`effect/ai/AiError/AiError`)({_tag:/*#__PURE__*/ YS(`AiError`),module:H,method:H,reason:G_e})){[I6]=I6;cause=this.reason;get isRetryable(){return this.reason.isRetryable}get retryAfter(){return`retryAfter`in this.reason?this.reason.retryAfter:void 0}get message(){return`${this.module}.${this.method}: ${this.reason.message}`}};const K_e=e=>A(e,I6),q_e=e=>A(e,O6),R6=e=>new L6(e),z6=(e,t)=>Object.assign(Object.create(Object.getPrototypeOf(e)),e,t),B6={"~effect/ai/Tool":{_Requirements:k},pipe(){return bt(this,arguments)},addDependency(){return z6(this)},setParameters(e){return z6(this,{parametersSchema:e,jsonSchema:void 0})},setSuccess(e){return z6(this,{successSchema:e})},setFailure(e){return z6(this,{failureSchema:e})},setNeedsApproval(e){return z6(this,{needsApproval:e})},annotate(e,t){return z6(this,{annotations:ra(this.annotations,e,t)})},annotateMerge(e){return z6(this,{annotations:ma(this.annotations,e)})}};({...B6}),{...B6};const J_e=e=>{let t=Object.assign(Object.create(B6),e);return t.id=`effect/ai/Tool/${e.name}`,t},Y_e=(e,t)=>{let n=t?.success??kS,r=t?.failure??SS;return J_e({name:e,description:t?.description,parametersSchema:t?.parameters??eve,successSchema:n,failureSchema:r,failureMode:t?.failureMode??`error`,annotations:ea(),needsApproval:t?.needsApproval})},X_e=e=>{if(e.description!==void 0)return e.description;if(hS(e.parametersSchema))return Ub(e.parametersSchema.ast)};var V6=class extends (/*#__PURE__*/ j()(`effect/ai/Tool/Title`)){},H6=class extends (/*#__PURE__*/ j()(`effect/ai/Tool/Meta`)){};const U6=/*#__PURE__*/ _a(`effect/ai/Tool/Readonly`,{defaultValue:Tt}),W6=/*#__PURE__*/ _a(`effect/ai/Tool/Destructive`,{defaultValue:wt}),G6=/*#__PURE__*/ _a(`effect/ai/Tool/Idempotent`,{defaultValue:Tt}),K6=/*#__PURE__*/ _a(`effect/ai/Tool/OpenWorld`,{defaultValue:wt}),q6=/*#__PURE__*/ _a(`effect/ai/Tool/Strict`,{defaultValue:()=>void 0}),Z_e=e=>la(e.annotations,q6),Q_e=/*#__PURE__*/ U({type:RS([`execution-denied`,`execution-interrupted`]),reason:H}).annotate({identifier:`ToolExecutionFailure`}),$_e=e=>G([L6,e.failureSchema,Q_e]),eve=/*#__PURE__*/ MS(H,SS),J6=`~effect/ai/Toolkit`,Y6=/*#__PURE__*/ _a(`effect/ai/Toolkit/FailureOrigin`,{defaultValue:()=>`result`}),X6=(e,t)=>Id(hd(e),na(Y6,t)),tve={.../*#__PURE__*/ oi({label:`Toolkit`,evaluate:/*#__PURE__*/ B(function*(e){let t=this.tools,n=e.context,r=/* @__PURE__ */ new WeakMap,i=e=>{let t=r.get(e);if(Ht(t)){let i=n.mapUnsafe.get(e.id),a=hS(e.parametersSchema)?sS(e.parametersSchema):e=>N(e),o=uS(e.successSchema),s=uS($_e(e));t={context:i.context,handler:i.handler,decodeParameters:a,encodeResult:(e,t)=>t?s(e):o(e)},r.set(e,t)}return t};return{tools:t,handle:B(function*(e,n,r,a){let o=Object.hasOwn(t,e)?t[e]:void 0;if(yield*Em({tool:e,parameters:n}),Ht(o))return yield*R6({module:`Toolkit`,method:`${e}.handle`,reason:new M6({toolName:e,availableTools:Object.keys(t)})});let s=i(o),c=(t,n)=>s.encodeResult(t,n).pipe(Hp(n=>R6({module:`Toolkit`,method:`${e}.handle`,reason:new F6({toolName:e,toolResult:t,description:n.message})}))),l=yield*Np(s.decodeParameters(n,a));if(wa(l)){let t=R6({module:`Toolkit`,method:`${e}.handle`,reason:new N6({toolName:e,description:l.failure.message})});return o.failureMode===`error`?yield*Tp(X6(t,`parameters`)):VE(z(c(t,!0),e=>({result:t,isFailure:!0,failureOrigin:`parameters`,preliminary:!1,encodedResult:e})))}let u=l.success,d=yield*Qw(),f={toolCallId:r,preliminary:e=>Ip(tT(d,{result:e,isFailure:!1,preliminary:!0}))},p=yield*s.handler(u,f).pipe(R(e=>tT(d,{result:e,isFailure:!1,preliminary:!1})),sm(e=>ma(s.context,e)),Qp({onFailure:e=>aT(d,e),onSuccess:()=>sT(d)}),jm),m=t=>rS(t)?R6({module:`Toolkit`,method:`${e}.handle`,reason:new P6({toolName:e,description:`Tool handler returned invalid result: ${t.message}`})}):q_e(t)?R6({module:`Toolkit`,method:`${e}.handle`,reason:t}):t;return qE(d).pipe(woe(e=>{let t=m(e),n=rS(e)?`result`:`handler`;return o.failureMode===`error`?goe(X6(t,n)):moe({result:t,isFailure:!0,failureOrigin:n,preliminary:!1})}),voe(B(function*(e){let t=yield*c(e.result,e.isFailure);return{...e,encodedResult:t}})),joe(iw(p)))})}})}),[J6]:J6,of:k,toHandlers(e){return I({self:this},function*(){let t=yield*em(),n=hp(e)?yield*e:e,r=/* @__PURE__ */ new Map;for(let[e,i]of Object.entries(n)){let n=Object.hasOwn(this.tools,e)?this.tools[e]:void 0;n!==void 0&&r.set(n.id,{name:e,handler:i,context:t})}return Xi(r)})},toLayer(e){return Wf(this.toHandlers(e))},toJSON(){return{_id:`effect/ai/Toolkit`,tools:Array.from(Object.values(this.tools)).map(e=>e.name)}}},nve=e=>Object.assign(function(){},tve,{tools:e}),rve=(...e)=>{let t={};for(let n of e)ir(t,n.name,n);return t},ive=(...e)=>nve(rve(...e)),Z6=`~effect/rpc/RpcMiddleware`,ave=()=>(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(j(e))),i.key=e,Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[Z6]=Z6,a.error=t?.error??SS,a.requiredForClient=t?.requiredForClient??!1,i},Q6=(e,t)=>{let n=P(t);return gS(e).pipe(KS({decode:Cv(n),encode:_v()}),qS(n))},Z=e=>gS(e).pipe(VS(vS(_S(e)),{decode:_v(),encode:bv(Ri(Pi))})),ove=/*#__PURE__*/ G([H,rC]),$6=/*#__PURE__*/ G([H,rC]);var e8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ NS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ Z($6)}),[K]))}))){},t8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(K)}))){},n8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({_meta:/*#__PURE__*/ Z(K)}))){};const sve=H;({...e8.fields});var r8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({...t8.fields,nextCursor:/*#__PURE__*/ Z(sve)}))){};const cve=/*#__PURE__*/ RS([`user`,`assistant`]);var i8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({audience:/*#__PURE__*/ Z(/*#__PURE__*/ W(cve)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(H)}))){},a8=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/Icon`)({src:H,mimeType:/*#__PURE__*/ Z(H),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ W(H)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ RS([`light`,`dark`]))})){},o8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ Z(H),version:H,icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),description:/*#__PURE__*/ Z(H),websiteUrl:/*#__PURE__*/ Z(H)}))){},lve=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ MS(H,/*#__PURE__*/ U({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ MS(/*#__PURE__*/ xS([H,`/`,H]),ZC)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(DS)})),sampling:/*#__PURE__*/ Z(/*#__PURE__*/ U({context:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ U({}))})),elicitation:/*#__PURE__*/ Z(/*#__PURE__*/ U({form:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),url:/*#__PURE__*/ Z(/*#__PURE__*/ U({}))}))})){},uve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ MS(H,/*#__PURE__*/ U({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ MS(/*#__PURE__*/ xS([H,`/`,H]),ZC)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ U({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(DS)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ Z(DS),listChanged:/*#__PURE__*/ Z(DS)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ Z(DS)}))}))){},s8=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/McpErrorBase`)({code:uC,message:H,data:/*#__PURE__*/ Z(CS)})){};const c8=-32601,l8=-32602,u8=-32603,d8=-32020;var f8=class extends (/*#__PURE__*/ KC(`effect/ai/McpSchema/ParseError`)({...s8.fields,_tag:/*#__PURE__*/ YS(`ParseError`),code:/*#__PURE__*/ YS(-32700)})){},p8=class extends (/*#__PURE__*/ KC(`effect/ai/McpSchema/InvalidRequest`)({...s8.fields,_tag:/*#__PURE__*/ YS(`InvalidRequest`),code:/*#__PURE__*/ YS(-32600)})){},m8=class extends (/*#__PURE__*/ KC(`effect/ai/McpSchema/MethodNotFound`)({...s8.fields,_tag:/*#__PURE__*/ YS(`MethodNotFound`),code:/*#__PURE__*/ YS(c8)})){},h8=class extends (/*#__PURE__*/ KC(`effect/ai/McpSchema/InvalidParams`)({...s8.fields,_tag:/*#__PURE__*/ YS(`InvalidParams`),code:/*#__PURE__*/ YS(l8)})){},g8=class e extends (/*#__PURE__*/ KC(`effect/ai/McpSchema/InternalError`)({...s8.fields,_tag:/*#__PURE__*/ YS(`InternalError`),code:/*#__PURE__*/ YS(u8)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const _8=/*#__PURE__*/ G([f8,p8,m8,h8,g8,s8]);var dve=class extends (/*#__PURE__*/ sP(`ping`,{success:/*#__PURE__*/ U({}),error:_8,payload:/*#__PURE__*/ BS(e8)})){},fve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({...t8.fields,protocolVersion:H,capabilities:uve,serverInfo:o8,instructions:/*#__PURE__*/ Z(H)}))){},pve=class extends (/*#__PURE__*/ sP(`initialize`,{success:fve,error:_8,payload:{...e8.fields,protocolVersion:H,capabilities:lve,clientInfo:o8}})){},v8=class extends (/*#__PURE__*/ sP(`notifications/cancelled`,{payload:{...n8.fields,requestId:ove,reason:/*#__PURE__*/ Z(H)}})){},y8=class extends (/*#__PURE__*/ sP(`notifications/progress`,{payload:{...n8.fields,progressToken:$6,progress:rC,total:/*#__PURE__*/ Z(rC),message:/*#__PURE__*/ Z(H)}})){},mve=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/Resource`)({uri:H,name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),mimeType:/*#__PURE__*/ Z(H),annotations:/*#__PURE__*/ Z(i8),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),size:/*#__PURE__*/ Z(uC),_meta:/*#__PURE__*/ Z(K)})){},b8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ Z(H),_meta:/*#__PURE__*/ Z(K)}))){},hve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({...b8.fields,text:H}))){},gve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({...b8.fields,blob:AC}))){};({...r8.fields}),{...r8.fields},{...t8.fields},{...e8.fields};var x8=class extends (/*#__PURE__*/ sP(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ BS(n8)})){};({...e8.fields}),{...e8.fields};var S8=class extends (/*#__PURE__*/ sP(`notifications/resources/updated`,{payload:{...n8.fields,uri:H}})){},_ve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),required:/*#__PURE__*/ Z(DS)}))){},vve=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/Prompt`)({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ W(_ve)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),_meta:/*#__PURE__*/ Z(K)})){},C8=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({type:/*#__PURE__*/ YS(`text`),text:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){};const yve=/*#__PURE__*/ G([C8,class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({type:/*#__PURE__*/ YS(`image`),data:AC,mimeType:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({type:/*#__PURE__*/ YS(`audio`),data:AC,mimeType:H,annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({type:/*#__PURE__*/ YS(`resource`),resource:/*#__PURE__*/ G([hve,gve]),annotations:/*#__PURE__*/ Z(i8),_meta:/*#__PURE__*/ Z(K)}))){},class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({...mve.fields,type:/*#__PURE__*/ YS(`resource_link`)}))){}]);({...r8.fields}),{...t8.fields},{...e8.fields};var w8=class extends (/*#__PURE__*/ sP(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ BS(n8)})){},bve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({title:/*#__PURE__*/ Z(H),readOnlyHint:/*#__PURE__*/ Q6(DS,Tt),destructiveHint:/*#__PURE__*/ Q6(DS,wt),idempotentHint:/*#__PURE__*/ Q6(DS,Tt),openWorldHint:/*#__PURE__*/ Q6(DS,wt)}))){};const T8=/*#__PURE__*/ NS(/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ MS(H,K)),required:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))}),[K]),E8=K;var D8=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/Tool`)({name:H,title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),inputSchema:T8,outputSchema:/*#__PURE__*/ Z(E8),annotations:/*#__PURE__*/ Z(bve),icons:/*#__PURE__*/ Z(/*#__PURE__*/ W(a8)),_meta:/*#__PURE__*/ Z(K)})){};({...r8.fields});var O8=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/CallToolResult`)({...t8.fields,content:/*#__PURE__*/ W(yve),structuredContent:/*#__PURE__*/ Z(ZC),isError:/*#__PURE__*/ Z(DS)})){};({...e8.fields});var k8=class extends (/*#__PURE__*/ sP(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ BS(n8)})){};const A8=/*#__PURE__*/ RS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({...e8.fields});var j8=class extends (/*#__PURE__*/ sP(`notifications/message`,{payload:/*#__PURE__*/ U({...n8.fields,level:A8,logger:/*#__PURE__*/ Z(H),data:CS})})){},xve=class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ RS([`auto`,`required`,`none`]))})){},Sve=class extends (/*#__PURE__*/ ZS()(/*#__PURE__*/ U({name:/*#__PURE__*/ Z(H)}))){};(class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ W(Sve)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1})))})){}).fields,D8.fields,xve.fields,{...t8.fields};const Cve=/*#__PURE__*/ U({$schema:/*#__PURE__*/ Z(H),type:/*#__PURE__*/ YS(`object`),properties:/*#__PURE__*/ MS(H,/* @__PURE__ */ G([/* @__PURE__ */ G([class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ YS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),enum:/*#__PURE__*/ W(H),enumNames:/*#__PURE__*/ Z(/*#__PURE__*/ W(H)),default:/*#__PURE__*/ Z(H)})){},/* @__PURE__ */ G([class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/UntitledSingleSelectEnum`)({type:/*#__PURE__*/ YS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),enum:/*#__PURE__*/ W(H),default:/*#__PURE__*/ Z(H)})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/TitledSingleSelectEnum`)({type:/*#__PURE__*/ YS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),oneOf:/*#__PURE__*/ W(/*#__PURE__*/ U({const:H,title:H})),default:/*#__PURE__*/ Z(H)})){}]),/* @__PURE__ */ G([class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/UntitledMultiSelectEnum`)({type:/*#__PURE__*/ YS(`array`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minItems:/*#__PURE__*/ Z(uC),maxItems:/*#__PURE__*/ Z(uC),items:/*#__PURE__*/ U({type:/*#__PURE__*/ YS(`string`),enum:/*#__PURE__*/ W(H)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ YS(`array`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minItems:/*#__PURE__*/ Z(uC),maxItems:/*#__PURE__*/ Z(uC),items:/*#__PURE__*/ U({anyOf:/*#__PURE__*/ W(/*#__PURE__*/ U({const:H,title:H}))}),default:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))})){}])]),class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitationString`)({type:/*#__PURE__*/ YS(`string`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minLength:/*#__PURE__*/ Z(uC),maxLength:/*#__PURE__*/ Z(uC),format:/*#__PURE__*/ Z(/*#__PURE__*/ RS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(H)})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ RS([`number`,`integer`]),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),minimum:/*#__PURE__*/ Z(rC),maximum:/*#__PURE__*/ Z(rC),default:/*#__PURE__*/ Z(rC)})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ YS(`boolean`),title:/*#__PURE__*/ Z(H),description:/*#__PURE__*/ Z(H),default:/*#__PURE__*/ Z(DS)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ W(H))}),wve=/*#__PURE__*/ G([class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitRequestFormParams`)({...e8.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ bS(`form`)),message:H,requestedSchema:Cve})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitRequestURLParams`)({...e8.fields,mode:/*#__PURE__*/ bS(`url`),message:H,elicitationId:H,url:H})){}]),Tve=/*#__PURE__*/ G([class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitAcceptResult`)({...t8.fields,action:/*#__PURE__*/ bS(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ MS(H,/*#__PURE__*/ G([H,rC,DS,/*#__PURE__*/ W(H)])))})){},class extends (/*#__PURE__*/ GC(`@effect/ai/McpSchema/ElicitDeclineResult`)({...t8.fields,action:/*#__PURE__*/ RS([`cancel`,`decline`])})){}]);var Eve=class extends (/*#__PURE__*/ sP(`elicitation/create`,{success:Tve,error:_8,payload:wve})){},Dve=class extends (/*#__PURE__*/ sP(`notifications/elicitation/complete`,{payload:{elicitationId:H}})){};Eve.payloadSchema;var Ove=class extends (/*#__PURE__*/ Bo(`McpReverseOperationUnsupported`)){},M8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/McpRequestContext`)){},N8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/McpServerClient`)){},P8=class extends (/*#__PURE__*/ ave()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},kve=class extends (/*#__PURE__*/ wP(v8,y8,j8,S8,x8,k8,w8,Dve)){},F8=class extends (/*#__PURE__*/ j()(`effect/ai/McpSchema/EnabledWhen`)){};const I8={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var Ave=class extends (/*#__PURE__*/ Bo(`ResourceNotFound`)){},jve=class extends (/*#__PURE__*/ Bo(`ToolNotFound`)){},Mve=class extends (/*#__PURE__*/ Bo(`InvalidToolInput`)){},Nve=class extends (/*#__PURE__*/ Bo(`InvalidToolContinuation`)){},Pve=class extends (/*#__PURE__*/ Bo(`ToolExecutionError`)){},Fve=class extends (/*#__PURE__*/ Bo(`PromptNotFound`)){};const L8=/*#__PURE__*/ Lo(),Ive=/*#__PURE__*/ P(()=>{let e=/* @__PURE__ */ new Map,t=[],n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{tools:{register:t=>P(()=>{e.set(t.descriptor.name,t)}),list:t=>P(()=>{let n=[];for(let r of e.values())r.isVisible(t)&&n.push(r.descriptor);return n}),call:(t,n)=>Sp(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new jve({name:t.name}):r.handle(t,n)})},resources:{register:e=>P(()=>{let n=t.findIndex(t=>t.descriptor.uri===e.descriptor.uri);n===-1?t.push(e):t[n]=e}),registerTemplate:e=>P(()=>{let t=n.findIndex(t=>t.descriptor.uriTemplate===e.descriptor.uriTemplate);t===-1?n.push(e):n[t]=e}),list:e=>P(()=>t.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),listTemplates:e=>P(()=>n.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),read:B(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 Ave({uri:e})})},prompts:{register:e=>P(()=>{r.set(e.descriptor.name,e)}),list:e=>P(()=>Array.from(r.values()).filter(t=>t.isVisible(e)).map(e=>e.descriptor)),get:B(function*(e,t,n){let i=r.get(e);return i===void 0||!i.isVisible(n.protocol)?yield*new Fve({name:e}):yield*i.get(t,n)})},completions:{register:(e,t)=>P(()=>{i.set(e,t)}),complete:B(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 h8({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=Jee(a.values,100);return{...a,values:o,hasMore:a.hasMore===!0||o.length<a.values.length}})},registrationPresence:P(()=>({tools:e.size>0,resources:t.length>0||n.length>0,prompts:r.size>0}))}}),Lve=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),R8={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}},z8=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=Jh(e.slice(9,-2));if(!wa(r))try{return Lve.decode(r.success)}catch{return}},Rve=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),B8=e=>({clientId:e.clientId,protocol:Rve(e),requestContext:M8.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),V8=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),H8=e=>Yt(e)&&(e.type===`tool_use`||e.type===`tool_result`),zve=e=>Yt(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!Yt(e))return!1;let t=e.content;return Array.isArray(t)?t.some(H8):H8(t)}):!1:!1;var U8=class e extends (/*#__PURE__*/ Bo(`ProtocolError`)){static fromTool(t){let n=wO(t).pipe(EO(`ToolNotFound`,e=>`Tool '${e.name}' not found`),EO(`UnsupportedByProtocol`,e=>`${e.feature} is not supported by MCP ${e.protocolVersion}`),DO({InvalidToolInput:e=>e.message,InvalidToolContinuation:e=>e.message,ToolExecutionError:e=>e.message}),NO);return new e({code:t._tag===`ToolExecutionError`?u8:l8,message:n})}static fromFeature(t){if(A(t,`_tag`)){if(t._tag===`PromptNotFound`&&A(t,`name`)&&It(t.name))return new e({code:l8,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&A(t,`uri`)&&It(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=Bve(t);return Ta(n)?new e(n.success):new e({code:u8,message:`MCP feature handler failed`})}};const Bve=/*#__PURE__*/ uae(/* @__PURE__ */ U({code:rC,message:H,data:/*#__PURE__*/ gS(wS)})),W8=(e,t,n)=>dS(e)(n).pipe(R(sS(t))),Vve=/*#__PURE__*/ V(function*(e,t){return L8.$match(t,{Cancelled:e=>({tag:v8._tag,payload:v8.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:y8._tag,payload:y8.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:j8._tag,payload:j8.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:S8._tag,payload:S8.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:x8._tag,payload:x8.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:k8._tag,payload:k8.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:w8._tag,payload:w8.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),G8=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},Hve=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=JC(e.payloadSchema);n={decode:sS(r),encode:uS(r)},t.set(e,n)}return n},r=(t,n,r)=>e.handlerRpcs===void 0||e.makeHandlers===void 0?F:n===void 0&&e.runtime._tag===`Stateful`?Dp(`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=>nce(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(z(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},K8=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,Uve=/*#__PURE__*/ B(function*(e){if(e.length===0)return yield*new Nd(`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 Nd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(K8(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(K8(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(K8(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${K8(e)}${t.tag}`}),handlerTarget:(e,t)=>({context:t,install:B(function*(t,n,i){let a=yield*n.toHandlers(i);for(let i of n.requests.values()){let n=r.requests.get(`${K8(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*Dp(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),q8=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),Wve=()=>{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=q8(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=q8(n);return t.set(e,r),r},resolve:r,resolveSessionId:t=>e.get(t),terminateSession:t=>e.delete(t),setLogLevel:(e,t,n)=>P(()=>{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?L(new U8({code:c8,message:`Resource subscriptions are not supported`})):P(()=>i.add(e)).pipe(Ip)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?L(new U8({code:c8,message:`Resource subscriptions are not supported`})):P(()=>i.delete(e)).pipe(Ip)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?R8[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`?R8[n.level].order>=R8[e.level].order:_D(R8[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)}}},J8=`mcp-session-id`,Y8=`mcp-protocol-version`,X8=`io.modelcontextprotocol/protocolVersion`,Z8=`io.modelcontextprotocol/clientCapabilities`,Q8=-32022,$8=e=>typeof e==`object`&&e?e:void 0,e5=e=>{let t=$8(e);return t!==void 0&&X8 in t?{present:!0,value:t[X8]}:{present:!1,value:void 0}},Gve=e=>e5($8($8(e)?.params)?._meta).present,Kve=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},t5=e=>({_tag:`Rejected`,status:400,error:{code:d8,message:e}}),n5=/*#__PURE__*/ wP(dve);var r5=class extends (/*#__PURE__*/ j()(`effect/ai/McpRuntime/ServerRuntime`)){};const i5=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),qve=/*#__PURE__*/ B(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:Wve(),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 Nd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*Uve(e),o=/* @__PURE__ */ new Set,s=e=>({code:Q8,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[Y8],a=e[J8],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 t5(`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[Y8],a=$8(n),o=$8($8(a?.params)?._meta),l=e5(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 t5(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:l8,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return t5(`MCP-Protocol-Version header does not match request metadata`);if(!f&&$8(o?.[Z8])===void 0)return{_tag:`Rejected`,status:400,error:{code:l8,message:`${Z8} 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 t5(`Mcp-Method header does not match request method`);let n=Kve(t);if(n!==void 0){let t=$8(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||z8(r)!==t)return t5(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return r5.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:B(function*(e,n,o){let c=$8(o.payload)?._meta,l=e5(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=i5(a.protocols,e);if(t===void 0)return yield*new U8({code:Q8,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?i5(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*Dp(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new U8(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=M8.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?eM({status:e}):oM({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(wa(r)){let t=e[Y8];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 f8({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new p8({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(Gve)||a.some(e=>A(e,`method`)&&e.method===`initialize`)||t.binding?.protocol.runtime.transport.jsonRpc.acceptsBatches!==!0?i(400):{_tag:`Accepted`,acknowledge:!a.some(e=>A(e,`method`)&&A(e,`id`)),isSubscription:!1}}let o=A(a,`id`),c=o&&(typeof a.id==`string`||typeof a.id==`number`)?a.id:null,u=A(a,`jsonrpc`)&&a.jsonrpc===`2.0`,d=!o||typeof a.id==`string`||typeof a.id==`number`,f=u&&d&&A(a,`method`)&&typeof a.method==`string`,p=o&&(typeof a.id==`string`||typeof a.id==`number`||a.id===null),m=A(a,`result`),h=A(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 p8({message:`Invalid Request`}),c);let v=A(a,`method`)&&a.method===`initialize`,y=e[J8]!==void 0;return v&&y?i(400,new p8({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 p8({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 m8({message:`Method not found: ${a.method}`}),c):{_tag:`Accepted`,acknowledge:!f||!o,isSubscription:A(a,`method`)&&a.method===`subscriptions/listen`}},effectLogLevel:(e,n,r)=>t?.effectLogLevel(e,n,r)??r,disconnect:e=>t?.disconnect(e),terminateHttpSession:e=>Sp(()=>{let n=e[J8];if(n===void 0)return N(eM({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return N(eM({status:r.status}));let i=r.binding;return t.terminateSession(n),Fp(_p(o,e=>e(i),{discard:!0}),eM({status:204}))}),onSessionTerminated:e=>fm(P(()=>{o.add(e)}),()=>P(()=>{o.delete(e)})),deliveryClientIds:()=>t?.initializedClientIds()??[],canDeliver:(e,n,r,i)=>t?.canDeliver(e,n,r,i)??!0,installHandlers:B(function*(e){let r=/* @__PURE__ */ new Map,i={subscribeServerNotifications:e.subscribeServerNotifications,...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*Dp(`MCP sessionful runtime invariant failed`);yield*o.install(n,n5,n5.of({ping:()=>N({})}));let r={initialize:B(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*kp(s=>{let c=oa(s.context,DN),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:pve.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),FN(c,(t,r)=>N(fM(r,{[J8]:e,[Y8]:n.protocolVersion})))}else t.registerConnection(a,u);return N({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:o8.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:B(function*(e,n){e._tag===`Initialized`&&t.markInitialized(n)})};yield*n.installHandlers(e.core,r,o)}return Xi(r)})})}),Jve=e=>Hf(r5)(qve(e)),a5=e=>gS(e).pipe(VS(vS(_S(e)),{decode:_v(),encode:bv(Ri(Pi))})),o5=K,Yve=/*#__PURE__*/ G([H,rC]),s5=/*#__PURE__*/ RS([`user`,`assistant`]),Xve=/*#__PURE__*/ RS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),c5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(/*#__PURE__*/ NS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ a5(Yve)}),[K]))}),l5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(o5)}),u5=/*#__PURE__*/ U({_meta:/*#__PURE__*/ a5(o5)});({...c5.fields});const d5=/*#__PURE__*/ U({...u5.fields,nextCursor:/*#__PURE__*/ a5(H)}),Zve=/*#__PURE__*/ U({extensions:/*#__PURE__*/ a5(/*#__PURE__*/ MS(/*#__PURE__*/ xS([H,`/`,H]),ZC)),experimental:/*#__PURE__*/ a5(/*#__PURE__*/ MS(H,o5)),roots:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(DS)})),sampling:/*#__PURE__*/ a5(o5)}),Qve=/*#__PURE__*/ U({extensions:/*#__PURE__*/ a5(/*#__PURE__*/ MS(/*#__PURE__*/ xS([H,`/`,H]),ZC)),experimental:/*#__PURE__*/ a5(/*#__PURE__*/ MS(H,o5)),logging:/*#__PURE__*/ a5(o5),prompts:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(DS)})),resources:/*#__PURE__*/ a5(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ a5(DS),listChanged:/*#__PURE__*/ a5(DS)})),tools:/*#__PURE__*/ a5(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ a5(DS)}))}),f5=/*#__PURE__*/ U({code:uC,message:H,data:/*#__PURE__*/ a5(CS)}),p5=/*#__PURE__*/ U({audience:/*#__PURE__*/ a5(/*#__PURE__*/ W(s5)),priority:/*#__PURE__*/ a5(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1})))}),$ve=/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ a5(H),text:H}),eye=/*#__PURE__*/ U({uri:H,mimeType:/*#__PURE__*/ a5(H),blob:H}),tye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`text`),text:H,annotations:/*#__PURE__*/ a5(p5)}),nye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`image`),data:H,mimeType:H,annotations:/*#__PURE__*/ a5(p5)}),rye=/*#__PURE__*/ U({uri:H,name:H,description:/*#__PURE__*/ a5(H),mimeType:/*#__PURE__*/ a5(H),size:/*#__PURE__*/ a5(rC),annotations:/*#__PURE__*/ a5(p5)}),iye=/*#__PURE__*/ U({uriTemplate:H,name:H,description:/*#__PURE__*/ a5(H),mimeType:/*#__PURE__*/ a5(H),annotations:/*#__PURE__*/ a5(p5)}),m5=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),required:/*#__PURE__*/ a5(DS)}),aye=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),arguments:/*#__PURE__*/ a5(/*#__PURE__*/ W(m5))}),oye=/*#__PURE__*/ U({name:H,description:/*#__PURE__*/ a5(H),inputSchema:/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`object`),properties:/*#__PURE__*/ a5(/*#__PURE__*/ MS(H,o5)),required:/*#__PURE__*/ a5(/*#__PURE__*/ W(H))})}),h5=/*#__PURE__*/ U({hints:/*#__PURE__*/ a5(/*#__PURE__*/ W(/* @__PURE__ */ U({name:/*#__PURE__*/ a5(H)}))),costPriority:/*#__PURE__*/ a5(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ a5(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ a5(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1})))}),sye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`ref/prompt`),name:H}),cye=/*#__PURE__*/ U({uri:H,name:/*#__PURE__*/ a5(H)});({...u5.fields}),{...d5.fields},{...d5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...u5.fields},{...u5.fields},{...u5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...l5.fields},{...l5.fields},{...l5.fields},{...l5.fields};const g5=a5,lye=/*#__PURE__*/ U({...Qve.fields,completions:/*#__PURE__*/ g5(/*#__PURE__*/ U({}))}),uye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`audio`),data:H,mimeType:H,annotations:/*#__PURE__*/ g5(p5)}),_5=/*#__PURE__*/ U({title:/*#__PURE__*/ g5(H),readOnlyHint:/*#__PURE__*/ g5(DS),destructiveHint:/*#__PURE__*/ g5(DS),idempotentHint:/*#__PURE__*/ g5(DS),openWorldHint:/*#__PURE__*/ g5(DS)});({...oye.fields}),{...u5.fields},{...u5.fields},{...d5.fields},{...u5.fields},{...u5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...c5.fields},{...l5.fields};const v5=a5,y5=K,b5=/*#__PURE__*/ v5(y5),x5=/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ v5(H),version:H}),S5=/*#__PURE__*/ U({...Zve.fields,elicitation:/*#__PURE__*/ v5(/*#__PURE__*/ U({}))}),C5=/*#__PURE__*/ U({audience:/*#__PURE__*/ v5(/*#__PURE__*/ W(s5)),priority:/*#__PURE__*/ v5(/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1})))}),w5=/*#__PURE__*/ U({...rye.fields,title:/*#__PURE__*/ v5(H),annotations:/*#__PURE__*/ v5(C5),_meta:b5}),dye=/*#__PURE__*/ U({...iye.fields,title:/*#__PURE__*/ v5(H),annotations:/*#__PURE__*/ v5(C5),_meta:b5}),T5=/*#__PURE__*/ G([/* @__PURE__ */ U({...$ve.fields,_meta:b5}),/* @__PURE__ */ U({...eye.fields,_meta:b5})]),fye=/*#__PURE__*/ U({...m5.fields,title:/*#__PURE__*/ v5(H)}),pye=/*#__PURE__*/ U({...aye.fields,title:/*#__PURE__*/ v5(H),arguments:/*#__PURE__*/ v5(/*#__PURE__*/ W(fye)),_meta:b5}),E5=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`resource`),resource:T5,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),mye=/*#__PURE__*/ U({...w5.fields,type:/*#__PURE__*/ bS(`resource_link`)}),D5=/*#__PURE__*/ U({...tye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),O5=/*#__PURE__*/ U({...nye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),k5=/*#__PURE__*/ U({...uye.fields,annotations:/*#__PURE__*/ v5(C5),_meta:b5}),A5=/*#__PURE__*/ G([D5,O5,k5,E5,mye]),j5=/*#__PURE__*/ G([D5,O5,k5]),hye=/*#__PURE__*/ U({role:s5,content:A5}),gye=/*#__PURE__*/ U({role:s5,content:j5}),_ye=/*#__PURE__*/ U({...lye.fields}),M5=/*#__PURE__*/ U({...u5.fields,protocolVersion:H,capabilities:_ye,serverInfo:x5,instructions:/*#__PURE__*/ v5(H)});var vye=class extends (/*#__PURE__*/ sP(`initialize`,{success:M5,error:f5,payload:{...c5.fields,protocolVersion:H,capabilities:S5,clientInfo:x5}})){};const N5=/*#__PURE__*/ NS(/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`object`),properties:/*#__PURE__*/ v5(/*#__PURE__*/ MS(H,y5)),required:/*#__PURE__*/ v5(/*#__PURE__*/ W(H))}),[K]),yye=/*#__PURE__*/ U({name:H,title:/*#__PURE__*/ v5(H),description:/*#__PURE__*/ v5(H),inputSchema:N5,outputSchema:/*#__PURE__*/ v5(N5),annotations:/*#__PURE__*/ v5(_5),_meta:b5}),P5=/*#__PURE__*/ U({...u5.fields,content:/*#__PURE__*/ W(A5),structuredContent:/*#__PURE__*/ v5(y5),isError:/*#__PURE__*/ v5(DS)}),bye=/*#__PURE__*/ U({...u5.fields,role:s5,content:j5,model:H,stopReason:/*#__PURE__*/ v5(H)});var xye=class extends (/*#__PURE__*/ sP(`sampling/createMessage`,{success:bye,error:f5,payload:{...c5.fields,messages:/*#__PURE__*/ W(gye),modelPreferences:/*#__PURE__*/ v5(h5),systemPrompt:/*#__PURE__*/ v5(H),includeContext:/*#__PURE__*/ v5(/*#__PURE__*/ RS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ v5(rC),maxTokens:rC,stopSequences:/*#__PURE__*/ v5(/*#__PURE__*/ W(H)),metadata:/*#__PURE__*/ v5(y5)}})){};const Sye=/*#__PURE__*/ U({...sye.fields,title:/*#__PURE__*/ v5(H)}),Cye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`ref/resource`),uri:H});({...c5.fields}),{...d5.fields},{...d5.fields},{...u5.fields},{...d5.fields};const wye=/*#__PURE__*/ U({...u5.fields,description:/*#__PURE__*/ v5(H),messages:/*#__PURE__*/ W(hye)});({...d5.fields}),{...c5.fields},{...c5.fields};var Tye=class extends (/*#__PURE__*/ sP(`tools/call`,{success:P5,error:f5,payload:{...c5.fields,name:H,arguments:/*#__PURE__*/ v5(y5)}})){};({...u5.fields}),{...c5.fields};const Q=a5,F5=K,I5=/*#__PURE__*/ Q(F5),L5=/*#__PURE__*/ U({src:H,mimeType:/*#__PURE__*/ Q(H),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ W(H)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ RS([`light`,`dark`]))}),Eye=/*#__PURE__*/ U({...x5.fields,description:/*#__PURE__*/ Q(H),websiteUrl:/*#__PURE__*/ Q(H),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))});({...S5.fields});const R5=/*#__PURE__*/ U({...C5.fields,lastModified:/*#__PURE__*/ Q(H)}),z5=/*#__PURE__*/ U({...w5.fields,annotations:/*#__PURE__*/ Q(R5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),Dye=/*#__PURE__*/ U({...dye.fields,annotations:/*#__PURE__*/ Q(R5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),Oye=/*#__PURE__*/ U({...pye.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))}),B5=/*#__PURE__*/ U({...D5.fields,annotations:/*#__PURE__*/ Q(R5)}),V5=/*#__PURE__*/ U({...O5.fields,annotations:/*#__PURE__*/ Q(R5)}),H5=/*#__PURE__*/ U({...k5.fields,annotations:/*#__PURE__*/ Q(R5)}),U5=/*#__PURE__*/ U({...E5.fields,annotations:/*#__PURE__*/ Q(R5)}),kye=/*#__PURE__*/ G([B5,V5,H5,/* @__PURE__ */ U({...z5.fields,type:/*#__PURE__*/ bS(`resource_link`)}),U5]),Aye=/*#__PURE__*/ U({...yye.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ W(L5))});({...P5.fields}),Tye.payloadSchema;const W5=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`tool_use`),id:H,name:H,input:F5,_meta:I5}),G5=/*#__PURE__*/ G([B5,V5,H5,W5,/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`tool_result`),toolUseId:H,content:/*#__PURE__*/ W(kye),structuredContent:/*#__PURE__*/ Q(F5),isError:/*#__PURE__*/ Q(DS),_meta:I5})]),jye=/*#__PURE__*/ U({role:s5,content:/*#__PURE__*/ G([G5,/*#__PURE__*/ W(G5)]),_meta:I5}),Mye=/*#__PURE__*/ U({mode:/*#__PURE__*/ Q(/*#__PURE__*/ RS([`auto`,`required`,`none`]))});({...u5.fields,...jye.fields}),{...xye.payloadSchema.fields};const Nye=/*#__PURE__*/ U({...cye.fields,_meta:I5});({...u5.fields});const Pye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minLength:/*#__PURE__*/ Q(uC),maxLength:/*#__PURE__*/ Q(uC),format:/*#__PURE__*/ Q(/*#__PURE__*/ RS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(H)}),Fye=/*#__PURE__*/ U({type:/*#__PURE__*/ RS([`number`,`integer`]),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minimum:/*#__PURE__*/ Q(rC),maximum:/*#__PURE__*/ Q(rC),default:/*#__PURE__*/ Q(rC)}),Iye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`boolean`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),default:/*#__PURE__*/ Q(DS)}),K5=/*#__PURE__*/ U({const:H,title:H}),Lye=/*#__PURE__*/ G([/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),enum:/*#__PURE__*/ W(H),default:/*#__PURE__*/ Q(H)}),/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),oneOf:/*#__PURE__*/ W(K5),default:/*#__PURE__*/ Q(H)})]),Rye=/*#__PURE__*/ G([/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`array`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minItems:/*#__PURE__*/ Q(uC),maxItems:/*#__PURE__*/ Q(uC),items:/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`string`),enum:/*#__PURE__*/ W(H)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ W(H))}),/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`array`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),minItems:/*#__PURE__*/ Q(uC),maxItems:/*#__PURE__*/ Q(uC),items:/*#__PURE__*/ U({anyOf:/*#__PURE__*/ W(K5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ W(H))})]),zye=/*#__PURE__*/ U({type:/*#__PURE__*/ bS(`string`),title:/*#__PURE__*/ Q(H),description:/*#__PURE__*/ Q(H),enum:/*#__PURE__*/ W(H),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ W(H)),default:/*#__PURE__*/ Q(H)});({...c5.fields}),{...c5.fields},{...u5.fields},{...M5.fields},{...vye.payloadSchema.fields},{...d5.fields},{...d5.fields},{...d5.fields},{...wye.fields},{...d5.fields},{...c5.fields};const q5=`2026-07-28`,$=a5,J5=/*#__PURE__*/ $(K),Y5=/*#__PURE__*/ G([H,uC]),X5=Y5,Z5=s5,Q5=Xve,$5=Eye,Bye=/*#__PURE__*/ NS(/*#__PURE__*/ U({experimental:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,K)),roots:/*#__PURE__*/ $(/*#__PURE__*/ U({})),sampling:/*#__PURE__*/ $(/*#__PURE__*/ U({context:/*#__PURE__*/ $(K),tools:/*#__PURE__*/ $(K)})),elicitation:/*#__PURE__*/ $(/*#__PURE__*/ U({form:/*#__PURE__*/ $(K),url:/*#__PURE__*/ $(K)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,K))}),[K]),Vye=/*#__PURE__*/ NS(/*#__PURE__*/ U({experimental:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,K)),logging:/*#__PURE__*/ $(K),completions:/*#__PURE__*/ $(K),prompts:/*#__PURE__*/ $(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ $(DS)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ U({subscribe:/*#__PURE__*/ $(DS),listChanged:/*#__PURE__*/ $(DS)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ U({listChanged:/*#__PURE__*/ $(DS)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,K))}),[K]),e7=/*#__PURE__*/ NS(/*#__PURE__*/ U({progressToken:/*#__PURE__*/ $(X5),"io.modelcontextprotocol/protocolVersion":H,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $($5),"io.modelcontextprotocol/clientCapabilities":Bye,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(Q5)}),[K]),t7=/*#__PURE__*/ U({_meta:e7}),n7=/*#__PURE__*/ U({_meta:/*#__PURE__*/ $(/* @__PURE__ */ NS(/*#__PURE__*/ U({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $(Y5)}),[K]))}),r7=/*#__PURE__*/ NS(/*#__PURE__*/ U({"io.modelcontextprotocol/serverInfo":$5}),[K]),i7={_meta:r7,resultType:/*#__PURE__*/ bS(`complete`)},a7=/*#__PURE__*/ U({code:uC,message:H,data:/*#__PURE__*/ $(ZC)}),Hye=R5,o7=/*#__PURE__*/ U({...z5.fields,size:/*#__PURE__*/ $(uC),annotations:/*#__PURE__*/ $(Hye)}),s7=Dye,Uye=T5,c7=B5,l7=V5,u7=H5,d7=/*#__PURE__*/ G([c7,l7,u7,/* @__PURE__ */ U({...o7.fields,type:/*#__PURE__*/ bS(`resource_link`)}),U5]),f7=Oye,Wye=/*#__PURE__*/ U({role:Z5,content:d7}),Gye=/*#__PURE__*/ NS(/*#__PURE__*/ U({$schema:/*#__PURE__*/ $(H),type:/*#__PURE__*/ bS(`object`)}),[K]),Kye=/*#__PURE__*/ NS(/*#__PURE__*/ U({$schema:/*#__PURE__*/ $(H)}),[K]),qye=_5,p7=/*#__PURE__*/ U({...Aye.fields,inputSchema:Gye,outputSchema:/*#__PURE__*/ $(Kye),annotations:/*#__PURE__*/ $(qye)}),m7=/*#__PURE__*/ G([c7,l7,u7,W5,/* @__PURE__ */ U({type:/*#__PURE__*/ bS(`tool_result`),toolUseId:H,content:/*#__PURE__*/ W(d7),structuredContent:/*#__PURE__*/ $(ZC),isError:/*#__PURE__*/ $(DS),_meta:J5})]),h7=/*#__PURE__*/ U({role:Z5,content:/*#__PURE__*/ G([m7,/*#__PURE__*/ W(m7)]),_meta:J5}),Jye=/*#__PURE__*/ NS(/*#__PURE__*/ U({name:/*#__PURE__*/ $(H)}),[K]),g7=/*#__PURE__*/ rC.check(/*#__PURE__*/ cC({minimum:0,maximum:1})),Yye=/*#__PURE__*/ U({...h5.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ W(Jye)),costPriority:/*#__PURE__*/ $(g7),speedPriority:/*#__PURE__*/ $(g7),intelligencePriority:/*#__PURE__*/ $(g7)}),Xye=/*#__PURE__*/ U({method:/*#__PURE__*/ bS(`sampling/createMessage`),params:/*#__PURE__*/ U({messages:/*#__PURE__*/ W(h7),modelPreferences:/*#__PURE__*/ $(Yye),systemPrompt:/*#__PURE__*/ $(H),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ RS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(rC),maxTokens:uC,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ W(H)),metadata:/*#__PURE__*/ $(K),tools:/*#__PURE__*/ $(/*#__PURE__*/ W(p7)),toolChoice:/*#__PURE__*/ $(Mye)})}),Zye=/*#__PURE__*/ U({...h7.fields,model:H,stopReason:/*#__PURE__*/ $(H)}),Qye=Nye,$ye=/*#__PURE__*/ U({method:/*#__PURE__*/ bS(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ U({_meta:J5}))}),ebe=/*#__PURE__*/ U({roots:/*#__PURE__*/ W(Qye)}),tbe=/*#__PURE__*/ U({method:/*#__PURE__*/ bS(`elicitation/create`),params:/* @__PURE__ */ G([/* @__PURE__ */ U({mode:/*#__PURE__*/ $(/*#__PURE__*/ bS(`form`)),message:H,requestedSchema:/* @__PURE__ */ U({$schema:/*#__PURE__*/ $(H),type:/*#__PURE__*/ bS(`object`),properties:/*#__PURE__*/ MS(H,/* @__PURE__ */ G([/* @__PURE__ */ G([zye,Lye,Rye]),Pye,Fye,Iye])),required:/*#__PURE__*/ $(/*#__PURE__*/ W(H))})}),/* @__PURE__ */ U({mode:/*#__PURE__*/ bS(`url`),message:H,url:H})])}),nbe=/*#__PURE__*/ U({action:/*#__PURE__*/ RS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,/*#__PURE__*/ G([H,rC,DS,/*#__PURE__*/ W(H)])))}),rbe=/*#__PURE__*/ G([Xye,$ye,tbe]),ibe=/*#__PURE__*/ G([Zye,ebe,nbe]),_7=/*#__PURE__*/ MS(H,rbe),abe=/*#__PURE__*/ MS(H,ibe),v7={_meta:r7,resultType:/*#__PURE__*/ bS(`input_required`)},y7=/*#__PURE__*/ G([/*#__PURE__*/ NS(/*#__PURE__*/ U({...v7,inputRequests:_7,requestState:/*#__PURE__*/ $(H)}),[K]),/*#__PURE__*/ NS(/*#__PURE__*/ U({...v7,inputRequests:/*#__PURE__*/ $(_7),requestState:H}),[K])]),b7={...t7.fields,inputResponses:/*#__PURE__*/ $(abe),requestState:/*#__PURE__*/ $(H)},x7={...i7,ttlMs:/*#__PURE__*/ uC.check(/*#__PURE__*/ sC(0)),cacheScope:/*#__PURE__*/ RS([`public`,`private`])},S7={...t7.fields,cursor:/*#__PURE__*/ $(H)},C7={...i7,nextCursor:/*#__PURE__*/ $(H)},w7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...x7,supportedVersions:/*#__PURE__*/ W(H),capabilities:Vye,instructions:/*#__PURE__*/ $(H)}),[K]);var obe=class extends (/*#__PURE__*/ sP(`server/discover`,{success:w7,error:a7,payload:t7})){};const T7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...C7,...x7,resources:/*#__PURE__*/ W(o7)}),[K]);var sbe=class extends (/*#__PURE__*/ sP(`resources/list`,{success:T7,error:a7,payload:S7})){};const E7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...C7,...x7,resourceTemplates:/*#__PURE__*/ W(s7)}),[K]);var cbe=class extends (/*#__PURE__*/ sP(`resources/templates/list`,{success:E7,error:a7,payload:S7})){};const D7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...x7,contents:/*#__PURE__*/ W(Uye)}),[K]);var lbe=class extends (/*#__PURE__*/ sP(`resources/read`,{success:/*#__PURE__*/ G([D7,y7]),error:a7,payload:{...b7,uri:H}})){};const O7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...C7,...x7,prompts:/*#__PURE__*/ W(f7)}),[K]);var ube=class extends (/*#__PURE__*/ sP(`prompts/list`,{success:O7,error:a7,payload:S7})){};const k7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...i7,description:/*#__PURE__*/ $(H),messages:/*#__PURE__*/ W(Wye)}),[K]);var dbe=class extends (/*#__PURE__*/ sP(`prompts/get`,{success:/*#__PURE__*/ G([k7,y7]),error:a7,payload:{...b7,name:H,arguments:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,H))}})){};const A7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...C7,...x7,tools:/*#__PURE__*/ W(p7)}),[K]);var fbe=class extends (/*#__PURE__*/ sP(`tools/list`,{success:A7,error:a7,payload:S7})){};const j7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...i7,content:/*#__PURE__*/ W(d7),structuredContent:/*#__PURE__*/ $(ZC),isError:/*#__PURE__*/ $(DS)}),[K]);var pbe=class extends (/*#__PURE__*/ sP(`tools/call`,{success:/*#__PURE__*/ G([j7,y7]),error:a7,payload:{...b7,name:H,arguments:/*#__PURE__*/ $(K)}})){};const mbe=Sye,hbe=Cye,M7=/*#__PURE__*/ NS(/*#__PURE__*/ U({...i7,completion:/*#__PURE__*/ U({values:/*#__PURE__*/ W(H).check(/*#__PURE__*/ mC(100)),total:/*#__PURE__*/ $(uC),hasMore:/*#__PURE__*/ $(DS)})}),[K]);var gbe=class extends (/*#__PURE__*/ sP(`completion/complete`,{success:M7,error:a7,payload:{...t7.fields,ref:/*#__PURE__*/ G([mbe,hbe]),argument:/*#__PURE__*/ U({name:H,value:H}),context:/*#__PURE__*/ $(/*#__PURE__*/ U({arguments:/*#__PURE__*/ $(/*#__PURE__*/ MS(H,H))}))}})){};const N7=/*#__PURE__*/ U({toolsListChanged:/*#__PURE__*/ $(DS),promptsListChanged:/*#__PURE__*/ $(DS),resourcesListChanged:/*#__PURE__*/ $(DS),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ W(H))}),P7=/*#__PURE__*/ NS(/*#__PURE__*/ U({_meta:/* @__PURE__ */ NS(/*#__PURE__*/ U({"io.modelcontextprotocol/serverInfo":$5,"io.modelcontextprotocol/subscriptionId":Y5}),[K]),resultType:/*#__PURE__*/ bS(`complete`)}),[K]);var _be=class extends (/*#__PURE__*/ sP(`subscriptions/listen`,{success:P7,error:a7,payload:{...t7.fields,notifications:N7}})){},F7=class extends (/*#__PURE__*/ sP(`notifications/cancelled`,{payload:{...n7.fields,requestId:Y5,reason:/*#__PURE__*/ $(H)}})){},vbe=class extends (/*#__PURE__*/ sP(`notifications/progress`,{payload:{...n7.fields,progressToken:X5,progress:rC,total:/*#__PURE__*/ $(rC),message:/*#__PURE__*/ $(H)}})){},ybe=class extends (/*#__PURE__*/ sP(`notifications/message`,{payload:{...n7.fields,level:Q5,logger:/*#__PURE__*/ $(H),data:ZC}})){},I7=class extends (/*#__PURE__*/ sP(`notifications/resources/updated`,{payload:{...n7.fields,uri:H}})){},L7=class extends (/*#__PURE__*/ sP(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ BS(n7)})){},R7=class extends (/*#__PURE__*/ sP(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ BS(n7)})){},z7=class extends (/*#__PURE__*/ sP(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ BS(n7)})){},B7=class extends (/*#__PURE__*/ sP(`notifications/subscriptions/acknowledged`,{payload:{...n7.fields,notifications:N7}})){},V7=class extends (/*#__PURE__*/ wP(obe,gbe,dbe,ube,sbe,cbe,lbe,_be,pbe,fbe)){},H7=class extends (/*#__PURE__*/ wP(F7)){},bbe=class extends (/*#__PURE__*/ V7.merge(H7)){},xbe=class extends (/*#__PURE__*/ wP()){},Sbe=class extends (/*#__PURE__*/ wP(F7,vbe,ybe,I7,L7,R7,z7,B7)){};const Cbe=/*#__PURE__*/ MS(H,K),wbe=/*#__PURE__*/ sS(e7),Tbe=/*#__PURE__*/ sS(F7.payloadSchema),Ebe=/*#__PURE__*/ oS(ZC),U7=/*#__PURE__*/ dS($5),W7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},Dbe=(e,t)=>{if(Gt(t))return e===void 0;if(e===void 0)return!1;let n=z8(e);return n!==void 0&&wO(t).pipe(TO(kO,e=>n===e),TO(jO,e=>n===String(e)),TO(AO,e=>Number.isSafeInteger(e)&&n.trim().length>0&&Number(n)===e),MO(()=>!1))},Obe=/*#__PURE__*/ B(function*(e){let t=yield*wbe(e);return{protocolVersion:q5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),G7=(e,t)=>{let n=e._meta;return{...Yt(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},K7=(e,t)=>W7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),q7=/*#__PURE__*/ sS(/*#__PURE__*/ G([j7,y7])),J7=/*#__PURE__*/ B(function*(e,t){let n=yield*U7(t);return e._tag===`Complete`?yield*q7({...W7(e.value),_meta:G7(e.value,n),resultType:`complete`}):yield*q7(K7(e,n))}),kbe=(e,t)=>{let n={};for(let r of Object.values(e??{}))wO(r).pipe(TO({method:`roots/list`},()=>{t.roots===void 0&&(n.roots={})}),TO({method:`sampling/createMessage`},e=>{let r=n.sampling??{};zve(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)}),TO({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]={})}),NO);return n},Y7=e=>W7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:qh(e.blob)}}),X7=/*#__PURE__*/ CO().pipe(/*#__PURE__*/ TO({type:/*#__PURE__*/ OO(`text`,`resource_link`)},e=>e),/*#__PURE__*/ TO({type:/*#__PURE__*/ OO(`image`,`audio`)},e=>W7({type:e.type,mimeType:e.mimeType,data:qh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ TO({type:`resource`},e=>W7({type:`resource`,resource:Y7(e.resource),annotations:e.annotations,_meta:e._meta})),NO),Abe=e=>o7.make(e),jbe=e=>s7.make(e),Mbe=e=>W8(vve,f7,e),Nbe=e=>W8(D8,p7,e),Z7={ttlMs:0,cacheScope:`private`},Q7=/*#__PURE__*/ B(function*(e,t){let n=yield*U7(t);return{...W7(e),_meta:G7(e,n),resultType:`complete`}}),Pbe=/*#__PURE__*/ CO().pipe(/*#__PURE__*/ EO(`ResourceNotFound`,e=>new U8({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ EO(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,U8.fromTool),/*#__PURE__*/ MO(U8.fromFeature)),$7=e=>{let t=Pbe(e);return a7.make({code:t.code,message:t.message,...Ebe(t.data)?{data:t.data}:{}})},e9=/*#__PURE__*/ B(function*(e,t){let n=yield*om(DN);return Ai(n)&&FN(n.value,(t,n)=>N(gM(n,e))),yield*t}),Fbe=e=>Tbe(e).pipe(z(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),t9=e=>new Ove({operation:e,protocolVersion:q5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),Ibe=/* @__PURE__ */ Hve({protocolVersion:q5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:Obe},clientRpcs:bbe,clientNotificationRpcs:H7,serverRequestRpcs:xbe,serverNotificationRpcs:Sbe,handlerRpcs:/* @__PURE__ */ V7.merge(H7),makeHandlers:(e,t,n)=>{let r=sS(Cbe),i=sS(w7),a=sS(T7),o=sS(E7),s=sS(D7),c=sS(O7),l=sS(k7),u=sS(G([k7,y7])),d=sS(M7),f=sS(A7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:Ia(n.serverInfo.extensions,e=>Yt(e)),g=z(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}}),_=M8.useSync(V8),v=B(function*(e){let t=yield*M8,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(Up);return V8(M8.of({...t,inputResponses:n,requestState:e.requestState}))}),y=B(function*(e,t){let n=kbe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*e9(400,new U8({code:-32021,message:`The request requires client capabilities that were not declared`,data:{requiredCapabilities:n}}))});return{"subscriptions/listen":B(function*(e,{client:t,requestId:r}){if(p===void 0)return yield*new U8({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*bf(yield*lm),o=yield*_f(n.subscribeServerNotifications,a),s={...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}:{}},c={"io.modelcontextprotocol/subscriptionId":r},l=new Set(s.resourceSubscriptions),u=yield*eT(64),d=yield*tf();yield*I(function*(){for(;;){let e=yield*Nw(o);if(e.targetClientId!==void 0&&e.targetClientId!==t.id)continue;let n=e.notification,r=wO(n).pipe(DO({ToolsChanged:()=>s.toolsListChanged===!0?R7:void 0,PromptsChanged:()=>s.promptsListChanged===!0?z7:void 0,ResourcesChanged:()=>s.resourcesListChanged===!0?L7:void 0,ResourceUpdated:e=>l.has(e.uri)?I7:void 0}),NO);if(r===void 0)continue;let i={tag:r._tag,payload:r.payloadSchema.make({_meta:{...n.metadata,...c},...n._tag===`ResourceUpdated`?{uri:n.uri}:{}})};if(!(yield*tT(u,i)))break}}).pipe(wf(a),jp(Sp(()=>n.markSubscriptionCancelled?.(t.id,r)??F)),jp(lf(d,void 0)),Nm),yield*p(q5,t.id,{tag:B7._tag,payload:B7.payloadSchema.make({_meta:c,notifications:s})});let f=Tm(mT(u).pipe(R(e=>p(q5,t.id,e))));yield*pre(f,nf(d)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??F;let m=yield*U7(n.serverInfo);return P7.make({_meta:{...c,"io.modelcontextprotocol/serverInfo":m},resultType:`complete`})},Hp($7)),"server/discover":B(function*(e){let t=yield*g,r=yield*Q7({...Z7,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},Hp($7)),"resources/list":B(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*Q7({...Z7,resources:i.map(Abe)},n.serverInfo);return yield*a(o)},Hp($7)),"resources/templates/list":B(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*Q7({...Z7,resourceTemplates:i.map(jbe)},n.serverInfo);return yield*o(a)},Hp($7)),"resources/read":B(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map(Y7),o=yield*Q7({...Z7,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},Hp($7)),"prompts/list":B(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*e9(404,new U8({code:c8,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*_p(i,Mbe),o=yield*Q7({...Z7,prompts:a},n.serverInfo);return yield*c(o)},Hp($7)),"prompts/get":B(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*U7(n.serverInfo);return yield*u(K7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:X7(e.content)})),s=yield*Q7({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},Hp($7)),"completion/complete":B(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*Q7({completion:W7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},Hp($7)),"tools/list":B(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*_p(i,Nbe),o=yield*Q7({...Z7,tools:a},n.serverInfo);return yield*f(o)},Hp($7)),"tools/call":B(function*(t){let r=yield*v(t),i=(yield*e.tools.list(r.protocol)).find(e=>e.name===t.name),a=yield*om(DN);if(i!==void 0&&Ai(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!Yt(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!Dbe(a.value.headers[e],n))return yield*e9(400,new U8({code:d8,message:`${e} does not match argument '${r}'`}))}if(Yt(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:Yt(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(Rp([`ToolExecutionError`,`InvalidToolInput`],e=>N(I8.Complete(O8.make({content:[C8.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*J7(o,n.serverInfo);let s=o.value,c=s.content.map(X7);return yield*J7(I8.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},Hp($7)),"notifications/cancelled":B(function*(e){return yield*F})}},toReverseClient:()=>({listRoots:()=>L(t9(`roots/list`)),createMessage:()=>L(t9(`sampling/createMessage`)),elicit:()=>L(t9(`elicitation/create`))}),projectNotification:e=>G8(e)?N(void 0):Vve({supportsProgressMessage:!0},e),normalizeCancellation:Fbe}),n9=/*#__PURE__*/ new WeakMap,Lbe=/*#__PURE__*/ kve.omit(`notifications/elicitation/complete`),r9=/*#__PURE__*/ oS(A8),Rbe=e=>{switch(e.tag){case`notifications/cancelled`:return L8.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return L8.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 L8.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return L8.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return L8.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return L8.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return L8.PromptsChanged({metadata:e.payload?._meta});default:return}},i9=(e,t)=>{let n=cm(e,M8,t.requestContext),r=t.requestContext.requestMetadata,i=A(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return r9(i)&&(n=cm(n,ff,R8[i].effect)),t.serverClient===void 0?n:cm(n,N8,t.serverClient)};var a9=class e extends (/*#__PURE__*/ j()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ I(function*(){let t=yield*Ive,n=Ka(),r=[],i=[],a=[],o=yield*Qw(),s={consumers:0},c=/* @__PURE__ */ new Set,l=(yield*Eo).makeDispatcher(),u=yield*vP(Lbe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>tf().pipe(R(t=>kp(n=>{let r=e.message;if(r._tag!==`Request`)return F;let i=Rbe(r);if(i===void 0)return F;let a={notification:i,delivered:t,requestContext:oa(n.context,M8),requestHeaders:oa(n.context,DN)?.headers},d=!1;if(r.tag.includes(`list_changed`)){if(!c.has(r.tag)){d=!0;let e=r.tag;l.scheduleTask(()=>{nT(o,a),c.delete(r.tag)},0),c.add(e)}}else d=!0,nT(o,a);let f=Sp(()=>u.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Gd}));return d&&a.requestContext!==void 0&&s.consumers>0?jp(nf(t),f):f})))}),d=e.of({notifications:u.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>tf().pipe(R(n=>tT(o,{notification:L8.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(jp(Sp(()=>s.consumers>0?nf(n):F))))),get tools(){return n},addTool:e=>I(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,F8);yield*t.tools.register({descriptor:new D8({...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)=>i9(e.handle(t.arguments),n).pipe(cre({InternalError:t=>L(new Pve({name:e.tool.name,message:t.message})),InvalidParams:t=>L(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?Mve:Nve)({name:e.tool.name,message:t.message}))}),z(e=>Zt(e,`InputRequired`)?I8.InputRequired(e):I8.Complete(e)))}),yield*u.client[`notifications/tools/list_changed`]({})}),callTool:e=>I(function*(){let n=yield*N8,r=yield*t.tools.call(e,B8(n)).pipe(Hp(e=>new h8({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new h8({message:`Client input is not supported by this MCP protocol`}):r.value}),get resources(){return r},get resourceTemplates(){return i},addResource:e=>I(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,F8);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>i9(e.handle,t)}),yield*u.client[`notifications/resources/list_changed`]({})}),addResourceTemplate:({annotations:e,completions:n,handle:r,routerPath:a,template:o})=>I(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=qbe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=oa(e,F8);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)=>i9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>i9(r(e.argument.value,e.context),t).pipe(z(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*u.client[`notifications/resources/list_changed`]({})}),findResource:e=>I(function*(){let n=yield*N8;return yield*t.resources.read(e,B8(n)).pipe(Rp(`ResourceNotFound`,e=>L(new h8({message:`Resource '${e.uri}' not found`}))))}),get prompts(){return a},addPrompt:e=>I(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,F8);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>i9(e.handle(t),n).pipe(z(e=>Zt(e,`InputRequired`)?I8.InputRequired(e):I8.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>i9(r(e.argument.value,e.context),t).pipe(z(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*u.client[`notifications/prompts/list_changed`]({})}),getPromptResult:B(function*({arguments:e,name:n}){let r=yield*N8,i=yield*t.prompts.get(n,e??{},B8(r)).pipe(Rp(`PromptNotFound`,()=>new h8({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new h8({message:`Client input is not supported by this MCP protocol`})}),completion:B(function*(e){let n=yield*N8,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},B8(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return n9.set(d,{core:t,notifications:o,notificationDelivery:s}),d});static layer=/*#__PURE__*/ Hf(e)(e.make)};const o9=`mcp-session-id`,s9=/*#__PURE__*/ new WeakMap,c9=e=>`${typeof e}:${e}`;var l9=class extends Fo{};const zbe=/*#__PURE__*/ B(function*(e,t,n){let r=yield*SP,i=yield*a9,a=yield*ff,o=n===`http`,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=e=>{c.delete(e),s.delete(e),t.disconnect(e)},d=(e,t,n)=>r.send(e,{_tag:`Exit`,requestId:t,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:n}]}}),f=(e,t)=>{let n=l.get(e);if(n===void 0)return;let r=n.filter(e=>e!==t);r.length===0?l.delete(e):l.set(e,r)},p=yield*Ow(),m=(e,n,i)=>Sp(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(i.tag);return o===void 0?Dp(`MCP protocol ${e} does not define server notification ${i.tag}`):a.payloadCodecs(o).encode(i.payload).pipe(Up,R(e=>r.send(n,{_tag:`Request`,id:``,tag:i.tag,payload:e,headers:[],isNotification:!0})))}),h=(e,t)=>{let n=c.get(e),r=c9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},g=(e,t,n,i)=>Sp(()=>h(t,n)?o?r.end(t):m(e,t,{tag:`notifications/cancelled`,payload:{requestId:n,reason:i}}):F),_,v=yield*t.installHandlers({core:n9.get(i).core,subscribeServerNotifications:jw(p),...r.supportsNotifications?{sendNotification:m,markSubscriptionCancelled:(e,t)=>P(()=>{h(e,t)}),terminateSubscription:g}:{},defaultLogLevel:a,serverInfo:e}),y=yield*noe({lookup:B(function*(e){let n=t.selectProtocol(e.profile.protocolVersion),i,a=yield*bP.make(B(function*(t){let n=0;return i=e=>t(n,e),{send(t,i,a){if(n=t,i._tag===`Request`){let t=c9(i.id),n=l.get(t)??[];return n.push(e),l.set(t,n),r.send(e.clientId,{_tag:`Request`,id:i.id,tag:i.tag,payload:i.payload,headers:[]}).pipe(hm(()=>P(()=>f(t,e))))}return i._tag===`Interrupt`&&f(c9(i.requestId),e),r.send(e.clientId,i)},supportsAck:!0,supportsTransferables:!1,supportsStructuredClone:!1,codecFor:r.codecFor}}));return{client:yield*n.makeReverseClient(e.profile).pipe(cm(bP,a)),write:i}}),idleTimeToLive:1e4}),b=P8.of((e,{client:n,headers:r,payload:i,rpc:o})=>{let c=t.resolveRequest(n.id,r);if(!o._tag.endsWith(`/initialize`)&&!c){let e=aw(),t=oa(e.context,DN);return t&&FN(t,()=>N(eM({status:r[o9]===void 0?400:404}))),Dp(/* @__PURE__ */ Error(`Mcp-Session-Id does not exist`))}let l=c?.initializePayload??i,u=s.get(n.id),d=c?.protocol??u?.protocol??t.protocolForInternalTag(o._tag);if(!Jbe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return Dp(`Unsupported selected MCP protocol version: ${d.protocolVersion}`);let f=c?.negotiatedProfile??{protocolVersion:d.protocolVersion,clientCapabilities:l.capabilities,clientInfo:l.clientInfo};u!==void 0&&(u.profile=f);let p=M8.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return cm(cm(cm(e,N8,N8.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:Yt(i)&&Yt(i._meta)?i._meta:void 0,getClient:NE(y,new l9({clientId:n.id,profile:f})).pipe(z(({client:e})=>e))})),M8,p),ff,t.effectLogLevel(n.id,r,a))}),x=SP.of({...r,send:(e,t)=>{if(t._tag===`Exit`){let i=c.get(e),a=c9(t.requestId),o=i?.get(a)?.cancelled;if(i!==void 0&&i.delete(a)&&i.size===0&&c.delete(e),o===!0)return n===`custom`?F:(s9.set(t,t.requestId),r.send(e,t));if(t.exit._tag===`Failure`&&!t.exit.cause.some(e=>e._tag===`Fail`))return r.send(e,{_tag:`Exit`,requestId:t.requestId,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:new g8({message:`Internal error`})}]}})}return r.send(e,t)},run:e=>(_=e,r.run((n,r)=>{let i=aw(),a=r,p=o?oa(i.context,DN):void 0;switch(p!==void 0&&a._tag!==`Eof`&&FN(p,(e,t)=>N(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?eM({headers:Yg(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{let r=o?ca(aw().context,DN).headers:Wg(a.headers),l=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`)?c.get(n)?.get(c9(a.payload.requestId)):void 0,f=l===void 0?t.prepareRequest(n,r,a):N(l.prepared);return I(function*(){let l=yield*f,m=s.get(n);o&&m===void 0&&(yield*yf(ca(i.context,mf),P(()=>u(n))));let g=l.binding,_=l.protocol;if(s.set(n,{protocol:_,profile:l.profile??m?.profile,sessionHeaders:o&&r[o9]!==void 0?Wg({[o9]:r[o9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*d(n,a.id,new p8({message:`JSON-RPC batches are not supported`}));p!==void 0&&g!==void 0&&FN(p,(e,i)=>N(t.resolveRequest(n,r)===void 0?eM({status:404}):uM(i,`mcp-protocol-version`,g.protocol.protocolVersion)));let y=t.routeClientRequest(_,a),b=t.clientRpcs.requests.get(y.tag),x=_.clientNotificationRpcs.requests.has(a.tag);if(b&&x&&a.isNotification){if(!g&&_.runtime._tag===`Stateful`){p&&FN(p,()=>N(eM({status:r[o9]===void 0?400:404})));return}let t=_.payloadCodecs(b).decode(a.payload);return yield*I(function*(){let i=yield*t;if(a.tag===`notifications/cancelled`){let t=yield*_.normalizeCancellation(i),r=c9(t.requestId),a=n;if(o){if(g===void 0)return;let e=Array.from(c).find(([,e])=>e.get(r)?.prepared.binding===g);if(e===void 0)return;a=e[0]}return h(a,t.requestId)?yield*e(a,{_tag:`Interrupt`,requestId:t.requestId}):void 0}let s=v.mapUnsafe.get(b.key),u=s?s.handler(i,{rpc:b,requestId:dP(a.id),client:new aP(n),headers:r}):F;return yield*l.requestContext===void 0?u:cm(u,M8,l.requestContext)}).pipe(qp)}if(!b||x)return a.isNotification?void 0:yield*d(n,a.id,new m8({message:`Method not found: ${a.tag}`}));let S=yield*Np(_.payloadCodecs(b).decode(a.payload));if(wa(S))return yield*a.isNotification?F:d(n,a.id,new h8({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=c.get(n)??/* @__PURE__ */ new Map;e.set(c9(a.id),{requestId:dP(a.id),prepared:l,cancelled:!1}),c.set(n,e)}let C=e(n,y);return yield*l.requestContext===void 0?C:cm(C,M8,l.requestContext)}).pipe(Lp(e=>a.isNotification?F:d(n,a.id,Zt(e,`ProtocolError`)?U8.fromFeature(e):new h8({message:`Invalid request metadata`}))))}case`Ping`:case`Ack`:case`Interrupt`:return e(n,a);case`Eof`:return o||u(n),e(n,a);case`Pong`:case`Exit`:case`Chunk`:case`ClientProtocolError`:case`Defect`:{let e=a._tag===`Exit`?c9(a.requestId):void 0,r=o?t.resolveRequest(n,ca(aw().context,DN).headers):void 0,i=(e===void 0?void 0:l.get(e))?.find(e=>o?e.profile===r?.negotiatedProfile:e.clientId===n);if(a._tag===`Exit`&&i===void 0)return F;i!==void 0&&e!==void 0&&f(e,i);let c=i?.clientId??n,u=s.get(c),d=u?.protocol??t.protocols[0],p=i?.profile??u?.profile??{protocolVersion:d.protocolVersion,clientCapabilities:{},clientInfo:{name:`unknown`,version:`unknown`}};return NE(y,new l9({clientId:c,profile:p})).pipe(R(({write:e})=>e(a)),um)}}}))});o&&(yield*t.onSessionTerminated(e=>{let t=[];for(let[n,r]of c)for(let{prepared:i,requestId:a}of r.values())i.binding===e&&h(n,a)&&t.push(_(n,{_tag:`Interrupt`,requestId:a}));return gp(t,{discard:!0})}));let{notificationDelivery:S,notifications:C}=n9.get(i);yield*fm(P(()=>{S.consumers++}),()=>P(()=>{S.consumers--}));let w=/* @__PURE__ */ new Map;return yield*mT(C).pipe(R(B(function*(e){let{delivered:n,notification:r,targetClientId:i,requestContext:c,requestHeaders:l}=e;G8(r)&&(yield*Aw(p,{notification:r,targetClientId:i}));let u=yield*x.clientIds;for(let e of s.keys())u.has(e)||(s.delete(e),t.disconnect(e));let d=r._tag===`LoggingMessage`||r._tag===`Progress`,f=d&&c!==void 0?[c.clientId]:i===void 0?o?s.keys():t.deliveryClientIds():[i],m=[],h=!1;for(let e of f){if(i!==void 0&&e!==i)continue;if(!u.has(e)){t.disconnect(e);continue}if(!x.supportsNotifications)continue;let o=d&&c!==void 0?t.selectProtocol(c.protocolVersion):s.get(e)?.protocol;if(!o)continue;let f=w.get(e),p=e===(i??c?.clientId);h||=p;let g=p?n:ef();w.set(e,g);let _=I(function*(){f!==void 0&&(yield*nf(f));let n=yield*o.projectNotification(r);if(n===void 0||r._tag===`Progress`&&o.runtime._tag===`Stateless`&&c?.requestMetadata?.progressToken!==r.progressToken)return;if(r._tag===`LoggingMessage`&&o.runtime._tag===`Stateless`){let t=c?.requestMetadata,n=A(t,`io.modelcontextprotocol/logLevel`)?t[`io.modelcontextprotocol/logLevel`]:void 0;if(c?.clientId!==e||!r9(n)||A8.literals.indexOf(r.level)<A8.literals.indexOf(n))return}else if(!t.canDeliver(e,(c?.clientId===e?l:void 0)??s.get(e)?.sessionHeaders??Ug,r,a))return;let i=o.serverNotificationRpcs.requests.get(n.tag);if(!i)return;let u=yield*o.payloadCodecs(i).encode(n.payload);yield*x.send(e,{_tag:`Request`,id:``,tag:n.tag,payload:u,headers:[],isNotification:!0})}).pipe(qp,mm(P(()=>{uf(g,Gd),w.get(e)===g&&w.delete(e)})));m.push(_)}h||(yield*lf(n,void 0)),yield*gp(m,{concurrency:`unbounded`,discard:!0}).pipe(Nm({startImmediately:!0}))})),qp,Tm,Nm),yield*sce(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(cm(SP,x),cm(P8,b),nm(v))},um),Bbe=(e,t)=>Gf(I(function*(){let n=yield*r5;yield*Nm(zbe(e,n,t))})).pipe(Qf(a9.layer)),Vbe=e=>{let t=Jve(e.protocols);return Bbe(e,`http`).pipe(Zf(Hbe(e)),Zf(t),Zf(Zse()))},Hbe=e=>Hf(SP)(I(function*(){let t=yield*r5,{httpEffect:n,protocol:r}=yield*cce().pipe(cm(pP,Ube)),i=yield*LN,a=e.allowSessionTermination===!0&&t.protocols.some(e=>e.runtime._tag===`Stateful`),o=N(eM({status:403})),s=t=>n=>d9(n,e.allowedOrigins)?t(n):o,c=N(eM({status:405,headers:{allow:a?`POST, DELETE`:`POST`}})),l=s(()=>c);for(let t of[`GET`,`PUT`,`PATCH`,`OPTIONS`])yield*i.add(t,e.path,l);return yield*i.add(`DELETE`,e.path,a?s(e=>t.terminateHttpSession(e.headers)):l),yield*i.add(`POST`,e.path,r=>{if(!d9(r,e.allowedOrigins))return N(eM({status:403}));if(f9(r.headers[`content-type`])[0]!==`application/json`)return N(eM({status:415}));let i=f9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?N(eM({status:406})):I(function*(){let e=yield*Np(R(r.text,cS(TC))),i=t.admitHttp(r.headers,e);if(i._tag===`Rejected`)return i.response;let a=z(n,e=>{let t=e.body._tag===`Uint8Array`&&e.body.body.subarray(0,-1).includes(10);return i.isSubscription||e.body._tag===`Stream`||t?Kbe(e,i.isSubscription):e});return yield*i.acknowledge?zp(a,()=>N(eM({status:202}))):a})}),r})),Ube=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Gbe();return pP.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}}}})})(),Wbe=/*#__PURE__*/ oS(/*#__PURE__*/ XS(`Cause`,{data:/*#__PURE__*/ FS([/*#__PURE__*/ XS(`Fail`,{error:/*#__PURE__*/ yS(_8)})])})),u9=e=>Array.isArray(e)?e.map(u9):!Yt(e)||!A(e,`error`)?e:Wbe(e.error)?{...e,error:e.error.data[0].error}:e;function Gbe(e){let t=mP(e);return pP.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(Yt(t)){let e=s9.get(t);e!==void 0&&(s9.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=>!(Yt(e)&&!A(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(u9(i))}}}})}const Kbe=(e,t)=>{let n=new TextEncoder,r=new TextDecoder,i=e=>n.encode(r.decode(e).trimEnd().split(`
|
|
532
|
+
`).map(e=>`data: ${e}\n\n`).join(``)),a={status:e.status,statusText:e.statusText,headers:Yg(e.headers,`content-type`),cookies:e.cookies,contentType:`text/event-stream`};if(e.body._tag===`Stream`){let r=e.body.stream.pipe(XE(i));if(!t)return lM(r,a);let o=foe(`15 seconds`).pipe(Eoe(1),XE(()=>n.encode(`: keepalive
|
|
533
533
|
|
|
534
|
-
`)));return uM($E(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?rM(i(e.body.body),a):dM(e,`content-type`,`text/event-stream`)},d9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},f9=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()]}),Jbe=()=>{let e=Wj({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},Ybe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,Xbe=Lbe,Zbe=cS(TY),Qbe=cS(W(TY)),p9=e=>sy(e)?p9(e.thunk()):e,m9=e=>DY(p9(e)),h9=e=>{let t=p9(e),n=DY(t);if(n!==void 0)return{kind:n,many:!1};if(!iy(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(m9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},$be=e=>{let t=e.context?.isOptional===!0,n=p9(e);if(t&&oy(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!vre(e)),r=e===void 0||t.length>0?void 0:m9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=h9(n);return r===void 0||t&&r.many?void 0:r},exe=e=>{let t=p9(e.ast),n=h9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!ay(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=$be(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:gS(new Py(a,t.indexSignatures,s))}},txe=e=>[...ey(e)?e.typeParameters:[],...iy(e)?[...e.elements,...e.rest]:[],...ay(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...oy(e)?e.types:[],...sy(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],nxe=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),EY(e))return!0;n.push(...txe(e))}return!1},rxe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>nxe(e)),ixe=(e,t)=>e.fields.flatMap(({name:e,kind:n,many:r})=>{let i=e===void 0?t:A(t,e)?t[e]:void 0;return(r?Qbe(i)?i:[]:Zbe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),g9=(e,t,n)=>n===void 0?e:e.annotate(t,n),axe=(e,{readOnly:t,mcp:n})=>{let r=n.destructiveHint??(!t&&void 0),i=n._meta===void 0?void 0:{...n._meta},a=g9(g9(g9(e.annotate(U6,t),W6,r),G6,n.idempotentHint),K6,n.openWorldHint);return g9(g9(a,V6,n.title),H6,i)},oxe=e=>X_e(e.name,{description:e.description,parameters:YC(e.input),success:YC(e.success),failure:YC(G(rY(e))),failureMode:`return`}),sxe=(e,t)=>{cY(t.label,e.flatMap(e=>e.actions));let n=ave(...e.flatMap(e=>e.actions.map(n=>axe(t.tool(oxe(n),n,e),n))));return{toolkit:n,layer:n.toLayer(z(SY(e),e=>Object.fromEntries(e.map(([e,n])=>[e.name,t.handler?.(n,e)??n]))))}},_9={label:`MCP tool`,tool:e=>e.annotate(q6,!0)},cxe=cS(T8),v9=(e,t)=>{let n=vae(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=It(n.schema.$ref)?Sx(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}},lxe=e=>{let t=e.map(([e])=>e).filter(e=>!cxe(v9(YC(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])=>rxe(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(`, `)}`)},uxe=e=>new O8({isError:!0,content:[{type:`text`,text:e}]}),y9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],dxe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),fxe=e=>q_e(e)&&Zt(e.reason,`ToolParameterValidationError`)?e.reason:void 0,b9=va(M8,N8,DN,ff),pxe=B(function*(e,t){let n=yield*a9,r=yield*e.pipe(cm(t=>ga(t,_a(...Object.values(e.tools).flatMap(e=>{let n=j(e.id);return Ree(ha(t,n)).map(e=>ia(n,{...e,context:b9(e.context)}))}))))),i=b9(yield*tm()),a=e=>{let t=Cd(e);return Ea(t)&&!Td(e)?Tp(t.failure):Wm(e).pipe(jp(im(rO(e),i)),Fp(uxe(`Tool execution failed due to an internal server error.`)))},o=e=>{let t=Cd(e);if(Da(t)){let{error:e}=t.success,n=da(Ld(t.success),Y6)===`parameters`?fxe(e):void 0;if(n!==void 0)return L(new h8({message:n.message}))}return a(e)},s=yield*_p(Object.entries(r.tools),([e,n])=>I(function*(){let a=Q_e(n)===!0,s={onExcessProperty:a?`error`:`ignore`,errors:`all`},c=t.get(e),l=c===void 0||c.fields.length===0?void 0:c,u=l===void 0?n.successSchema:l.rest===void 0?void 0:YC(l.rest),d=u===void 0?void 0:yield*lS(E8)(v9(u,!1)).pipe(Up),f=yield*lS(T8)(v9(n.parametersSchema,a)).pipe(Up),p=new Set(l?.fields.map(({name:e})=>e)),m=({encodedResult:e,result:t})=>{if(l===void 0)return new O8({isError:!1,structuredContent:e,content:y9(e)});let n=ixe(l,t).map(dxe);if(u===void 0)return new O8({isError:!1,content:n});let r=Jt(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!p.has(e))):e;return new O8({isError:!1,structuredContent:r,content:[...y9(r),...n]})};return{tool:new D8({name:e,description:Z_e(n),inputSchema:f,outputSchema:d,annotations:{...ha(n.annotations,V6).pipe(zi(e=>({title:e})),Li),readOnlyHint:da(n.annotations,U6),destructiveHint:da(n.annotations,W6),idempotentHint:da(n.annotations,G6),openWorldHint:da(n.annotations,K6)},_meta:ca(n.annotations,H6)}),annotations:n.annotations,handle:t=>r.handle(e,t??{},void 0,s).pipe(XE,Noe,R(are),R(e=>e.isFailure?e.failureOrigin===`handler`?N(new O8({isError:!0,content:y9(e.encodedResult)})):Tp(Id(hd(e.result),ia(Y6,e.failureOrigin??`result`))):N(m(e))),zp(o),im(i))}}));for(let e of s)yield*n.addTool(e)}),mxe=(e,t,n=Vf,r)=>{let i=sxe(e,r===void 0?_9:{..._9,handler:(e,t)=>n=>t.caller===iY?e(n):g$(RY(r,e(n)))}),a=e.flatMap(e=>e.actions.map(e=>[e,exe(e.success)]));lxe(a);let o=new Map(a.map(([{name:e},t])=>[e,t])),s=I(function*(){let e=yield*a9,t=e.tools.flatMap(({tool:e})=>o.has(e.name)?[e.name]:[]);if(t.length>0)return yield*Dp(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature`));let n=yield*Lf(i.layer);yield*pxe(i.toolkit,o).pipe(am(aa(n,a9,e)))});return Gf(s).pipe(Zf(n),Zf(t),Hne,xY(e))},hxe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),gxe=e=>{let t=new Set(e.filter(({caller:e})=>e===iY).map(({name:e})=>e));return e=>{if(t.size===0)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(hxe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}};function _xe(e,{actions:t,features:n,path:r,authentication:i,...a}){let o=bY(vY(e),t),s=o.flatMap(e=>e.actions);LY(s,i);let c=mxe(o,Hbe({...a,path:r??`/mcp`,protocols:[Xbe]}),n,i);if(i===void 0)return c;let l=gxe(s),u=KN(z(i[`~provider`],e=>t=>R(DN,n=>e.http(t,!l(n.headers)))));return c.pipe(Zf(u.layer))}var vxe=`0.16.0`,x9=class extends Vo(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},S9=class extends JC()(`ProviderUnavailable`,{operation:H},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},C9=class extends Vo(`InsufficientScope`){},yxe=class extends JC()(`ConfigurationError`,{message:H}){};const w9=`key-list+jwt`,bxe=U({keys:W(U({id:H,sealed:H}))}),T9=TC(U({keyId:yC,ownerId:yC,scopes:W(yC),expiresAt:VS(iC)})),E9=new TextEncoder,xxe=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,E9.encode(e))),D9=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:E9.encode(`clankerauth key list\0${t}`)},n,512));return{id:cR(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},Sxe=async(e,t,n)=>{let{id:r,key:i}=await D9(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,E9.encode(hS(T9)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:cR(s)}},Cxe=async(e,t,n)=>{let r=await D9(await xxe(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(sR(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return dS(T9)(new TextDecoder().decode(o))},O9=yo(1),k9=(e,t)=>nm(n=>cj(e).execute(t).pipe(lm(LP,{...ca(n,LP),redirect:`error`}),Hp(e=>new S9({operation:`http.request`,cause:e})))),wxe=U({keys:W(U({kty:H,crv:vS(H),x:vS(H),kid:vS(H),alg:vS(H),use:vS(H),key_ops:vS(W(H))}))}),Txe=U({sub:yC,client_id:yC,scope:H,iat:iC,exp:iC}),Exe=U({list:H}),Dxe=bxe.pipe(NS({exp:iC})),A9=e=>new x9({cause:e}),j9=vo(5),M9=V(`Verifier.make`)(function*(e){let t=yield*tj,n=yield*Op({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new yxe({message:`Invalid issuer URL`})}),r=V(`Verifier.jwks`)(function*(){let e=yield*k9(t,CA(n.jwks));return e.status===200?UB({keys:(yield*RA(wxe)(e).pipe(Hp(e=>new S9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t)}):yield*new S9({operation:`jwks.fetch`,cause:{status:e.status}})},dm),i=yield*bm(r(),e=>Kd(e)?`1 minute`:j9),a=V(`Verifier.signingKey`)(function*(e){let t=yield*i;return yield*bp({try:()=>t({alg:`EdDSA`,kid:e}),catch:A9})}),o=V(`Verifier.signed`)(function*(t,n){let r=yield*Op({try:()=>$B(t),catch:A9});if(r.alg!==`EdDSA`||r.kid===void 0)return yield*A9();let i=yield*a(r.kid),o=yield*ep,{payload:s}=yield*bp({try:()=>OB(t,i,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(o)}),catch:A9});return s}),s=V(`Verifier.jwt`)(function*(e){let t=yield*o(e,`at+jwt`);if(t.cnf!==void 0)return yield*A9();let n=yield*lS(Txe)(t).pipe(Hp(A9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),c=V(`Verifier.keyList`)(function*(){let r=wA(n.keyList).pipe(FA({resource:e.resource})),i=yield*k9(t,r);if(i.status!==200)return yield*new S9({operation:`key-list.fetch`,cause:{status:i.status}});let{list:a}=yield*RA(Exe)(i).pipe(Hp(e=>new S9({operation:`key-list.decode`,cause:e}))),s=e=>new S9({operation:`key-list.verify`,cause:e}),c=yield*o(a,w9).pipe(Rp(`Unauthorized`,e=>L(s(e)))),l=yield*lS(Dxe)(c).pipe(Hp(s));return{readAt:yield*ep,expiresAt:l.exp*1e3,entries:new Map(l.keys.map(e=>[e.id,e.sealed]))}},dm),l=yield*LO(!1),u=yield*bm(c().pipe(Jp({duration:`3 seconds`,orElse:()=>L(new S9({operation:`key-list.timeout`}))}),Wp(({operation:e})=>R(BO(l,!0),t=>t?F:Um(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:e}))),Mp(()=>R(BO(l,!1),e=>e?Gm(`clankerauth key list reads have recovered`):F))),j9),d=yield*LO(void 0),f=I(function*(){let e=yield*Np(u);Da(e)&&(yield*zO(d,e.success));let t=yield*RO(d);return t!==void 0&&t.expiresAt>(yield*ep)?t:yield*Ea(e)?e.failure:new S9({operation:`key-list.expired`})}),p=V(`Verifier.apiKey`)(function*(t){let n=n=>bp({try:()=>Cxe(t,e.resource,n.entries),catch:A9}),r=yield*ep,i=yield*RO(d),a=i!==void 0&&r-i.readAt<bo(O9)&&i.expiresAt>r?i:yield*f,o=(yield*n(a))??(yield*R(f,e=>e===a?N(void 0):n(e)));return o===void 0||o.expiresAt!==null&&o.expiresAt<=(yield*ep)?yield*A9():{subject:o.ownerId,scopes:o.scopes,actor:{kind:`key`,keyId:o.keyId},expiresAt:o.expiresAt??void 0}});return{verifyToken:V(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?L(A9()):p(t):s(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new C9({scope:r,actor:n.actor})})}}),Oxe=V(`AdministrationResource.make`)(function*(){let e=yield*w6,t=`${e.settings.baseURL}/api/auth`,n=b1(e.settings.baseURL);return{protectedResource:{resource:n,authorizationServers:[t],scopesSupported:[y1.read,y1.write,`offline_access`],scopesRequired:[y1.read,y1.write]},verifier:yield*M9({issuer:t,resource:n,apiKeys:!1}).pipe(rm(RP.pipe(Zf(zf(IP,(t,n)=>{let r=new Request(t,n);return r.headers.set(`x-clankerauth-peer`,`127.0.0.1`),e.auth.handler(r)})))))}}),kxe=lS(X$),Axe=lS(U({id:H,key:H,referenceId:H,expiresAt:VS(RC),permissions:VS(TC(X$))})),N9=B(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*kxe(e.permissions??{}).pipe(Lp(()=>Fp(Um(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?Hh(e.expiresAt):null,createdAt:Hh(e.createdAt)}}),P9=z(w6,e=>{let t=V(`MachineKeys.validate`)(function*(t){if(t!==void 0)for(let[n,r]of Object.entries(t)){if(n===b1(e.settings.baseURL))return yield*c1([`permissions`,n],`Administration requires OAuth access tokens, not API keys`);let t=yield*e.resources.get(n);if(!t||r.some(e=>!t.scopes.includes(e)))return yield*c1([`permissions`,n],`Select explicitly granted, currently available Resource scopes`)}});return{list:V(`MachineKeys.list`)(function*(){let{providerHeaders:t}=yield*z$,n=yield*t,r=yield*l1(()=>e.auth.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*_p(r.apiKeys,N9)}}),create:V(`MachineKeys.create`)(function*(n){let r=yield*z$;yield*t(n.permissions);let i=n.expiresAt===null?null:(Kh(n.expiresAt)-(yield*ep))/1e3;if(i!==null&&i<1)return yield*c1([`expiresAt`],`Expiry must be in the future`);let a=yield*l1(()=>e.auth.api.createApiKey({body:{userId:r.userId,name:n.name.trim(),permissions:Object.fromEntries(Object.entries(n.permissions).map(([e,t])=>[e,[...t]])),expiresIn:i}}));return{...yield*N9(a),key:a.key}}),update:V(`MachineKeys.update`)(function*(n){let r=yield*z$;return yield*t(n.permissions),yield*N9(yield*l1(()=>e.auth.api.updateApiKey({body:{userId:r.userId,keyId:n.keyId,name:n.name?.trim(),enabled:n.enabled,permissions:n.permissions?Object.fromEntries(Object.entries(n.permissions).map(([e,t])=>[e,[...t]])):void 0}})))}),delete:V(`MachineKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>e.auth.api.deleteApiKey({headers:r,body:{keyId:t}})),{deleted:!0}}),keyList:V(`MachineKeys.keyList`)(function*(t){let n=yield*ep,r=yield*e.resources.get(t),i=r===void 0||t===b1(e.settings.baseURL)?[]:r.scopes,a=i.length?yield*e.sql`
|
|
534
|
+
`)));return lM(QE(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?nM(i(e.body.body),a):uM(e,`content-type`,`text/event-stream`)},d9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},f9=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()]}),qbe=()=>{let e=Uj({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},Jbe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,Ybe=Ibe,Xbe=oS(TY),Zbe=oS(W(TY)),p9=e=>oy(e)?p9(e.thunk()):e,m9=e=>DY(p9(e)),h9=e=>{let t=p9(e),n=DY(t);if(n!==void 0)return{kind:n,many:!1};if(!ry(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(m9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},Qbe=e=>{let t=e.context?.isOptional===!0,n=p9(e);if(t&&ay(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!yre(e)),r=e===void 0||t.length>0?void 0:m9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=h9(n);return r===void 0||t&&r.many?void 0:r},$be=e=>{let t=p9(e.ast),n=h9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!iy(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=Qbe(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:mS(new Ny(a,t.indexSignatures,s))}},exe=e=>[...$v(e)?e.typeParameters:[],...ry(e)?[...e.elements,...e.rest]:[],...iy(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...ay(e)?e.types:[],...oy(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],txe=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),EY(e))return!0;n.push(...exe(e))}return!1},nxe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>txe(e)),rxe=(e,t)=>e.fields.flatMap(({name:e,kind:n,many:r})=>{let i=e===void 0?t:A(t,e)?t[e]:void 0;return(r?Zbe(i)?i:[]:Xbe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),g9=(e,t,n)=>n===void 0?e:e.annotate(t,n),ixe=(e,{readOnly:t,mcp:n})=>{let r=n.destructiveHint??(!t&&void 0),i=n._meta===void 0?void 0:{...n._meta},a=g9(g9(g9(e.annotate(U6,t),W6,r),G6,n.idempotentHint),K6,n.openWorldHint);return g9(g9(a,V6,n.title),H6,i)},axe=e=>Y_e(e.name,{description:e.description,parameters:JC(e.input),success:JC(e.success),failure:JC(G(rY(e))),failureMode:`return`}),oxe=(e,t)=>{cY(t.label,e.flatMap(e=>e.actions));let n=ive(...e.flatMap(e=>e.actions.map(n=>ixe(t.tool(axe(n),n,e),n))));return{toolkit:n,layer:n.toLayer(z(SY(e),e=>Object.fromEntries(e.map(([e,n])=>[e.name,t.handler?.(n,e)??n]))))}},_9={label:`MCP tool`,tool:e=>e.annotate(q6,!0)},sxe=oS(T8),v9=(e,t)=>{let n=yae(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=It(n.schema.$ref)?bx(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}},cxe=e=>{let t=e.map(([e])=>e).filter(e=>!sxe(v9(JC(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])=>nxe(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(`, `)}`)},lxe=e=>new O8({isError:!0,content:[{type:`text`,text:e}]}),y9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],uxe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),dxe=e=>K_e(e)&&Zt(e.reason,`ToolParameterValidationError`)?e.reason:void 0,b9=ga(M8,N8,DN,ff),fxe=B(function*(e,t){let n=yield*a9,r=yield*e.pipe(sm(t=>ma(t,ha(...Object.values(e.tools).flatMap(e=>{let n=j(e.id);return Bee(pa(t,n)).map(e=>na(n,{...e,context:b9(e.context)}))}))))),i=b9(yield*em()),a=e=>{let t=Cd(e);return wa(t)&&!Td(e)?Tp(t.failure):Um(e).pipe(jp(rm(nO(e),i)),Fp(lxe(`Tool execution failed due to an internal server error.`)))},o=e=>{let t=Cd(e);if(Ta(t)){let{error:e}=t.success,n=la(Ld(t.success),Y6)===`parameters`?dxe(e):void 0;if(n!==void 0)return L(new h8({message:n.message}))}return a(e)},s=yield*_p(Object.entries(r.tools),([e,n])=>I(function*(){let a=Z_e(n)===!0,s={onExcessProperty:a?`error`:`ignore`,errors:`all`},c=t.get(e),l=c===void 0||c.fields.length===0?void 0:c,u=l===void 0?n.successSchema:l.rest===void 0?void 0:JC(l.rest),d=u===void 0?void 0:yield*sS(E8)(v9(u,!1)).pipe(Up),f=yield*sS(T8)(v9(n.parametersSchema,a)).pipe(Up),p=new Set(l?.fields.map(({name:e})=>e)),m=({encodedResult:e,result:t})=>{if(l===void 0)return new O8({isError:!1,structuredContent:e,content:y9(e)});let n=rxe(l,t).map(uxe);if(u===void 0)return new O8({isError:!1,content:n});let r=Jt(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!p.has(e))):e;return new O8({isError:!1,structuredContent:r,content:[...y9(r),...n]})};return{tool:new D8({name:e,description:X_e(n),inputSchema:f,outputSchema:d,annotations:{...pa(n.annotations,V6).pipe(Li(e=>({title:e})),Fi),readOnlyHint:la(n.annotations,U6),destructiveHint:la(n.annotations,W6),idempotentHint:la(n.annotations,G6),openWorldHint:la(n.annotations,K6)},_meta:oa(n.annotations,H6)}),annotations:n.annotations,handle:t=>r.handle(e,t??{},void 0,s).pipe(YE,Poe,R(are),R(e=>e.isFailure?e.failureOrigin===`handler`?N(new O8({isError:!0,content:y9(e.encodedResult)})):Tp(Id(hd(e.result),na(Y6,e.failureOrigin??`result`))):N(m(e))),zp(o),rm(i))}}));for(let e of s)yield*n.addTool(e)}),pxe=(e,t,n=Vf,r)=>{let i=oxe(e,r===void 0?_9:{..._9,handler:(e,t)=>n=>t.caller===iY?e(n):g$(RY(r,e(n)))}),a=e.flatMap(e=>e.actions.map(e=>[e,$be(e.success)]));cxe(a);let o=new Map(a.map(([{name:e},t])=>[e,t])),s=I(function*(){let e=yield*a9,t=e.tools.flatMap(({tool:e})=>o.has(e.name)?[e.name]:[]);if(t.length>0)return yield*Dp(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature`));let n=yield*Lf(i.layer);yield*fxe(i.toolkit,o).pipe(im(ra(n,a9,e)))});return Gf(s).pipe(Zf(n),Zf(t),Hne,xY(e))},mxe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),hxe=e=>{let t=new Set(e.filter(({caller:e})=>e===iY).map(({name:e})=>e));return e=>{if(t.size===0)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(mxe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}};function gxe(e,{actions:t,features:n,path:r,authentication:i,...a}){let o=bY(vY(e),t),s=o.flatMap(e=>e.actions);LY(s,i);let c=pxe(o,Vbe({...a,path:r??`/mcp`,protocols:[Ybe]}),n,i);if(i===void 0)return c;let l=hxe(s),u=KN(z(i[`~provider`],e=>t=>R(DN,n=>e.http(t,!l(n.headers)))));return c.pipe(Zf(u.layer))}var _xe=`0.17.0`,x9=class extends Bo(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},S9=class extends qC()(`ProviderUnavailable`,{operation:H},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},C9=class extends Bo(`InsufficientScope`){},vxe=class extends qC()(`ConfigurationError`,{message:H}){};const w9=`key-list+jwt`,yxe=U({keys:W(U({id:H,sealed:H}))}),T9=wC(U({keyId:vC,ownerId:vC,scopes:W(vC),expiresAt:zS(rC)})),E9=new TextEncoder,bxe=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,E9.encode(e))),D9=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:E9.encode(`clankerauth key list\0${t}`)},n,512));return{id:cR(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},xxe=async(e,t,n)=>{let{id:r,key:i}=await D9(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,E9.encode(pS(T9)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:cR(s)}},Sxe=async(e,t,n)=>{let r=await D9(await bxe(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(sR(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return lS(T9)(new TextDecoder().decode(o))},O9=yo(1),k9=(e,t)=>tm(n=>sj(e).execute(t).pipe(cm(LP,{...oa(n,LP),redirect:`error`}),Hp(e=>new S9({operation:`http.request`,cause:e})))),Cxe=U({keys:W(U({kty:H,crv:gS(H),x:gS(H),kid:gS(H),alg:gS(H),use:gS(H),key_ops:gS(W(H))}))}),wxe=U({sub:vC,client_id:vC,scope:H,iat:rC,exp:rC}),Txe=U({list:H}),Exe=yxe.pipe(jS({exp:rC})),A9=e=>new x9({cause:e}),j9=vo(5),M9=V(`Verifier.make`)(function*(e){let t=yield*ej,n=yield*Op({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new vxe({message:`Invalid issuer URL`})}),r=V(`Verifier.jwks`)(function*(){let e=yield*k9(t,SA(n.jwks));return e.status===200?UB({keys:(yield*LA(Cxe)(e).pipe(Hp(e=>new S9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t)}):yield*new S9({operation:`jwks.fetch`,cause:{status:e.status}})},um),i=yield*ym(r(),e=>Kd(e)?`1 minute`:j9),a=V(`Verifier.signingKey`)(function*(e){let t=yield*i;return yield*bp({try:()=>t({alg:`EdDSA`,kid:e}),catch:A9})}),o=V(`Verifier.signed`)(function*(t,n){let r=yield*Op({try:()=>$B(t),catch:A9});if(r.alg!==`EdDSA`||r.kid===void 0)return yield*A9();let i=yield*a(r.kid),o=yield*ep,{payload:s}=yield*bp({try:()=>OB(t,i,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(o)}),catch:A9});return s}),s=V(`Verifier.jwt`)(function*(e){let t=yield*o(e,`at+jwt`);if(t.cnf!==void 0)return yield*A9();let n=yield*sS(wxe)(t).pipe(Hp(A9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),c=V(`Verifier.keyList`)(function*(){let r=CA(n.keyList).pipe(PA({resource:e.resource})),i=yield*k9(t,r);if(i.status!==200)return yield*new S9({operation:`key-list.fetch`,cause:{status:i.status}});let{list:a}=yield*LA(Txe)(i).pipe(Hp(e=>new S9({operation:`key-list.decode`,cause:e}))),s=e=>new S9({operation:`key-list.verify`,cause:e}),c=yield*o(a,w9).pipe(Rp(`Unauthorized`,e=>L(s(e)))),l=yield*sS(Exe)(c).pipe(Hp(s));return{readAt:yield*ep,expiresAt:l.exp*1e3,entries:new Map(l.keys.map(e=>[e.id,e.sealed]))}},um),l=yield*IO(!1),u=yield*ym(c().pipe(Jp({duration:`3 seconds`,orElse:()=>L(new S9({operation:`key-list.timeout`}))}),Wp(({operation:e})=>R(zO(l,!0),t=>t?F:Hm(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:e}))),Mp(()=>R(zO(l,!1),e=>e?Wm(`clankerauth key list reads have recovered`):F))),j9),d=yield*IO(void 0),f=I(function*(){let e=yield*Np(u);Ta(e)&&(yield*RO(d,e.success));let t=yield*LO(d);return t!==void 0&&t.expiresAt>(yield*ep)?t:yield*wa(e)?e.failure:new S9({operation:`key-list.expired`})}),p=V(`Verifier.apiKey`)(function*(t){let n=n=>bp({try:()=>Sxe(t,e.resource,n.entries),catch:A9}),r=yield*ep,i=yield*LO(d),a=i!==void 0&&r-i.readAt<bo(O9)&&i.expiresAt>r?i:yield*f,o=(yield*n(a))??(yield*R(f,e=>e===a?N(void 0):n(e)));return o===void 0||o.expiresAt!==null&&o.expiresAt<=(yield*ep)?yield*A9():{subject:o.ownerId,scopes:o.scopes,actor:{kind:`key`,keyId:o.keyId},expiresAt:o.expiresAt??void 0}});return{verifyToken:V(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?L(A9()):p(t):s(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new C9({scope:r,actor:n.actor})})}}),Dxe=V(`AdministrationResource.make`)(function*(){let e=yield*w6,t=`${e.settings.baseURL}/api/auth`,n=b1(e.settings.baseURL);return{protectedResource:{resource:n,authorizationServers:[t],scopesSupported:[y1.read,y1.write,`offline_access`],scopesRequired:[y1.read,y1.write]},verifier:yield*M9({issuer:t,resource:n,apiKeys:!1}).pipe(nm(RP.pipe(Zf(zf(IP,(t,n)=>{let r=new Request(t,n);return r.headers.set(`x-clankerauth-peer`,`127.0.0.1`),e.auth.handler(r)})))))}}),Oxe=sS(X$),kxe=sS(U({id:H,key:H,referenceId:H,expiresAt:zS(LC),permissions:zS(wC(X$))})),N9=B(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*Oxe(e.permissions??{}).pipe(Lp(()=>Fp(Hm(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?Vh(e.expiresAt):null,createdAt:Vh(e.createdAt)}}),P9=z(w6,e=>{let t=V(`MachineKeys.validate`)(function*(t){if(t!==void 0)for(let[n,r]of Object.entries(t)){if(n===b1(e.settings.baseURL))return yield*c1([`permissions`,n],`Administration requires OAuth access tokens, not API keys`);let t=yield*e.resources.get(n);if(!t||r.some(e=>!t.scopes.includes(e)))return yield*c1([`permissions`,n],`Select explicitly granted, currently available Resource scopes`)}});return{list:V(`MachineKeys.list`)(function*(){let{providerHeaders:t}=yield*z$,n=yield*t,r=yield*l1(()=>e.auth.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*_p(r.apiKeys,N9)}}),create:V(`MachineKeys.create`)(function*(n){let r=yield*z$;yield*t(n.permissions);let i=n.expiresAt===null?null:(Gh(n.expiresAt)-(yield*ep))/1e3;if(i!==null&&i<1)return yield*c1([`expiresAt`],`Expiry must be in the future`);let a=yield*l1(()=>e.auth.api.createApiKey({body:{userId:r.userId,name:n.name.trim(),permissions:Object.fromEntries(Object.entries(n.permissions).map(([e,t])=>[e,[...t]])),expiresIn:i}}));return{...yield*N9(a),key:a.key}}),update:V(`MachineKeys.update`)(function*(n){let r=yield*z$;return yield*t(n.permissions),yield*N9(yield*l1(()=>e.auth.api.updateApiKey({body:{userId:r.userId,keyId:n.keyId,name:n.name?.trim(),enabled:n.enabled,permissions:n.permissions?Object.fromEntries(Object.entries(n.permissions).map(([e,t])=>[e,[...t]])):void 0}})))}),delete:V(`MachineKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*z$,r=yield*n;return yield*l1(()=>e.auth.api.deleteApiKey({headers:r,body:{keyId:t}})),{deleted:!0}}),keyList:V(`MachineKeys.keyList`)(function*(t){let n=yield*ep,r=yield*e.resources.get(t),i=r===void 0||t===b1(e.settings.baseURL)?[]:r.scopes,a=i.length?yield*e.sql`
|
|
535
535
|
SELECT id, key, referenceId, expiresAt, permissions FROM apikey
|
|
536
536
|
WHERE enabled = 1 AND (expiresAt IS NULL OR expiresAt > ${new Date(n).toISOString()})
|
|
537
|
-
`:[],o=yield*_p(a,e=>I(function*(){let n=yield*
|
|
537
|
+
`:[],o=yield*_p(a,e=>I(function*(){let n=yield*kxe(e),r=(n.permissions?.[t]??[]).filter(e=>i.includes(e));return r.length?[yield*bp(()=>xxe(new Uint8Array(Buffer.from(n.key,`base64url`)),t,{keyId:n.id,ownerId:n.referenceId,scopes:r,expiresAt:n.expiresAt===null?null:Gh(n.expiresAt)}))]:[]}).pipe(Lp(()=>Fp(Hm(`An API key row cannot be listed; it is left out of key lists`,{keyId:e.id}),[])))),s=Math.floor(n/1e3),{token:c}=yield*l1(()=>e.auth.api.signDocument({body:{typ:w9,payload:{aud:t,iat:s,exp:s+86400,keys:o.flat()}}}));return{list:c}})}}),F9=(e,t)=>{let n=`Requires ${e}.`;return t.kind===`client`?new QJ({message:n,scopes:[e]}):new QJ({message:n})},Axe=(e,t)=>t===void 0||e.scopes.includes(t)?void 0:F9(t,e.actor),I9=e=>e instanceof x9?new YJ({message:e.message}):e instanceof C9?F9(e.scope,e.actor):e,L9=(e,t)=>Hp(e.verifyToken(Lg(t)),I9);V(`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*M9({issuer:r.issuer,resource:i,requiredScopes:[n],apiKeys:r.apiKeys}),c=e=>Jp(e,{duration:`5 seconds`,orElse:()=>L(new S9({operation:`verify.timeout`}))}),l={verifyToken:e=>c(s.verifyToken(e))},u=V(`Resource.principal`)(function*(e,t){let n=y$(e);if(ki(n))return yield*new YJ({message:`A bearer token is required.`});let r=yield*L9(l,n.value),i=Axe(r,t);return i===void 0?r:yield*i}),d=V(`Resource.admit`)(function*(t,n){let r=yield*Np(u(t,n));if(Ta(r))return{ok:!0,principal:r.success};let i=vM(Bue(r.failure,{authentication:e,protectedResource:o,authorization:t}));return{ok:!1,refusal:{status:i.status,headers:Object.fromEntries(i.headers),body:yield*yp(()=>i.text())}}});return{resource:i,issuer:r.issuer,protectedResource:o,verifier:l,admit:d,watch:(e,t)=>Tm(I(function*(){let n=yield*u(e,t),r=yield*ep,i=Math.max(0,(n.expiresAt??1/0)-r);return n.actor.kind===`key`?yield*Yp(Math.min(i,bo(O9))):(yield*Yp(i),yield*I9(new x9))}))}});const R9=V(`Administration.providerSession`)(function*(e,t){let{context:n}=e,r=new Date((yield*ep)+6e4),i=yield*fm(l1(()=>n.internalAdapter.createSession(t,!0,{expiresAt:r},!0)),e=>yp(()=>n.internalAdapter.deleteSession(e.token))),a=yield*l1(async()=>(await Promise.all([iF(n.authCookies.sessionToken.name,i.token,n.secret),iF(n.authCookies.dontRememberToken.name,`true`,n.secret)])).map(e=>e.split(`;`)[0]).join(`; `));return new Headers({origin:e.settings.baseURL,cookie:a})}),jxe=e=>A$(e,z(w6,e=>()=>I(function*(){let t=yield*DN,n=new Headers(t.headers),r=yield*l1(()=>e.auth.api.getSession({headers:n}));return r?{providerHeaders:N(n),userId:r.user.id,email:r.user.email,writable:!0}:yield*new YJ({message:`Owner session required`})}))),Mxe=f1(U({id:H,email:H})),Nxe=e=>A$(V$,z(w6,t=>{let n=()=>new YJ({message:`Owner authorization required`});return r=>I(function*(){let i=yield*L9(e.verifier,r).pipe(Rp(`ProviderUnavailable`,()=>L(new I$({error:`Request could not be completed`}))));if(i.actor.kind!==`client`)return yield*n();let a=i.scopes.includes(y1.write);if(!a&&!i.scopes.includes(y1.read))return yield*new QJ({message:`Insufficient scope`,scopes:[y1.read]});let o=yield*t.sql`SELECT u.id, u.email FROM user u
|
|
538
538
|
JOIN oauthClient c ON c.clientId = ${i.actor.clientId}
|
|
539
|
-
WHERE u.id = ${i.subject} AND c.disabled IS NOT 1`;if(!o[0])return yield*n();let s=yield*Nxe(o[0]);return{userId:s.id,email:s.email,writable:a,providerHeaders:R9(t,s.id)}})}),{protectedResource:e.protectedResource}),Fxe=e=>e.readOnly?F:R(z$,({writable:e})=>e?F:L(new QJ({message:`This action requires the ${y1.write} scope`,scopes:[y1.write]})));function Ixe(e){return qf(I(function*(){let t=yield*w6,n=yield*E6,r=yield*P9,i=IY(i1,{listClients:n.list,createClient:n.create,updateClient:n.update,deleteClient:n.delete,revokeClient:n.revoke,blockClient:n.block,rotateClientSecret:n.rotate,setClientAccess:n.access,createResource:n.createResource,updateResource:n.updateResource,deleteResource:n.deleteResource,listApiKeys:r.list,createApiKey:r.create,updateApiKey:r.update,deleteApiKey:r.delete},{authorize:Fxe}),a=IY(r1,{setupStatus:()=>t.owner().pipe(z(e=>({required:!e})),Hp(()=>new F$({error:`Request could not be completed`}))),setupOwner:n.setup,keyList:({resource:e})=>r.keyList(e)}),o=yield*Oxe(),s=B$(t.context.authCookies.sessionToken.name),c=a1(s),l=Yf(a$(c,i).pipe(Zf(Mxe(s))),BN(`GET`,`/openapi.json`,sM(jZ(c.api))),a$(c,a).pipe(Zf(Dde.layer))),u=Yf(_xe(i,{name:`clankerauth-admin`,version:vxe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${y1.read} or ${y1.write}; every other action changes authorization policy and needs ${y1.write}. Create and rotate actions return secrets once.`,authentication:V$}),a$(ode,i)).pipe(Zf(Pxe(o)));return Yf(l,u)}))}const z9=(e,t)=>e===t||e.endsWith(`.${t}`),Lxe=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!lt(e)}catch{return!1}},B9=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),V9=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,H9=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&B9(new URL(e),t),U9=B(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return H9(n,t)?Rg(e.secret).length<32?yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>H9(e,t))?r!==void 0&&(!Lxe(r)||!z9(new URL(n).hostname,r))?yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_COOKIE_DOMAIN must be a bare parent domain of the CLANKERAUTH_BASE_URL host, such as home.example`)):e:yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_MCP_ALLOWED_ORIGINS must contain exact ${V9}`)):yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${V9}`))});I(function*(){let e={baseURL:yield*LD(`CLANKERAUTH_BASE_URL`),secret:yield*VD(`CLANKERAUTH_BETTER_AUTH_SECRET`),database:yield*LD(`CLANKERAUTH_DATABASE`).pipe(wD(`data/clankerauth.sqlite`)),host:yield*LD(`CLANKERAUTH_HOST`).pipe(wD(`127.0.0.1`)),port:yield*BD(`CLANKERAUTH_PORT`).pipe(wD(3e3)),mcpAllowedOrigins:yield*RD(OC,`CLANKERAUTH_MCP_ALLOWED_ORIGINS`).pipe(wD([])),trustProxy:yield*zD(`CLANKERAUTH_TRUST_PROXY`).pipe(wD(!1)),allowInsecureHttp:yield*zD(`CLANKERAUTH_ALLOW_INSECURE_HTTP`).pipe(wD(!1)),cookieDomain:yield*LD(`CLANKERAUTH_COOKIE_DOMAIN`).pipe(wD(void 0))};return yield*U9(e)});const W9=`clankerauth_forward`,G9=(e,t)=>sM({error:t},{status:e}),Rxe=e=>qf(z(w6,t=>{let{settings:n}=t,r=t=>{if(!URL.canParse(t))return;let r=new URL(t);return!r.username&&!r.password&&B9(r,n.allowInsecureHttp)&&z9(r.hostname,e)?r:void 0},i=Rg(n.secret),a=b1(n.baseURL),o=new URL(`/login`,n.baseURL),s={domain:e,path:`/`,httpOnly:!0,secure:n.baseURL.startsWith(`https:`),sameSite:`lax`},c=t.context.authCookies.sessionToken.name,l=(e,t)=>{let r=new URL(e,n.baseURL);return r.searchParams.set(`rd`,t.href),r},u=e=>l1(()=>t.auth.api.getSession({headers:new Headers({cookie:e})})),d=I(function*(){let e=yield*DN,{headers:o}=e,s=o[`x-forwarded-proto`],d=o[`x-forwarded-host`],f=s&&d?r(`${s}://${d}${o[`x-forwarded-uri`]??`/`}`):void 0;if(!f)return G9(400,`invalid_forwarded_request`);let p=new URL(e.url,n.baseURL).searchParams.get(`resource`),m=p&&p!==a&&(yield*t.resources.get(p));if(!m)return G9(403,`unknown_resource`);let h=e.cookies[W9],g=h?yield*sre(bp(()=>EW({key:i,data:h}))):Oi(),_=Mi(g)?yield*u(`${c}=${g.value}`):null;if(!_)return o[`sec-fetch-mode`]===`navigate`?nM(l(`/forward-auth/continue`,f)):G9(401,`unauthenticated`);let v=Math.floor((yield*ep)/1e3),{token:y}=yield*l1(()=>t.auth.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 tM({status:204,headers:{authorization:`Bearer ${y}`}})}),f=I(function*(){let e=yield*DN,t=new URL(e.url,n.baseURL).searchParams.get(`rd`),a=t?r(t):void 0;if(!a)return G9(400,`invalid_return_url`);let o=e.cookies[c];if(!(o&&(yield*u(e.headers.cookie??``)))||!o)return nM(l(`/login`,l(`/forward-auth/continue`,a)));let d=yield*bp(()=>TW({key:i,data:o}));return yield*nM(a).pipe(mM(W9,d,s))}),p=I(function*(){let e=yield*DN,i=new URL(e.url,n.baseURL).searchParams.get(`rd`),a=i&&r(i)||o,{headers:c}=yield*l1(()=>t.auth.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}));return yield*hM(nM(a),pg(c.getSetCookie())).pipe(mM(W9,``,{...s,maxAge:0}))});return Yf(BN(`GET`,`/forward-auth`,Lp(d,u1)),BN(`GET`,`/forward-auth/continue`,Lp(f,u1)),BN(`GET`,`/forward-auth/logout`,Lp(p,u1)))})),zxe=e=>ct({requestTimeout:15e3,headersTimeout:1e4},e),Bxe=Rh(65536),Vxe=/^\/forward-auth(?:\?|$)/,Hxe=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Pi(t,()=>`unknown`)},Uxe=({baseURL:e,trustProxy:t})=>n=>I(function*(){let r=yield*DN,i=r.source,a=i instanceof st?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return tM({status:400});let o=Ot(r.headers,Vxe.test(a)?Xg(`forwarded`):Zg([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),qg(`host`,new URL(e).host),qg(`x-clankerauth-peer`,Hxe(r.headers,r.remoteAddress,t)),Xg(`x-forwarded-for`)),s=yield*n.pipe(lm(DN,r.modify({headers:o})),lm(zA,Bxe));return i instanceof st?TO(s.body).pipe(DO(`Stream`,e=>gM(s,tA(e.stream.pipe(Soe(()=>P(()=>i.socket.destroy()))),e.contentType,e.contentLength))),NO(()=>s)):s}).pipe(Sm),Wxe=/* @__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`]),Gxe=/* @__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`]),Kxe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),qxe=/* @__PURE__ */ new Set([`/`,`/login`,`/consent`,`/setup`]),Jxe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css)$/,K9=(e,t=200)=>sM(e,{status:t}),q9=K9({error:`Not found`},404),J9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],Yxe=new Set(J9.map(e=>e.toLowerCase())),Xxe=(e=tt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>qf(z(w6,t=>{let{auth:n,settings:r}=t,i=[.../* @__PURE__ */ new Set([r.baseURL,...r.mcpAllowedOrigins])],a=I(function*(){let e=yield*DN,i=new URL(e.url,r.baseURL),a=i.pathname.replace(/^\/api\/auth/,``);if(!Wxe.has(a)&&a!==`/.well-known/oauth-authorization-server/api/auth`)return q9;if(a===`/oauth2/authorize`){let n=e.method===`GET`?i.searchParams.getAll(`resource`):new URLSearchParams(yield*e.text).getAll(`resource`);if(n.length!==1||!(yield*t.resources.get(n[0]??``)))return K9({error:`invalid_target`,error_description:`Exactly one configured resource is required`},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*l1(()=>n.handler(new Request(i,{method:e.method,headers:e.headers,body:o})));return CM(s)}).pipe(Lp(u1)),o=zN(t=>I(function*(){let n=yield*AM;yield*t.add(`*`,`/*`,I(function*(){let t=yield*DN;if(t.method!==`GET`&&t.method!==`HEAD`)return q9;let i=new URL(t.url,r.baseURL).pathname,a=qxe.has(i)?`index.html`:Jxe.test(i)?i.slice(1):void 0;return a?yield*n.fileResponse($e(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:`text/html; charset=utf-8`}).pipe(Lp(()=>N(q9))):q9}))})),s=KN(e=>Uxe({baseURL:r.baseURL,trustProxy:r.trustProxy})(I(function*(){let t=yield*DN,n=new URL(t.url,r.baseURL).pathname,a=n.replace(/^\/api\/auth/,``),o=n===`/mcp`,s=t.headers.origin,c=s!==void 0&&i.includes(s),l=Gxe.has(a),u;if(o&&s!==void 0&&!c)u=K9({error:`Invalid origin`},403);else if(o&&t.method===`OPTIONS`){let e=t.headers[`access-control-request-method`],n=(t.headers[`access-control-request-headers`]??``).split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);u=c&&e===`POST`&&n.every(e=>Yxe.has(e))?tM({status:204}):K9({error:`MCP preflight rejected`},403)}else u=l&&t.method===`OPTIONS`?tM({status:204}):yield*e;l&&(u=u.pipe(pM({"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`}),fM(`access-control-allow-credentials`))),o&&(u=u.pipe(dM(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),fM(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(pM({"access-control-allow-origin":s,"access-control-expose-headers":`WWW-Authenticate, Mcp-Protocol-Version`})),t.method===`OPTIONS`&&u.status>=200&&u.status<300&&(u=u.pipe(pM({"access-control-allow-methods":`POST`,"access-control-allow-headers":J9.join(`, `)})))));let d=t.method!==`GET`||u.status!==200?`no-store`:n.startsWith(`/assets/`)?`public, max-age=31536000, immutable`:Kxe.has(a)?`public, max-age=300`:`no-store`;return u=u.pipe(pM({"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'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`})),r.baseURL.startsWith(`https:`)&&(u=u.pipe(dM(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),c=KN(e=>wm(e));return Yf(Ixe(i),r.cookieDomain===void 0?Vf:Rxe(r.cookieDomain),BN(`GET`,`/healthz`,t.sql`SELECT 1`.pipe(Fp(K9({status:`ok`})),Lp(u1))),BN(`*`,`/api/auth/*`,a),BN(`*`,`/.well-known/*`,a),o).pipe(Zf(c.layer),Zf(s),Zf(ale))})),Zxe=V(`Http.nodeHandler`)(function*(e){let t=yield*Fse(Xxe(e));return yield*rle(t,{scope:yield*um})}),Y9=`credentials.json`,X9=U({email:H,password:H,secret:H,clientId:yS(H),clientSecret:yS(H)}),Qxe=lS(TC(X9)),$xe=hS(X9),Z9=(e,t)=>R(oD,n=>n.writeFileString(Qe(e,Y9),`${JSON.stringify($xe(t),null,2)}\n`,{mode:384})),eSe=V(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:Ye(24).toString(`base64url`),secret:Ye(32).toString(`hex`)};if(!t)return n;let r=yield*oD,i=Qe(e,Y9);return(yield*r.exists(i))?yield*Qxe(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=V(`Dev.ownerSession`)(function*(e,t,n,r){if(t===void 0)return yield*L(/* @__PURE__ */ Error(`A forward-auth session needs a cookieDomain; the issuer serves none`));let i=yield*tj,a=yield*i.execute(wA(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(FA(n)));if(yield*a.text,a.status!==200)return yield*L(/* @__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:Dg(a.cookies)}});yield*s.text;let c=wg(a.cookies,s.cookies);return{cookie:Dg(c),cookies:Object.entries(Og(c)).map(([e,t])=>({name:e,value:t}))}}),tSe=Yf(FP,RP,zf(LP,{redirect:`manual`})),nSe=B(function*(e){let t=yield*oD,n=tt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(Qe(n,`index.html`))))return yield*L(/* @__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*Fp(t.makeDirectory($e(r),{recursive:!0,mode:448}),$e(r)),a=(e,t)=>{t.writeHead(503).end()},o=zxe((t,n)=>{try{e.onRequest?.({method:t.method??`GET`,url:new URL(t.url??`/`,`http://127.0.0.1:${t.socket.localPort}`)}),a(t,n)}catch{n.headersSent?n.destroy():n.writeHead(500).end(`Request failed`)}}),s=Cp(e=>{o.close(()=>e(F)),o.closeAllConnections()});yield*pm(Cp(t=>{let n=e=>t(L(e));o.once(`error`,n),o.listen(e.port??0,`127.0.0.1`,()=>{o.off(`error`,n),t(F)})}),()=>s);let c=o.address();if(!(c instanceof Object))return yield*L(/* @__PURE__ */ Error(`Disposable issuer failed to bind a TCP port`));let{port:l}=c,u=e.cookieDomain===void 0?`http://127.0.0.1:${l}`:`http://clankerauth.${e.cookieDomain}:${l}`,d=yield*eSe(i,r!==void 0),f=yield*U9({baseURL:u,secret:Ig(d.secret),database:Qe(i,`issuer.sqlite`),host:`127.0.0.1`,port:l,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),p=yield*Lf(w6.layer(f,{cimdTransport:e.cimdTransport})),m=da(p,w6),h=yield*bf(yield*um);a=yield*Zxe(n).pipe(rm(p),lm(mf,h)),yield*mm(()=>s);let g={email:d.email,password:d.password},_=yield*rm(E6,p),v=yield*rm(P9,p),y=e=>wm(dm(I(function*(){let t=yield*m.owner();if(t===void 0)return yield*Dp(/* @__PURE__ */ Error(`Owner setup failed`));let n=yield*R9(m,t);return yield*e(t).pipe(lm(z$,{userId:t,email:g.email,writable:!0,providerHeaders:N(n)}))}))).pipe(Hp(Q9));(yield*m.owner())||(yield*T6(m,g).pipe(Hp(Q9))),yield*y(()=>_p(e.resources,e=>R(m.resources.get(e.identifier),t=>t?F:Ip(_.createResource(e)))));let b=yield*y(()=>I(function*(){if(d.clientId!==void 0&&d.clientSecret!==void 0){let{clients:e}=yield*_.list();if(e.some(e=>e.client_id===d.clientId))return{client_id:d.clientId,client_secret:d.clientSecret}}return yield*_.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`})})),x=b.client_secret;if(x===void 0)return yield*L(/* @__PURE__ */ Error(`Disposable issuer did not return client credentials`));r!==void 0&&(yield*Z9(i,{...d,clientId:b.client_id,clientSecret:x}));let S=e.cookieDomain===void 0?void 0:u;return{details:{issuer:`${u}/api/auth`,clientId:b.client_id,clientSecret:x,owner:g,url:u,port:l,directory:i},apiKey:e=>y(()=>z(v.create({name:e.name??`development`,permissions:e.permissions,expiresAt:null}),e=>e.key)),ownerSession:e=>$9(u,S,g,e),ownerToken:V(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(u,S,g,e.appOrigin),n=yield*tj,r=new URL(e.appOrigin),i=new URL(`/forward-auth`,u);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*L(/* @__PURE__ */ Error(`Forward auth issued no token (HTTP ${a.status})`)):o.replace(/^Bearer /iu,``)})}});async function rSe(e){let t=gf(),n=e=>Lm(e.pipe(lm(mf,t),rm(tSe)),{onFiberStart:sw(t)}),r=zm(ym(Sf(t,Gd)));try{let t=await n(nSe(e));return{...t.details,apiKey:e=>n(t.apiKey(e)),ownerSession:e=>n(t.ownerSession(e)),ownerToken:e=>n(t.ownerToken(e)),close:()=>Lm(r)}}catch(e){throw await Lm(r),e}}export{rSe as startDisposableIssuer,mde as t};
|
|
539
|
+
WHERE u.id = ${i.subject} AND c.disabled IS NOT 1`;if(!o[0])return yield*n();let s=yield*Mxe(o[0]);return{userId:s.id,email:s.email,writable:a,providerHeaders:R9(t,s.id)}})}),{protectedResource:e.protectedResource}),Pxe=e=>e.readOnly?F:R(z$,({writable:e})=>e?F:L(new QJ({message:`This action requires the ${y1.write} scope`,scopes:[y1.write]})));function Fxe(e){return qf(I(function*(){let t=yield*w6,n=yield*E6,r=yield*P9,i=IY(i1,{listClients:n.list,createClient:n.create,updateClient:n.update,deleteClient:n.delete,revokeClient:n.revoke,blockClient:n.block,rotateClientSecret:n.rotate,setClientAccess:n.access,createResource:n.createResource,updateResource:n.updateResource,deleteResource:n.deleteResource,listApiKeys:r.list,createApiKey:r.create,updateApiKey:r.update,deleteApiKey:r.delete},{authorize:Pxe}),a=IY(r1,{setupStatus:()=>t.owner().pipe(z(e=>({required:!e})),Hp(()=>new F$({error:`Request could not be completed`}))),setupOwner:n.setup,keyList:({resource:e})=>r.keyList(e)}),o=yield*Dxe(),s=B$(t.context.authCookies.sessionToken.name),c=a1(s),l=Yf(a$(c,i).pipe(Zf(jxe(s))),BN(`GET`,`/openapi.json`,oM(jZ(c.api))),a$(c,a).pipe(Zf(Ede.layer))),u=Yf(gxe(i,{name:`clankerauth-admin`,version:_xe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${y1.read} or ${y1.write}; every other action changes authorization policy and needs ${y1.write}. Create and rotate actions return secrets once.`,authentication:V$}),a$(ode,i)).pipe(Zf(Nxe(o)));return Yf(l,u)}))}const z9=(e,t)=>e===t||e.endsWith(`.${t}`),Ixe=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!lt(e)}catch{return!1}},B9=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),V9=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,H9=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&B9(new URL(e),t),U9=B(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return H9(n,t)?Lg(e.secret).length<32?yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>H9(e,t))?r!==void 0&&(!Ixe(r)||!z9(new URL(n).hostname,r))?yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_COOKIE_DOMAIN must be a bare parent domain of the CLANKERAUTH_BASE_URL host, such as home.example`)):e:yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_MCP_ALLOWED_ORIGINS must contain exact ${V9}`)):yield*L(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${V9}`))});I(function*(){let e={baseURL:yield*ID(`CLANKERAUTH_BASE_URL`),secret:yield*BD(`CLANKERAUTH_BETTER_AUTH_SECRET`),database:yield*ID(`CLANKERAUTH_DATABASE`).pipe(CD(`data/clankerauth.sqlite`)),host:yield*ID(`CLANKERAUTH_HOST`).pipe(CD(`127.0.0.1`)),port:yield*zD(`CLANKERAUTH_PORT`).pipe(CD(3e3)),mcpAllowedOrigins:yield*LD(DC,`CLANKERAUTH_MCP_ALLOWED_ORIGINS`).pipe(CD([])),trustProxy:yield*RD(`CLANKERAUTH_TRUST_PROXY`).pipe(CD(!1)),allowInsecureHttp:yield*RD(`CLANKERAUTH_ALLOW_INSECURE_HTTP`).pipe(CD(!1)),cookieDomain:yield*ID(`CLANKERAUTH_COOKIE_DOMAIN`).pipe(CD(void 0))};return yield*U9(e)});const W9=`clankerauth_forward`,G9=(e,t)=>oM({error:t},{status:e}),Lxe=e=>qf(z(w6,t=>{let{settings:n}=t,r=t=>{if(!URL.canParse(t))return;let r=new URL(t);return!r.username&&!r.password&&B9(r,n.allowInsecureHttp)&&z9(r.hostname,e)?r:void 0},i=Lg(n.secret),a=b1(n.baseURL),o=new URL(`/login`,n.baseURL),s={domain:e,path:`/`,httpOnly:!0,secure:n.baseURL.startsWith(`https:`),sameSite:`lax`},c=t.context.authCookies.sessionToken.name,l=(e,t)=>{let r=new URL(e,n.baseURL);return r.searchParams.set(`rd`,t.href),r},u=e=>l1(()=>t.auth.api.getSession({headers:new Headers({cookie:e})})),d=I(function*(){let e=yield*DN,{headers:o}=e,s=o[`x-forwarded-proto`],d=o[`x-forwarded-host`],f=s&&d?r(`${s}://${d}${o[`x-forwarded-uri`]??`/`}`):void 0;if(!f)return G9(400,`invalid_forwarded_request`);let p=new URL(e.url,n.baseURL).searchParams.get(`resource`),m=p&&p!==a&&(yield*t.resources.get(p));if(!m)return G9(403,`unknown_resource`);let h=e.cookies[W9],g=h?yield*sre(bp(()=>EW({key:i,data:h}))):Di(),_=Ai(g)?yield*u(`${c}=${g.value}`):null;if(!_)return o[`sec-fetch-mode`]===`navigate`?tM(l(`/forward-auth/continue`,f)):G9(401,`unauthenticated`);let v=Math.floor((yield*ep)/1e3),{token:y}=yield*l1(()=>t.auth.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 eM({status:204,headers:{authorization:`Bearer ${y}`}})}),f=I(function*(){let e=yield*DN,t=new URL(e.url,n.baseURL).searchParams.get(`rd`),a=t?r(t):void 0;if(!a)return G9(400,`invalid_return_url`);let o=e.cookies[c];if(!(o&&(yield*u(e.headers.cookie??``)))||!o)return tM(l(`/login`,l(`/forward-auth/continue`,a)));let d=yield*bp(()=>TW({key:i,data:o}));return yield*tM(a).pipe(pM(W9,d,s))}),p=I(function*(){let e=yield*DN,i=new URL(e.url,n.baseURL).searchParams.get(`rd`),a=i&&r(i)||o,{headers:c}=yield*l1(()=>t.auth.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}));return yield*mM(tM(a),fg(c.getSetCookie())).pipe(pM(W9,``,{...s,maxAge:0}))});return Yf(BN(`GET`,`/forward-auth`,Lp(d,u1)),BN(`GET`,`/forward-auth/continue`,Lp(f,u1)),BN(`GET`,`/forward-auth/logout`,Lp(p,u1)))})),Rxe=e=>ct({requestTimeout:15e3,headersTimeout:1e4},e),zxe=Lh(65536),Bxe=/^\/forward-auth(?:\?|$)/,Vxe=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Mi(t,()=>`unknown`)},Hxe=({baseURL:e,trustProxy:t})=>n=>I(function*(){let r=yield*DN,i=r.source,a=i instanceof st?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return eM({status:400});let o=Ot(r.headers,Bxe.test(a)?Yg(`forwarded`):Xg([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),Kg(`host`,new URL(e).host),Kg(`x-clankerauth-peer`,Vxe(r.headers,r.remoteAddress,t)),Yg(`x-forwarded-for`)),s=yield*n.pipe(cm(DN,r.modify({headers:o})),cm(RA,zxe));return i instanceof st?wO(s.body).pipe(EO(`Stream`,e=>hM(s,eA(e.stream.pipe(Coe(()=>P(()=>i.socket.destroy()))),e.contentType,e.contentLength))),MO(()=>s)):s}).pipe(xm),Uxe=/* @__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`]),Wxe=/* @__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`]),Gxe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),Kxe=/* @__PURE__ */ new Set([`/`,`/login`,`/consent`,`/setup`]),qxe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css)$/,K9=(e,t=200)=>oM(e,{status:t}),q9=K9({error:`Not found`},404),J9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],Jxe=new Set(J9.map(e=>e.toLowerCase())),Yxe=(e=tt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>qf(z(w6,t=>{let{auth:n,settings:r}=t,i=[.../* @__PURE__ */ new Set([r.baseURL,...r.mcpAllowedOrigins])],a=I(function*(){let e=yield*DN,i=new URL(e.url,r.baseURL),a=i.pathname.replace(/^\/api\/auth/,``);if(!Uxe.has(a)&&a!==`/.well-known/oauth-authorization-server/api/auth`)return q9;if(a===`/oauth2/authorize`){let n=e.method===`GET`?i.searchParams.getAll(`resource`):new URLSearchParams(yield*e.text).getAll(`resource`);if(n.length!==1||!(yield*t.resources.get(n[0]??``)))return K9({error:`invalid_target`,error_description:`Exactly one configured resource is required`},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*l1(()=>n.handler(new Request(i,{method:e.method,headers:e.headers,body:o})));return SM(s)}).pipe(Lp(u1)),o=zN(t=>I(function*(){let n=yield*kM;yield*t.add(`*`,`/*`,I(function*(){let t=yield*DN;if(t.method!==`GET`&&t.method!==`HEAD`)return q9;let i=new URL(t.url,r.baseURL).pathname,a=Kxe.has(i)?`index.html`:qxe.test(i)?i.slice(1):void 0;return a?yield*n.fileResponse($e(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:`text/html; charset=utf-8`}).pipe(Lp(()=>N(q9))):q9}))})),s=KN(e=>Hxe({baseURL:r.baseURL,trustProxy:r.trustProxy})(I(function*(){let t=yield*DN,n=new URL(t.url,r.baseURL).pathname,a=n.replace(/^\/api\/auth/,``),o=n===`/mcp`,s=t.headers.origin,c=s!==void 0&&i.includes(s),l=Wxe.has(a),u;if(o&&s!==void 0&&!c)u=K9({error:`Invalid origin`},403);else if(o&&t.method===`OPTIONS`){let e=t.headers[`access-control-request-method`],n=(t.headers[`access-control-request-headers`]??``).split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);u=c&&e===`POST`&&n.every(e=>Jxe.has(e))?eM({status:204}):K9({error:`MCP preflight rejected`},403)}else u=l&&t.method===`OPTIONS`?eM({status:204}):yield*e;l&&(u=u.pipe(fM({"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`}),dM(`access-control-allow-credentials`))),o&&(u=u.pipe(uM(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),dM(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(fM({"access-control-allow-origin":s,"access-control-expose-headers":`WWW-Authenticate, Mcp-Protocol-Version`})),t.method===`OPTIONS`&&u.status>=200&&u.status<300&&(u=u.pipe(fM({"access-control-allow-methods":`POST`,"access-control-allow-headers":J9.join(`, `)})))));let d=t.method!==`GET`||u.status!==200?`no-store`:n.startsWith(`/assets/`)?`public, max-age=31536000, immutable`:Gxe.has(a)?`public, max-age=300`:`no-store`;return u=u.pipe(fM({"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'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`})),r.baseURL.startsWith(`https:`)&&(u=u.pipe(uM(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),c=KN(e=>Cm(e));return Yf(Fxe(i),r.cookieDomain===void 0?Vf:Lxe(r.cookieDomain),BN(`GET`,`/healthz`,t.sql`SELECT 1`.pipe(Fp(K9({status:`ok`})),Lp(u1))),BN(`*`,`/api/auth/*`,a),BN(`*`,`/.well-known/*`,a),o).pipe(Zf(c.layer),Zf(s),Zf(ale))})),Xxe=V(`Http.nodeHandler`)(function*(e){let t=yield*Fse(Yxe(e));return yield*rle(t,{scope:yield*lm})}),Y9=`credentials.json`,X9=U({email:H,password:H,secret:H,clientId:_S(H),clientSecret:_S(H)}),Zxe=sS(wC(X9)),Qxe=pS(X9),Z9=(e,t)=>R(aD,n=>n.writeFileString(Qe(e,Y9),`${JSON.stringify(Qxe(t),null,2)}\n`,{mode:384})),$xe=V(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:Ye(24).toString(`base64url`),secret:Ye(32).toString(`hex`)};if(!t)return n;let r=yield*aD,i=Qe(e,Y9);return(yield*r.exists(i))?yield*Zxe(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=V(`Dev.ownerSession`)(function*(e,t,n,r){if(t===void 0)return yield*L(/* @__PURE__ */ Error(`A forward-auth session needs a cookieDomain; the issuer serves none`));let i=yield*ej,a=yield*i.execute(CA(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(PA(n)));if(yield*a.text,a.status!==200)return yield*L(/* @__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:Eg(a.cookies)}});yield*s.text;let c=Cg(a.cookies,s.cookies);return{cookie:Eg(c),cookies:Object.entries(Dg(c)).map(([e,t])=>({name:e,value:t}))}}),eSe=Yf(FP,RP,zf(LP,{redirect:`manual`})),tSe=B(function*(e){let t=yield*aD,n=tt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(Qe(n,`index.html`))))return yield*L(/* @__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*Fp(t.makeDirectory($e(r),{recursive:!0,mode:448}),$e(r)),a=(e,t)=>{t.writeHead(503).end()},o=Rxe((t,n)=>{try{e.onRequest?.({method:t.method??`GET`,url:new URL(t.url??`/`,`http://127.0.0.1:${t.socket.localPort}`)}),a(t,n)}catch{n.headersSent?n.destroy():n.writeHead(500).end(`Request failed`)}}),s=Cp(e=>{o.close(()=>e(F)),o.closeAllConnections()});yield*fm(Cp(t=>{let n=e=>t(L(e));o.once(`error`,n),o.listen(e.port??0,`127.0.0.1`,()=>{o.off(`error`,n),t(F)})}),()=>s);let c=o.address();if(!(c instanceof Object))return yield*L(/* @__PURE__ */ Error(`Disposable issuer failed to bind a TCP port`));let{port:l}=c,u=e.cookieDomain===void 0?`http://127.0.0.1:${l}`:`http://clankerauth.${e.cookieDomain}:${l}`,d=yield*$xe(i,r!==void 0),f=yield*U9({baseURL:u,secret:Fg(d.secret),database:Qe(i,`issuer.sqlite`),host:`127.0.0.1`,port:l,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),p=yield*Lf(w6.layer(f,{cimdTransport:e.cimdTransport})),m=la(p,w6),h=yield*bf(yield*lm);a=yield*Xxe(n).pipe(nm(p),cm(mf,h)),yield*pm(()=>s);let g={email:d.email,password:d.password},_=yield*nm(E6,p),v=yield*nm(P9,p),y=e=>Cm(um(I(function*(){let t=yield*m.owner();if(t===void 0)return yield*Dp(/* @__PURE__ */ Error(`Owner setup failed`));let n=yield*R9(m,t);return yield*e(t).pipe(cm(z$,{userId:t,email:g.email,writable:!0,providerHeaders:N(n)}))}))).pipe(Hp(Q9));(yield*m.owner())||(yield*T6(m,g).pipe(Hp(Q9))),yield*y(()=>_p(e.resources,e=>R(m.resources.get(e.identifier),t=>t?F:Ip(_.createResource(e)))));let b=yield*y(()=>I(function*(){if(d.clientId!==void 0&&d.clientSecret!==void 0){let{clients:e}=yield*_.list();if(e.some(e=>e.client_id===d.clientId))return{client_id:d.clientId,client_secret:d.clientSecret}}return yield*_.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`})})),x=b.client_secret;if(x===void 0)return yield*L(/* @__PURE__ */ Error(`Disposable issuer did not return client credentials`));r!==void 0&&(yield*Z9(i,{...d,clientId:b.client_id,clientSecret:x}));let S=e.cookieDomain===void 0?void 0:u;return{details:{issuer:`${u}/api/auth`,clientId:b.client_id,clientSecret:x,owner:g,url:u,port:l,directory:i},apiKey:e=>y(()=>z(v.create({name:e.name??`development`,permissions:e.permissions,expiresAt:null}),e=>e.key)),ownerSession:e=>$9(u,S,g,e),ownerToken:V(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(u,S,g,e.appOrigin),n=yield*ej,r=new URL(e.appOrigin),i=new URL(`/forward-auth`,u);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*L(/* @__PURE__ */ Error(`Forward auth issued no token (HTTP ${a.status})`)):o.replace(/^Bearer /iu,``)})}});async function nSe(e){let t=gf(),n=e=>Im(e.pipe(cm(mf,t),nm(eSe)),{onFiberStart:ow(t)}),r=Rm(vm(Sf(t,Gd)));try{let t=await n(tSe(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{nSe as startDisposableIssuer,mde as t};
|