context-doctor 0.35.1 → 0.37.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/README.md +21 -14
- package/dist/ab.d.ts +188 -0
- package/dist/ab.js +857 -0
- package/dist/abtasks.d.ts +49 -0
- package/dist/abtasks.js +287 -0
- package/dist/cli.js +83 -8
- package/dist/compact.d.ts +36 -0
- package/dist/compact.js +144 -0
- package/dist/copilot.d.ts +63 -0
- package/dist/copilot.js +96 -0
- package/dist/doctor.js +114 -1
- package/dist/extract.d.ts +23 -0
- package/dist/extract.js +121 -4
- package/dist/fileparams.d.ts +61 -0
- package/dist/fileparams.js +308 -0
- package/dist/handoff.d.ts +143 -0
- package/dist/handoff.js +529 -0
- package/dist/hook.d.ts +1 -1
- package/dist/hook.js +25 -3
- package/dist/httpguard.d.ts +56 -0
- package/dist/httpguard.js +141 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +16 -0
- package/dist/install.js +176 -3
- package/dist/ledger.d.ts +6 -1
- package/dist/ledger.js +45 -7
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +72 -56
- package/dist/pack.d.ts +20 -0
- package/dist/pack.js +29 -1
- package/dist/preferences.d.ts +3 -1
- package/dist/preferences.js +8 -6
- package/dist/pricing.d.ts +7 -0
- package/dist/pricing.js +29 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/rules.d.ts +19 -0
- package/dist/rules.js +34 -0
- package/dist/sketch.d.ts +5 -1
- package/dist/sketch.js +23 -7
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +2 -0
package/dist/mcp.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cdRequire } from 'module'; const require = __cdRequire(import.meta.url);
|
|
3
|
-
var C0=Object.create;var ka=Object.defineProperty;var A0=Object.getOwnPropertyDescriptor;var N0=Object.getOwnPropertyNames;var M0=Object.getPrototypeOf,j0=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var T=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),eo=(t,e)=>{for(var r in e)ka(t,r,{get:e[r],enumerable:!0})},Z0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of N0(e))!j0.call(t,o)&&o!==r&&ka(t,o,{get:()=>e[o],enumerable:!(n=A0(e,o))||n.enumerable});return t};var Sa=(t,e,r)=>(r=t!=null?C0(M0(t)):{},Z0(e||!t||!t.__esModule?ka(r,"default",{value:t,enumerable:!0}):r,t));function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function tt(t){return t&&Object.assign(vs,t),vs}var Wx,Kx,Ut,vs,yn=G(()=>{Wx=Object.freeze({status:"aborted"});Kx=Symbol("zod_brand"),Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vs={}});var X={};eo(X,{BIGINT_FORMAT_RANGES:()=>ap,Class:()=>Ia,NUMBER_FORMAT_RANGES:()=>Za,aborted:()=>Dr,allowsEval:()=>Na,assert:()=>eb,assertEqual:()=>Gx,assertIs:()=>Yx,assertNever:()=>Qx,assertNotEqual:()=>Xx,assignProp:()=>Aa,cached:()=>io,captureStackTrace:()=>bs,cleanEnum:()=>pb,cleanRegex:()=>co,clone:()=>rt,createTransparentProxy:()=>ib,defineLazy:()=>de,esc:()=>Zr,escapeRegex:()=>rr,extend:()=>ub,finalizeIssue:()=>ht,floatSafeRemainder:()=>Ca,getElementAtPath:()=>tb,getEnumValues:()=>so,getLengthableOrigin:()=>uo,getParsedType:()=>sb,getSizableOrigin:()=>cp,isObject:()=>_n,isPlainObject:()=>vn,issue:()=>Da,joinValues:()=>xs,jsonStringifyReplacer:()=>Oa,merge:()=>lb,normalizeParams:()=>j,nullish:()=>ao,numKeys:()=>ob,omit:()=>cb,optionalKeys:()=>ja,partial:()=>db,pick:()=>ab,prefixIssues:()=>Tt,primitiveTypes:()=>ip,promiseAllObject:()=>rb,propertyKeyTypes:()=>Ma,randomString:()=>nb,required:()=>fb,stringifyPrimitive:()=>ws,unwrapMessage:()=>oo});function Gx(t){return t}function Xx(t){return t}function Yx(t){}function Qx(t){throw new Error}function eb(t){}function so(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function xs(t,e="|"){return t.map(r=>ws(r)).join(e)}function Oa(t,e){return typeof e=="bigint"?e.toString():e}function io(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ao(t){return t==null}function co(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ca(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Aa(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tb(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function rb(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function nb(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Zr(t){return JSON.stringify(t)}function _n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vn(t){if(_n(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(_n(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ob(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ib(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function ws(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ja(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function ab(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return rt(t,{...t._zod.def,shape:r,checks:[]})}function cb(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return rt(t,{...t._zod.def,shape:r,checks:[]})}function ub(t,e){if(!vn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Aa(this,"shape",n),n},checks:[]};return rt(t,r)}function lb(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Aa(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function db(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return rt(e,{...e._zod.def,shape:o,checks:[]})}function fb(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return rt(e,{...e._zod.def,shape:o,checks:[]})}function Dr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Tt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function oo(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=oo(t.inst?._zod.def?.error?.(t))??oo(e?.error?.(t))??oo(r.customError?.(t))??oo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function cp(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function uo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Da(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function pb(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var bs,Na,sb,Ma,ip,Za,ap,Ia,zt=G(()=>{bs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Na=io(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});sb=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ma=new Set(["string","number","symbol"]),ip=new Set(["string","number","bigint","boolean","symbol","undefined"]);Za={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ap={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ia=class{constructor(...e){}}});function qa(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function La(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var up,$s,lo,Ua=G(()=>{yn();zt();up=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Oa,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$s=w("$ZodError",up),lo=w("$ZodError",up,{Parent:Error})});var Fa,Ha,Va,Ba,Ja,qr,Wa,Lr,Ka=G(()=>{yn();Ua();zt();Fa=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ut;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Ha=Fa(lo),Va=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,tt())));throw bs(a,o?.callee),a}return i.value},Ba=Va(lo),Ja=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(t??$s)(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},qr=Ja(lo),Wa=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ht(i,o,tt())))}:{success:!0,data:s.value}},Lr=Wa(lo)});function vp(){return new RegExp(hb,"u")}function Pp(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rp(t){return new RegExp(`^${Pp(t)}$`)}function Ip(t){let e=Pp({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Tp}T(?:${n})$`)}var lp,dp,fp,pp,mp,hp,gp,yp,Ga,_p,hb,xp,bp,wp,$p,kp,Xa,Sp,Ep,Tp,zp,Op,Cp,Ap,Np,Mp,jp,Zp,Ss=G(()=>{lp=/^[cC][^\s-]{8,}$/,dp=/^[0-9a-z]+$/,fp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pp=/^[0-9a-vA-V]{20}$/,mp=/^[A-Za-z0-9]{27}$/,hp=/^[a-zA-Z0-9_-]{21}$/,gp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ga=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,_p=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";xp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,bp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,wp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,$p=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xa=/^[A-Za-z0-9_-]*$/,Sp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ep=/^\+(?:[0-9]){6,14}[0-9]$/,Tp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zp=new RegExp(`^${Tp}$`);Op=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Cp=/^\d+$/,Ap=/^-?\d+(?:\.\d+)?/i,Np=/true|false/i,Mp=/null/i,jp=/^[^A-Z]*$/,Zp=/^[^a-z]*$/});var Re,Dp,Ya,Qa,qp,Lp,Up,Fp,Hp,fo,Vp,Bp,Jp,Wp,Kp,Gp,Xp,Es=G(()=>{yn();Ss();zt();Re=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Dp={number:"number",bigint:"bigint",object:"date"},Ya=w("$ZodCheckLessThan",(t,e)=>{Re.init(t,e);let r=Dp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Qa=w("$ZodCheckGreaterThan",(t,e)=>{Re.init(t,e);let r=Dp[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qp=w("$ZodCheckMultipleOf",(t,e)=>{Re.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Ca(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Lp=w("$ZodCheckNumberFormat",(t,e)=>{Re.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Za[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Cp)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Up=w("$ZodCheckMaxLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=uo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Fp=w("$ZodCheckMinLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=uo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Hp=w("$ZodCheckLengthEquals",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=uo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),fo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Re.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Vp=w("$ZodCheckRegex",(t,e)=>{fo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Bp=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=jp),fo.init(t,e)}),Jp=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Zp),fo.init(t,e)}),Wp=w("$ZodCheckIncludes",(t,e)=>{Re.init(t,e);let r=rr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Kp=w("$ZodCheckStartsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`^${rr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Gp=w("$ZodCheckEndsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`.*${rr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Xp=w("$ZodCheckOverwrite",(t,e)=>{Re.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ts,ec=G(()=>{Ts=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
3
|
+
var Jx=Object.create;var Ga=Object.defineProperty;var Kx=Object.getOwnPropertyDescriptor;var Wx=Object.getOwnPropertyNames;var Gx=Object.getPrototypeOf,Xx=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),fo=(t,e)=>{for(var r in e)Ga(t,r,{get:e[r],enumerable:!0})},Yx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wx(e))!Xx.call(t,o)&&o!==r&&Ga(t,o,{get:()=>e[o],enumerable:!(n=Kx(e,o))||n.enumerable});return t};var Xa=(t,e,r)=>(r=t!=null?Jx(Gx(t)):{},Yx(e||!t||!t.__esModule?Ga(r,"default",{value:t,enumerable:!0}):r,t));function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function ot(t){return t&&Object.assign(Cs,t),Cs}var cw,uw,Wt,Cs,Sn=X(()=>{cw=Object.freeze({status:"aborted"});uw=Symbol("zod_brand"),Wt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Cs={}});var Y={};fo(Y,{BIGINT_FORMAT_RANGES:()=>Hp,Class:()=>nc,NUMBER_FORMAT_RANGES:()=>lc,aborted:()=>Wr,allowsEval:()=>ac,assert:()=>mw,assertEqual:()=>lw,assertIs:()=>fw,assertNever:()=>pw,assertNotEqual:()=>dw,assignProp:()=>ic,cached:()=>_o,captureStackTrace:()=>As,cleanEnum:()=>Ew,cleanRegex:()=>xo,clone:()=>st,createTransparentProxy:()=>xw,defineLazy:()=>fe,esc:()=>Kr,escapeRegex:()=>lr,extend:()=>$w,finalizeIssue:()=>xt,floatSafeRemainder:()=>sc,getElementAtPath:()=>hw,getEnumValues:()=>yo,getLengthableOrigin:()=>bo,getParsedType:()=>vw,getSizableOrigin:()=>Bp,isObject:()=>Tn,isPlainObject:()=>En,issue:()=>dc,joinValues:()=>Os,jsonStringifyReplacer:()=>oc,merge:()=>kw,normalizeParams:()=>L,nullish:()=>vo,numKeys:()=>_w,omit:()=>ww,optionalKeys:()=>uc,partial:()=>Sw,pick:()=>bw,prefixIssues:()=>Ot,primitiveTypes:()=>Up,promiseAllObject:()=>gw,propertyKeyTypes:()=>cc,randomString:()=>yw,required:()=>Tw,stringifyPrimitive:()=>Ns,unwrapMessage:()=>go});function lw(t){return t}function dw(t){return t}function fw(t){}function pw(t){throw new Error}function mw(t){}function yo(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Os(t,e="|"){return t.map(r=>Ns(r)).join(e)}function oc(t,e){return typeof e=="bigint"?e.toString():e}function _o(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function vo(t){return t==null}function xo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function sc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function fe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ic(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function hw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function gw(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function yw(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Kr(t){return JSON.stringify(t)}function Tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function En(t){if(Tn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Tn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function _w(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function lr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function xw(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ns(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function uc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function bw(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return st(t,{...t._zod.def,shape:r,checks:[]})}function ww(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return st(t,{...t._zod.def,shape:r,checks:[]})}function $w(t,e){if(!En(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ic(this,"shape",n),n},checks:[]};return st(t,r)}function kw(t,e){return st(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return ic(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Sw(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return st(e,{...e._zod.def,shape:o,checks:[]})}function Tw(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return st(e,{...e._zod.def,shape:o,checks:[]})}function Wr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Ot(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function go(t){return typeof t=="string"?t:t?.message}function xt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=go(t.inst?._zod.def?.error?.(t))??go(e?.error?.(t))??go(r.customError?.(t))??go(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Bp(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function bo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function dc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ew(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var As,ac,vw,cc,Up,lc,Hp,nc,At=X(()=>{As=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};ac=_o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});vw=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},cc=new Set(["string","number","symbol"]),Up=new Set(["string","number","bigint","boolean","symbol","undefined"]);lc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Hp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};nc=class{constructor(...e){}}});function fc(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function pc(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Vp,Ms,wo,mc=X(()=>{Sn();At();Vp=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,oc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ms=w("$ZodError",Vp),wo=w("$ZodError",Vp,{Parent:Error})});var hc,gc,yc,_c,vc,Gr,xc,Xr,bc=X(()=>{Sn();mc();At();hc=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Wt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xt(c,s,ot())));throw As(a,o?.callee),a}return i.value},gc=hc(wo),yc=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xt(c,s,ot())));throw As(a,o?.callee),a}return i.value},_c=yc(wo),vc=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Wt;return s.issues.length?{success:!1,error:new(t??Ms)(s.issues.map(i=>xt(i,o,ot())))}:{success:!0,data:s.value}},Gr=vc(wo),xc=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>xt(i,o,ot())))}:{success:!0,data:s.value}},Xr=xc(wo)});function rm(){return new RegExp(Pw,"u")}function fm(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function pm(t){return new RegExp(`^${fm(t)}$`)}function mm(t){let e=fm({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${lm}T(?:${n})$`)}var Jp,Kp,Wp,Gp,Xp,Yp,Qp,em,wc,tm,Pw,nm,om,sm,im,am,$c,cm,um,lm,dm,hm,gm,ym,_m,vm,xm,bm,Zs=X(()=>{Jp=/^[cC][^\s-]{8,}$/,Kp=/^[0-9a-z]+$/,Wp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gp=/^[0-9a-vA-V]{20}$/,Xp=/^[A-Za-z0-9]{27}$/,Yp=/^[a-zA-Z0-9_-]{21}$/,Qp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,em=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wc=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,tm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";nm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,om=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sm=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,im=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,am=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$c=/^[A-Za-z0-9_-]*$/,cm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,um=/^\+(?:[0-9]){6,14}[0-9]$/,lm="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",dm=new RegExp(`^${lm}$`);hm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},gm=/^\d+$/,ym=/^-?\d+(?:\.\d+)?/i,_m=/true|false/i,vm=/null/i,xm=/^[^A-Z]*$/,bm=/^[^a-z]*$/});var Re,wm,kc,Sc,$m,km,Sm,Tm,Em,$o,zm,Pm,Rm,Im,Cm,Om,Am,Ds=X(()=>{Sn();Zs();At();Re=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),wm={number:"number",bigint:"bigint",object:"date"},kc=w("$ZodCheckLessThan",(t,e)=>{Re.init(t,e);let r=wm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Sc=w("$ZodCheckGreaterThan",(t,e)=>{Re.init(t,e);let r=wm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),$m=w("$ZodCheckMultipleOf",(t,e)=>{Re.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):sc(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),km=w("$ZodCheckNumberFormat",(t,e)=>{Re.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=lc[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=gm)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Sm=w("$ZodCheckMaxLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=bo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Tm=w("$ZodCheckMinLength",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=bo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Em=w("$ZodCheckLengthEquals",(t,e)=>{var r;Re.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=bo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$o=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Re.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),zm=w("$ZodCheckRegex",(t,e)=>{$o.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Pm=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=xm),$o.init(t,e)}),Rm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=bm),$o.init(t,e)}),Im=w("$ZodCheckIncludes",(t,e)=>{Re.init(t,e);let r=lr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Cm=w("$ZodCheckStartsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`^${lr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Om=w("$ZodCheckEndsWith",(t,e)=>{Re.init(t,e);let r=new RegExp(`.*${lr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Am=w("$ZodCheckOverwrite",(t,e)=>{Re.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ls,Tc=X(()=>{Ls=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
4
4
|
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
|
|
5
|
-
`))}}});var
|
|
6
|
-
if (${
|
|
5
|
+
`))}}});var Mm,Ec=X(()=>{Mm={major:4,minor:0,patch:0}});function Gm(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Rw(t){if(!$c.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gm(r)}function Iw(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function jm(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function qs(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function Zm(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Ot(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Dm(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>xt(s,n,ot())))}),e}function zc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(En(t)&&En(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=zc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=zc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Lm(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Wr(t))return t;let n=zc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function qm(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Fm(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Um(t,e,r){return Wr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Hm(t){return t.value=Object.freeze(t.value),t}function Bm(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(dc(o))}}var ue,ko,pe,Pc,Rc,Ic,Cc,Oc,Ac,Nc,Mc,jc,Zc,Dc,Vm,Jm,Km,Wm,Lc,qc,Fc,Uc,Hc,Bc,Vc,Jc,Fs,Kc,Wc,Gc,Xc,Yc,Qc,Us,Hs,eu,tu,ru,nu,ou,su,iu,au,cu,uu,lu,du,fu,pu,mu,Xm=X(()=>{Ds();Sn();Tc();bc();Zs();At();Ec();At();ue=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mm;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Wr(s),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let l=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Wt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==l&&(c||(c=Wr(s,l)))});else{if(s.issues.length===l)continue;c||(c=Wr(s,l))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Wt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Gr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Xr(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ko=w("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??hm(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),pe=w("$ZodStringFormat",(t,e)=>{$o.init(t,e),ko.init(t,e)}),Pc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=em),pe.init(t,e)}),Rc=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=wc(n))}else e.pattern??(e.pattern=wc());pe.init(t,e)}),Ic=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=tm),pe.init(t,e)}),Cc=w("$ZodURL",(t,e)=>{pe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:cm.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Oc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=rm()),pe.init(t,e)}),Ac=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Yp),pe.init(t,e)}),Nc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Jp),pe.init(t,e)}),Mc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Kp),pe.init(t,e)}),jc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Wp),pe.init(t,e)}),Zc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Gp),pe.init(t,e)}),Dc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Xp),pe.init(t,e)}),Vm=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mm(e)),pe.init(t,e)}),Jm=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=dm),pe.init(t,e)}),Km=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=pm(e)),pe.init(t,e)}),Wm=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Qp),pe.init(t,e)}),Lc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=nm),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),qc=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=om),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Fc=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sm),pe.init(t,e)}),Uc=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=im),pe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Hc=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=am),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Gm(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Bc=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=$c),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Rw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Vc=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=um),pe.init(t,e)});Jc=w("$ZodJWT",(t,e)=>{pe.init(t,e),t._zod.check=r=>{Iw(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Fs=w("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??ym,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Kc=w("$ZodNumber",(t,e)=>{km.init(t,e),Fs.init(t,e)}),Wc=w("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=_m,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Gc=w("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=vm,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Xc=w("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),Yc=w("$ZodNever",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Qc=w("$ZodArray",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>jm(u,r,i))):jm(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Us=w("$ZodObject",(t,e)=>{ue.init(t,e);let r=_o(()=>{let l=Object.keys(e.shape);for(let m of l)if(!(e.shape[m]instanceof ue))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=uc(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(p)}});fe(t._zod,"propValues",()=>{let l=e.shape,p={};for(let m in l){let f=l[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(let h of f.values)p[m].add(h)}}return p});let n=l=>{let p=new Ls(["shape","payload","ctx"]),m=r.value,f=v=>{let y=Kr(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of m.keys)h[v]=`key_${g++}`;p.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let y=h[v];p.write(`const ${y} = ${f(v)};`);let x=Kr(v);p.write(`
|
|
6
|
+
if (${y}.issues.length) {
|
|
7
7
|
if (input[${x}] === undefined) {
|
|
8
8
|
if (${x} in input) {
|
|
9
9
|
newResult[${x}] = undefined;
|
|
10
10
|
}
|
|
11
11
|
} else {
|
|
12
12
|
payload.issues = payload.issues.concat(
|
|
13
|
-
${
|
|
13
|
+
${y}.issues.map((iss) => ({
|
|
14
14
|
...iss,
|
|
15
15
|
path: iss.path ? [${x}, ...iss.path] : [${x}],
|
|
16
16
|
}))
|
|
17
17
|
);
|
|
18
18
|
}
|
|
19
|
-
} else if (${
|
|
19
|
+
} else if (${y}.value === undefined) {
|
|
20
20
|
if (${x} in input) newResult[${x}] = undefined;
|
|
21
21
|
} else {
|
|
22
|
-
newResult[${x}] = ${
|
|
22
|
+
newResult[${x}] = ${y}.value;
|
|
23
23
|
}
|
|
24
|
-
`)}else{let
|
|
25
|
-
if (${
|
|
24
|
+
`)}else{let y=h[v];p.write(`const ${y} = ${f(v)};`),p.write(`
|
|
25
|
+
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
|
-
path: iss.path ? [${
|
|
28
|
-
})));`),p.write(`newResult[${Zr(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,g)=>_(d,v,g)},o,s=_n,i=!vs.jitless,c=i&&Na.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let g=l.shape;for(let x of l.keys){let $=g[x],D=$._zod.run({value:m[x],issues:[]},p),R=$._zod.optin==="optional"&&$._zod.optout==="optional";D instanceof Promise?f.push(D.then(ie=>R?tm(ie,d,x,m):zs(ie,d,x))):R?tm(D,d,x,m):zs(D,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],y=l.keySet,_=u._zod,v=_.def.type;for(let g of Object.keys(m)){if(y.has(g))continue;if(v==="never"){h.push(g);continue}let x=_.run({value:m[g],issues:[]},p);x instanceof Promise?f.push(x.then($=>zs($,d,g))):zs(x,d,g)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Is=w("$ZodUnion",(t,e)=>{ce.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>co(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>rm(i,r,t,n)):rm(s,r,t,n)}}),zc=w("$ZodDiscriminatedUnion",(t,e)=>{Is.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=io(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!_n(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Pc=w("$ZodIntersection",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>nm(r,c,u)):nm(r,s,i)}});Rc=w("$ZodRecord",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Tt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Tt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ht(u,n,tt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Tt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Tt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Ic=w("$ZodEnum",(t,e)=>{ce.init(t,e);let r=so(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ma.has(typeof n)).map(n=>typeof n=="string"?rr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Oc=w("$ZodLiteral",(t,e)=>{ce.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Cc=w("$ZodTransform",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ut;return r.value=o,r}}),Ac=w("$ZodOptional",(t,e)=>{ce.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Nc=w("$ZodNullable",(t,e)=>{ce.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${co(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Mc=w("$ZodDefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>om(s,e)):om(o,e)}});jc=w("$ZodPrefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Zc=w("$ZodNonOptional",(t,e)=>{ce.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sm(s,t)):sm(o,t)}});Dc=w("$ZodCatch",(t,e)=>{ce.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ht(i,n,tt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ht(s,n,tt()))},input:r.value}),r.issues=[]),r)}}),qc=w("$ZodPipe",(t,e)=>{ce.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>im(s,e,n)):im(o,e,n)}});Lc=w("$ZodReadonly",(t,e)=>{ce.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(am):am(o)}});Uc=w("$ZodCustom",(t,e)=>{Re.init(t,e),ce.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>cm(s,r,n,t));cm(o,r,n,t)}})});function hm(){return{localeError:vb()}}var _b,vb,gm=G(()=>{zt();_b=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},vb=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${_b(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ws(n.values[0])}`:`Invalid option: expected one of ${xs(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${xs(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Os=G(()=>{});function ym(){return new mo}var xb,bb,mo,nr,Hc=G(()=>{xb=Symbol("ZodOutput"),bb=Symbol("ZodInput"),mo=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};nr=ym()});function Vc(t,e){return new t({type:"string",...j(e)})}function Bc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Cs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Jc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Wc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Kc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Gc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Xc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Yc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Qc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function eu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function tu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function ru(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function nu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function ou(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function su(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function iu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function au(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function cu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function uu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function lu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function du(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function fu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function _m(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function vm(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function xm(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function bm(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function pu(t,e){return new t({type:"number",checks:[],...j(e)})}function mu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function hu(t,e){return new t({type:"boolean",...j(e)})}function gu(t,e){return new t({type:"null",...j(e)})}function yu(t){return new t({type:"unknown"})}function _u(t,e){return new t({type:"never",...j(e)})}function As(t,e){return new Ya({check:"less_than",...j(e),value:t,inclusive:!1})}function ho(t,e){return new Ya({check:"less_than",...j(e),value:t,inclusive:!0})}function Ns(t,e){return new Qa({check:"greater_than",...j(e),value:t,inclusive:!1})}function go(t,e){return new Qa({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ms(t,e){return new qp({check:"multiple_of",...j(e),value:t})}function js(t,e){return new Up({check:"max_length",...j(e),maximum:t})}function xn(t,e){return new Fp({check:"min_length",...j(e),minimum:t})}function Zs(t,e){return new Hp({check:"length_equals",...j(e),length:t})}function vu(t,e){return new Vp({check:"string_format",format:"regex",...j(e),pattern:t})}function xu(t){return new Bp({check:"string_format",format:"lowercase",...j(t)})}function bu(t){return new Jp({check:"string_format",format:"uppercase",...j(t)})}function wu(t,e){return new Wp({check:"string_format",format:"includes",...j(e),includes:t})}function $u(t,e){return new Kp({check:"string_format",format:"starts_with",...j(e),prefix:t})}function ku(t,e){return new Gp({check:"string_format",format:"ends_with",...j(e),suffix:t})}function Ur(t){return new Xp({check:"overwrite",tx:t})}function Su(t){return Ur(e=>e.normalize(t))}function Eu(){return Ur(t=>t.trim())}function Tu(){return Ur(t=>t.toLowerCase())}function zu(){return Ur(t=>t.toUpperCase())}function wm(t,e,r){return new t({type:"array",element:e,...j(r)})}function Pu(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Ru(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}var $m=G(()=>{Es();zt()});var km=G(()=>{});function Iu(t,e){if(t instanceof mo){let n=new Ds(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Ds(e);return r.process(t),r.emit(t,e)}function Se(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Se(o.element,r);case"object":{for(let s in o.shape)if(Se(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Se(s,r))return!0;return!1}case"intersection":return Se(o.left,r)||Se(o.right,r);case"tuple":{for(let s of o.items)if(Se(s,r))return!0;return!!(o.rest&&Se(o.rest,r))}case"record":return Se(o.keyType,r)||Se(o.valueType,r);case"map":return Se(o.keyType,r)||Se(o.valueType,r);case"set":return Se(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Se(o.innerType,r);case"lazy":return Se(o.getter(),r);case"default":return Se(o.innerType,r);case"prefault":return Se(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Se(o.in,r)||Se(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ds,Sm=G(()=>{Hc();zt();Ds=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:y,format:_,patterns:v,contentEncoding:g}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof y=="number"&&(f.maxLength=y),_&&(f.format=s[_]??_,f.format===""&&delete f.format),g&&(f.contentEncoding=g),v&&v.size>0){let x=[...v];x.length===1?f.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{let f=m,{minimum:h,maximum:y,format:_,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof h=="number"&&(f.minimum=h,typeof x=="number"&&(x>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof y=="number"&&(f.maximum=y,typeof g=="number"&&(g<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:y}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let v in h)f.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let y=new Set(Object.keys(h)),_=new Set([...y].filter(v=>{let g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));_.size>0&&(f.required=Array.from(_)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,y)=>this.process(h,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{let f=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),y=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=g=>"allOf"in g&&Object.keys(g).length===1,v=[..._(h)?h.allOf:[h],..._(y)?y.allOf:[y]];f.allOf=v;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((v,g)=>this.process(v,{...d,path:[...d.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=so(o.entries);h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];f.type=y===null?"null":typeof y,f.const=y}else h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),h.every(y=>typeof y=="boolean")&&(f.type="string"),h.every(y=>y===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:v}=e._zod.bag;y!==void 0&&(h.minLength=y),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(f,h)):f.anyOf=v.map(g=>({...h,contentMediaType:g})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Se(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,y=n.external.uri??(v=>v);if(h)return{ref:y(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${y("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let h in f)delete f[h];f.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
27
|
+
path: iss.path ? [${Kr(v)}, ...iss.path] : [${Kr(v)}]
|
|
28
|
+
})));`),p.write(`newResult[${Kr(v)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(v,y)=>_(l,v,y)},o,s=Tn,i=!Cs.jitless,c=i&&ac.value,u=e.catchall,d;t._zod.parse=(l,p)=>{d??(d=r.value);let m=l.value;if(!s(m))return l.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),l;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),l=o(l,p);else{l.value={};let y=d.shape;for(let x of d.keys){let $=y[x],C=$._zod.run({value:m[x],issues:[]},p),R=$._zod.optin==="optional"&&$._zod.optout==="optional";C instanceof Promise?f.push(C.then(ae=>R?Zm(ae,l,x,m):qs(ae,l,x))):R?Zm(C,l,x,m):qs(C,l,x)}}if(!u)return f.length?Promise.all(f).then(()=>l):l;let h=[],g=d.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(m)){if(g.has(y))continue;if(v==="never"){h.push(y);continue}let x=_.run({value:m[y],issues:[]},p);x instanceof Promise?f.push(x.then($=>qs($,l,y))):qs(x,l,y)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>l):l}});Hs=w("$ZodUnion",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),fe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>xo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Dm(i,r,t,n)):Dm(s,r,t,n)}}),eu=w("$ZodDiscriminatedUnion",(t,e)=>{Hs.init(t,e);let r=t._zod.parse;fe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=_o(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Tn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),tu=w("$ZodIntersection",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Lm(r,c,u)):Lm(r,s,i)}});ru=w("$ZodRecord",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!En(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Ot(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Ot(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>xt(u,n,ot())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Ot(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Ot(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),nu=w("$ZodEnum",(t,e)=>{ue.init(t,e);let r=yo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>cc.has(typeof n)).map(n=>typeof n=="string"?lr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),ou=w("$ZodLiteral",(t,e)=>{ue.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?lr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),su=w("$ZodTransform",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Wt;return r.value=o,r}}),iu=w("$ZodOptional",(t,e)=>{ue.init(t,e),t._zod.optin="optional",t._zod.optout="optional",fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${xo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),au=w("$ZodNullable",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${xo(r.source)}|null)$`):void 0}),fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),cu=w("$ZodDefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>qm(s,e)):qm(o,e)}});uu=w("$ZodPrefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),lu=w("$ZodNonOptional",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Fm(s,t)):Fm(o,t)}});du=w("$ZodCatch",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>xt(i,n,ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>xt(s,n,ot()))},input:r.value}),r.issues=[]),r)}}),fu=w("$ZodPipe",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>e.in._zod.values),fe(t._zod,"optin",()=>e.in._zod.optin),fe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Um(s,e,n)):Um(o,e,n)}});pu=w("$ZodReadonly",(t,e)=>{ue.init(t,e),fe(t._zod,"propValues",()=>e.innerType._zod.propValues),fe(t._zod,"values",()=>e.innerType._zod.values),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Hm):Hm(o)}});mu=w("$ZodCustom",(t,e)=>{Re.init(t,e),ue.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Bm(s,r,n,t));Bm(o,r,n,t)}})});function Ym(){return{localeError:Ow()}}var Cw,Ow,Qm=X(()=>{At();Cw=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Ow=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Cw(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ns(n.values[0])}`:`Invalid option: expected one of ${Os(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Os(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Bs=X(()=>{});function eh(){return new So}var Aw,Nw,So,dr,gu=X(()=>{Aw=Symbol("ZodOutput"),Nw=Symbol("ZodInput"),So=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};dr=eh()});function yu(t,e){return new t({type:"string",...L(e)})}function _u(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...L(e)})}function Vs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...L(e)})}function vu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...L(e)})}function xu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(e)})}function bu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(e)})}function wu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(e)})}function $u(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...L(e)})}function ku(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...L(e)})}function Su(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(e)})}function Tu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...L(e)})}function Eu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(e)})}function zu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...L(e)})}function Pu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...L(e)})}function Ru(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(e)})}function Iu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(e)})}function Cu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(e)})}function Ou(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(e)})}function Au(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(e)})}function Nu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...L(e)})}function Mu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...L(e)})}function ju(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...L(e)})}function Zu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...L(e)})}function th(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(e)})}function rh(t,e){return new t({type:"string",format:"date",check:"string_format",...L(e)})}function nh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...L(e)})}function oh(t,e){return new t({type:"string",format:"duration",check:"string_format",...L(e)})}function Du(t,e){return new t({type:"number",checks:[],...L(e)})}function Lu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...L(e)})}function qu(t,e){return new t({type:"boolean",...L(e)})}function Fu(t,e){return new t({type:"null",...L(e)})}function Uu(t){return new t({type:"unknown"})}function Hu(t,e){return new t({type:"never",...L(e)})}function Js(t,e){return new kc({check:"less_than",...L(e),value:t,inclusive:!1})}function To(t,e){return new kc({check:"less_than",...L(e),value:t,inclusive:!0})}function Ks(t,e){return new Sc({check:"greater_than",...L(e),value:t,inclusive:!1})}function Eo(t,e){return new Sc({check:"greater_than",...L(e),value:t,inclusive:!0})}function Ws(t,e){return new $m({check:"multiple_of",...L(e),value:t})}function Gs(t,e){return new Sm({check:"max_length",...L(e),maximum:t})}function zn(t,e){return new Tm({check:"min_length",...L(e),minimum:t})}function Xs(t,e){return new Em({check:"length_equals",...L(e),length:t})}function Bu(t,e){return new zm({check:"string_format",format:"regex",...L(e),pattern:t})}function Vu(t){return new Pm({check:"string_format",format:"lowercase",...L(t)})}function Ju(t){return new Rm({check:"string_format",format:"uppercase",...L(t)})}function Ku(t,e){return new Im({check:"string_format",format:"includes",...L(e),includes:t})}function Wu(t,e){return new Cm({check:"string_format",format:"starts_with",...L(e),prefix:t})}function Gu(t,e){return new Om({check:"string_format",format:"ends_with",...L(e),suffix:t})}function Yr(t){return new Am({check:"overwrite",tx:t})}function Xu(t){return Yr(e=>e.normalize(t))}function Yu(){return Yr(t=>t.trim())}function Qu(){return Yr(t=>t.toLowerCase())}function el(){return Yr(t=>t.toUpperCase())}function sh(t,e,r){return new t({type:"array",element:e,...L(r)})}function tl(t,e,r){let n=L(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function rl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...L(r)})}var ih=X(()=>{Ds();At()});var ah=X(()=>{});function nl(t,e){if(t instanceof So){let n=new Ys(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Ys(e);return r.process(t),r.emit(t,e)}function Se(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Se(o.element,r);case"object":{for(let s in o.shape)if(Se(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Se(s,r))return!0;return!1}case"intersection":return Se(o.left,r)||Se(o.right,r);case"tuple":{for(let s of o.items)if(Se(s,r))return!0;return!!(o.rest&&Se(o.rest,r))}case"record":return Se(o.keyType,r)||Se(o.valueType,r);case"map":return Se(o.keyType,r)||Se(o.valueType,r);case"set":return Se(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Se(o.innerType,r);case"lazy":return Se(o.getter(),r);case"default":return Se(o.innerType,r);case"prefault":return Se(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Se(o.in,r)||Se(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ys,ch=X(()=>{gu();At();Ys=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??dr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,l),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:g,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof g=="number"&&(f.maxLength=g),_&&(f.format=s[_]??_,f.format===""&&delete f.format),y&&(f.contentEncoding=y),v&&v.size>0){let x=[...v];x.length===1?f.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{let f=m,{minimum:h,maximum:g,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof h=="number"&&(f.minimum=h,typeof x=="number"&&(x>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof g=="number"&&(f.maximum=g,typeof y=="number"&&(y<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(o.element,{...l,path:[...l.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let v in h)f.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),_=new Set([...g].filter(v=>{let y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));_.size>0&&(f.required=Array.from(_)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let f=m,h=this.process(o.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(o.right,{...l,path:[...l.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(h)?h.allOf:[h],..._(g)?g.allOf:[g]];f.allOf=v;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((v,y)=>this.process(v,{...l,path:[...l.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let v=this.process(o.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...l,path:[...l.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=yo(o.entries);h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];f.type=g===null?"null":typeof g,f.const=g}else h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),h.every(g=>typeof g=="boolean")&&(f.type="string"),h.every(g=>g===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:_,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),_!==void 0&&(h.maxLength=_),v?v.length===1?(h.contentMediaType=v[0],Object.assign(f,h)):f.anyOf=v.map(y=>({...h,contentMediaType:y})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,l);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,l),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,l),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,l),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,l),a.ref=f;break}case"readonly":{this.process(o.innerType,l),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,l),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,l),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Se(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let _=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=_,{defId:_,ref:`${g("__shared")}#/${l}/${_}`}}if(d[1]===o)return{ref:"#"};let m=`#/${l}/`,f=d[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:p,defId:m}=s(d);l.def={...l.schema},m&&(l.defId=m);let f=l.schema;for(let h in f)delete f[h];f.$ref=p};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
29
29
|
|
|
30
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(y)):(Object.assign(m,y),Object.assign(m,f))}p.isParent||this.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Em=G(()=>{});var qe=G(()=>{yn();Ka();Ua();mm();Es();tc();zt();Ss();Os();Hc();ec();km();$m();Sm();Em()});var Cu=G(()=>{qe()});var yo={};eo(yo,{ZodISODate:()=>Rm,ZodISODateTime:()=>Pm,ZodISODuration:()=>Om,ZodISOTime:()=>Im,date:()=>Nu,datetime:()=>Au,duration:()=>ju,time:()=>Mu});function Au(t){return _m(Pm,t)}function Nu(t){return vm(Rm,t)}function Mu(t){return xm(Im,t)}function ju(t){return bm(Om,t)}var Pm,Rm,Im,Om,Zu=G(()=>{qe();Du();Pm=w("ZodISODateTime",(t,e)=>{um.init(t,e),ve.init(t,e)});Rm=w("ZodISODate",(t,e)=>{lm.init(t,e),ve.init(t,e)});Im=w("ZodISOTime",(t,e)=>{dm.init(t,e),ve.init(t,e)});Om=w("ZodISODuration",(t,e)=>{fm.init(t,e),ve.init(t,e)})});var Cm,PA,_o,qu=G(()=>{qe();qe();Cm=(t,e)=>{$s.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>La(t,r)},flatten:{value:r=>qa(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},PA=w("ZodError",Cm),_o=w("ZodError",Cm,{Parent:Error})});var Am,Nm,Mm,jm,Lu=G(()=>{qe();qu();Am=Fa(_o),Nm=Va(_o),Mm=Ja(_o),jm=Wa(_o)});function b(t){return Vc(pw,t)}function se(t){return pu(Um,t)}function Dm(t){return mu(Iw,t)}function ze(t){return hu(Ow,t)}function Fm(t){return gu(Cw,t)}function xe(){return yu(Aw)}function Mw(t){return _u(Nw,t)}function Y(t,e){return wm(jw,t,e)}function P(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new Hm(r)}function Le(t,e){return new Hm({type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...X.normalizeParams(e)})}function he(t,e){return new Vm({type:"union",options:t,...X.normalizeParams(e)})}function Hu(t,e,r){return new Zw({type:"union",options:e,discriminator:t,...X.normalizeParams(r)})}function Fs(t,e){return new Dw({type:"intersection",left:t,right:e})}function pe(t,e,r){return new qw({type:"record",keyType:t,valueType:e,...X.normalizeParams(r)})}function We(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Uu({type:"enum",entries:r,...X.normalizeParams(e)})}function C(t,e){return new Lw({type:"literal",values:Array.isArray(t)?t:[t],...X.normalizeParams(e)})}function Bm(t){return new Uw({type:"transform",transform:t})}function be(t){return new Jm({type:"optional",innerType:t})}function qm(t){return new Fw({type:"nullable",innerType:t})}function Vw(t,e){return new Hw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Jw(t,e){return new Bw({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Ww(t,e){return new Wm({type:"nonoptional",innerType:t,...X.normalizeParams(e)})}function Gw(t,e){return new Kw({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Fu(t,e){return new Xw({type:"pipe",in:t,out:e})}function Qw(t){return new Yw({type:"readonly",innerType:t})}function e$(t){let e=new Re({check:"custom"});return e._zod.check=t,e}function Gm(t,e){return Pu(Km,t??(()=>!0),e)}function t$(t,e={}){return Ru(Km,t,e)}function r$(t){let e=e$(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(X.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(X.issue(o))}},t(r.value,r)));return e}function Vu(t,e){return Fu(Bm(t),e)}var $e,Lm,pw,ve,mw,Zm,Us,hw,gw,yw,_w,vw,xw,bw,ww,$w,kw,Sw,Ew,Tw,zw,Pw,Rw,Um,Iw,Ow,Cw,Aw,Nw,jw,Hm,Vm,Zw,Dw,qw,Uu,Lw,Uw,Jm,Fw,Hw,Bw,Wm,Kw,Xw,Yw,Km,Du=G(()=>{qe();qe();Cu();Zu();Lu();$e=w("ZodType",(t,e)=>(ce.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Am(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Mm(t,r,n),t.parseAsync=async(r,n)=>Nm(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>jm(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(t$(r,n)),t.superRefine=r=>t.check(r$(r)),t.overwrite=r=>t.check(Ur(r)),t.optional=()=>be(t),t.nullable=()=>qm(t),t.nullish=()=>be(qm(t)),t.nonoptional=r=>Ww(t,r),t.array=()=>Y(t),t.or=r=>he([t,r]),t.and=r=>Fs(t,r),t.transform=r=>Fu(t,Bm(r)),t.default=r=>Vw(t,r),t.prefault=r=>Jw(t,r),t.catch=r=>Gw(t,r),t.pipe=r=>Fu(t,r),t.readonly=()=>Qw(t),t.describe=r=>{let n=t.clone();return nr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nr.get(t);let n=t.clone();return nr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Lm=w("_ZodString",(t,e)=>{po.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(vu(...n)),t.includes=(...n)=>t.check(wu(...n)),t.startsWith=(...n)=>t.check($u(...n)),t.endsWith=(...n)=>t.check(ku(...n)),t.min=(...n)=>t.check(xn(...n)),t.max=(...n)=>t.check(js(...n)),t.length=(...n)=>t.check(Zs(...n)),t.nonempty=(...n)=>t.check(xn(1,...n)),t.lowercase=n=>t.check(xu(n)),t.uppercase=n=>t.check(bu(n)),t.trim=()=>t.check(Eu()),t.normalize=(...n)=>t.check(Su(...n)),t.toLowerCase=()=>t.check(Tu()),t.toUpperCase=()=>t.check(zu())}),pw=w("ZodString",(t,e)=>{po.init(t,e),Lm.init(t,e),t.email=r=>t.check(Bc(mw,r)),t.url=r=>t.check(Xc(hw,r)),t.jwt=r=>t.check(fu(Rw,r)),t.emoji=r=>t.check(Yc(gw,r)),t.guid=r=>t.check(Cs(Zm,r)),t.uuid=r=>t.check(Jc(Us,r)),t.uuidv4=r=>t.check(Wc(Us,r)),t.uuidv6=r=>t.check(Kc(Us,r)),t.uuidv7=r=>t.check(Gc(Us,r)),t.nanoid=r=>t.check(Qc(yw,r)),t.guid=r=>t.check(Cs(Zm,r)),t.cuid=r=>t.check(eu(_w,r)),t.cuid2=r=>t.check(tu(vw,r)),t.ulid=r=>t.check(ru(xw,r)),t.base64=r=>t.check(uu(Tw,r)),t.base64url=r=>t.check(lu(zw,r)),t.xid=r=>t.check(nu(bw,r)),t.ksuid=r=>t.check(ou(ww,r)),t.ipv4=r=>t.check(su($w,r)),t.ipv6=r=>t.check(iu(kw,r)),t.cidrv4=r=>t.check(au(Sw,r)),t.cidrv6=r=>t.check(cu(Ew,r)),t.e164=r=>t.check(du(Pw,r)),t.datetime=r=>t.check(Au(r)),t.date=r=>t.check(Nu(r)),t.time=r=>t.check(Mu(r)),t.duration=r=>t.check(ju(r))});ve=w("ZodStringFormat",(t,e)=>{fe.init(t,e),Lm.init(t,e)}),mw=w("ZodEmail",(t,e)=>{sc.init(t,e),ve.init(t,e)}),Zm=w("ZodGUID",(t,e)=>{nc.init(t,e),ve.init(t,e)}),Us=w("ZodUUID",(t,e)=>{oc.init(t,e),ve.init(t,e)}),hw=w("ZodURL",(t,e)=>{ic.init(t,e),ve.init(t,e)}),gw=w("ZodEmoji",(t,e)=>{ac.init(t,e),ve.init(t,e)}),yw=w("ZodNanoID",(t,e)=>{cc.init(t,e),ve.init(t,e)}),_w=w("ZodCUID",(t,e)=>{uc.init(t,e),ve.init(t,e)}),vw=w("ZodCUID2",(t,e)=>{lc.init(t,e),ve.init(t,e)}),xw=w("ZodULID",(t,e)=>{dc.init(t,e),ve.init(t,e)}),bw=w("ZodXID",(t,e)=>{fc.init(t,e),ve.init(t,e)}),ww=w("ZodKSUID",(t,e)=>{pc.init(t,e),ve.init(t,e)}),$w=w("ZodIPv4",(t,e)=>{mc.init(t,e),ve.init(t,e)}),kw=w("ZodIPv6",(t,e)=>{hc.init(t,e),ve.init(t,e)}),Sw=w("ZodCIDRv4",(t,e)=>{gc.init(t,e),ve.init(t,e)}),Ew=w("ZodCIDRv6",(t,e)=>{yc.init(t,e),ve.init(t,e)}),Tw=w("ZodBase64",(t,e)=>{_c.init(t,e),ve.init(t,e)}),zw=w("ZodBase64URL",(t,e)=>{vc.init(t,e),ve.init(t,e)}),Pw=w("ZodE164",(t,e)=>{xc.init(t,e),ve.init(t,e)}),Rw=w("ZodJWT",(t,e)=>{bc.init(t,e),ve.init(t,e)}),Um=w("ZodNumber",(t,e)=>{Ps.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(Ns(n,o)),t.gte=(n,o)=>t.check(go(n,o)),t.min=(n,o)=>t.check(go(n,o)),t.lt=(n,o)=>t.check(As(n,o)),t.lte=(n,o)=>t.check(ho(n,o)),t.max=(n,o)=>t.check(ho(n,o)),t.int=n=>t.check(Dm(n)),t.safe=n=>t.check(Dm(n)),t.positive=n=>t.check(Ns(0,n)),t.nonnegative=n=>t.check(go(0,n)),t.negative=n=>t.check(As(0,n)),t.nonpositive=n=>t.check(ho(0,n)),t.multipleOf=(n,o)=>t.check(Ms(n,o)),t.step=(n,o)=>t.check(Ms(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});Iw=w("ZodNumberFormat",(t,e)=>{wc.init(t,e),Um.init(t,e)});Ow=w("ZodBoolean",(t,e)=>{$c.init(t,e),$e.init(t,e)});Cw=w("ZodNull",(t,e)=>{kc.init(t,e),$e.init(t,e)});Aw=w("ZodUnknown",(t,e)=>{Sc.init(t,e),$e.init(t,e)});Nw=w("ZodNever",(t,e)=>{Ec.init(t,e),$e.init(t,e)});jw=w("ZodArray",(t,e)=>{Tc.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xn(r,n)),t.nonempty=r=>t.check(xn(1,r)),t.max=(r,n)=>t.check(js(r,n)),t.length=(r,n)=>t.check(Zs(r,n)),t.unwrap=()=>t.element});Hm=w("ZodObject",(t,e)=>{Rs.init(t,e),$e.init(t,e),X.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>We(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xe()}),t.loose=()=>t.clone({...t._zod.def,catchall:xe()}),t.strict=()=>t.clone({...t._zod.def,catchall:Mw()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>X.extend(t,r),t.merge=r=>X.merge(t,r),t.pick=r=>X.pick(t,r),t.omit=r=>X.omit(t,r),t.partial=(...r)=>X.partial(Jm,t,r[0]),t.required=(...r)=>X.required(Wm,t,r[0])});Vm=w("ZodUnion",(t,e)=>{Is.init(t,e),$e.init(t,e),t.options=e.options});Zw=w("ZodDiscriminatedUnion",(t,e)=>{Vm.init(t,e),zc.init(t,e)});Dw=w("ZodIntersection",(t,e)=>{Pc.init(t,e),$e.init(t,e)});qw=w("ZodRecord",(t,e)=>{Rc.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Uu=w("ZodEnum",(t,e)=>{Ic.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Uu({...e,checks:[],...X.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Uu({...e,checks:[],...X.normalizeParams(o),entries:s})}});Lw=w("ZodLiteral",(t,e)=>{Oc.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Uw=w("ZodTransform",(t,e)=>{Cc.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(X.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(X.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Jm=w("ZodOptional",(t,e)=>{Ac.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Fw=w("ZodNullable",(t,e)=>{Nc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Hw=w("ZodDefault",(t,e)=>{Mc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Bw=w("ZodPrefault",(t,e)=>{jc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Wm=w("ZodNonOptional",(t,e)=>{Zc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Kw=w("ZodCatch",(t,e)=>{Dc.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Xw=w("ZodPipe",(t,e)=>{qc.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});Yw=w("ZodReadonly",(t,e)=>{Lc.init(t,e),$e.init(t,e)});Km=w("ZodCustom",(t,e)=>{Uc.init(t,e),$e.init(t,e)})});var Xm=G(()=>{});var Ym=G(()=>{});var Qm=G(()=>{qe();Du();Cu();qu();Lu();Xm();qe();gm();Os();Zu();Ym();tt(hm())});var eh=G(()=>{Qm()});var th=G(()=>{eh()});function gh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function yh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ju,rh,kn,ir,Vs,Ee,nh,oh,VA,s$,i$,Wu,nt,vo,sh,Ie,it,at,Oe,Bs,ih,Ft,ah,ch,Ku,Ht,N,Gu,Sn,xo,BA,Js,a$,Ws,c$,bo,$n,uh,u$,l$,d$,f$,p$,m$,Ks,Xu,h$,g$,Yu,Gs,y$,_$,Xs,v$,wo,$o,x$,ko,En,b$,So,Ys,Qs,ei,JA,ti,ri,ni,lh,dh,fh,Qu,ph,Eo,Tn,mh,w$,oi,$$,si,k$,el,S$,ii,E$,T$,z$,P$,R$,I$,O$,C$,A$,N$,ai,M$,j$,ci,tl,rl,nl,Z$,D$,q$,ol,L$,U$,F$,H$,V$,hh,ui,B$,li,WA,J$,zn,W$,KA,To,K$,sl,G$,X$,Y$,Q$,ek,tk,rk,Hs,nk,ok,sk,zo,il,ik,ak,ck,uk,lk,dk,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,$k,Pn,kk,Sk,Ek,di,Tk,zk,Pk,al,Rk,GA,XA,YA,QA,eN,tN,O,Bu,Vr=G(()=>{th();Ju="2025-11-25",rh="2025-03-26",kn=[Ju,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ir="io.modelcontextprotocol/related-task",Vs="2.0",Ee=Gm(t=>t!==null&&(typeof t=="object"||typeof t=="function")),nh=he([b(),se().int()]),oh=b(),VA=Le({ttl:se().optional(),pollInterval:se().optional()}),s$=P({ttl:se().optional()}),i$=P({taskId:b()}),Wu=Le({progressToken:nh.optional(),[ir]:i$.optional()}),nt=P({_meta:Wu.optional()}),vo=nt.extend({task:s$.optional()}),sh=t=>vo.safeParse(t).success,Ie=P({method:b(),params:nt.loose().optional()}),it=P({_meta:Wu.optional()}),at=P({method:b(),params:it.loose().optional()}),Oe=Le({_meta:Wu.optional()}),Bs=he([b(),se().int()]),ih=P({jsonrpc:C(Vs),id:Bs,...Ie.shape}).strict(),Ft=t=>ih.safeParse(t).success,ah=P({jsonrpc:C(Vs),...at.shape}).strict(),ch=t=>ah.safeParse(t).success,Ku=P({jsonrpc:C(Vs),id:Bs,result:Oe}).strict(),Ht=t=>Ku.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));Gu=P({jsonrpc:C(Vs),id:Bs.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),Sn=t=>Gu.safeParse(t).success,xo=he([ih,ah,Ku,Gu]),BA=he([Ku,Gu]),Js=Oe.strict(),a$=it.extend({requestId:Bs.optional(),reason:b().optional()}),Ws=at.extend({method:C("notifications/cancelled"),params:a$}),c$=P({src:b(),mimeType:b().optional(),sizes:Y(b()).optional(),theme:We(["light","dark"]).optional()}),bo=P({icons:Y(c$).optional()}),$n=P({name:b(),title:b().optional()}),uh=$n.extend({...$n.shape,...bo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),u$=Fs(P({applyDefaults:ze().optional()}),pe(b(),xe())),l$=Vu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Fs(P({form:u$.optional(),url:Ee.optional()}),pe(b(),xe()).optional())),d$=Le({list:Ee.optional(),cancel:Ee.optional(),requests:Le({sampling:Le({createMessage:Ee.optional()}).optional(),elicitation:Le({create:Ee.optional()}).optional()}).optional()}),f$=Le({list:Ee.optional(),cancel:Ee.optional(),requests:Le({tools:Le({call:Ee.optional()}).optional()}).optional()}),p$=P({experimental:pe(b(),Ee).optional(),sampling:P({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:l$.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:d$.optional(),extensions:pe(b(),Ee).optional()}),m$=nt.extend({protocolVersion:b(),capabilities:p$,clientInfo:uh}),Ks=Ie.extend({method:C("initialize"),params:m$}),Xu=t=>Ks.safeParse(t).success,h$=P({experimental:pe(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:f$.optional(),extensions:pe(b(),Ee).optional()}),g$=Oe.extend({protocolVersion:b(),capabilities:h$,serverInfo:uh,instructions:b().optional()}),Yu=at.extend({method:C("notifications/initialized"),params:it.optional()}),Gs=Ie.extend({method:C("ping"),params:nt.optional()}),y$=P({progress:se(),total:be(se()),message:be(b())}),_$=P({...it.shape,...y$.shape,progressToken:nh}),Xs=at.extend({method:C("notifications/progress"),params:_$}),v$=nt.extend({cursor:oh.optional()}),wo=Ie.extend({params:v$.optional()}),$o=Oe.extend({nextCursor:oh.optional()}),x$=We(["working","input_required","completed","failed","cancelled"]),ko=P({taskId:b(),status:x$,ttl:he([se(),Fm()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),En=Oe.extend({task:ko}),b$=it.merge(ko),So=at.extend({method:C("notifications/tasks/status"),params:b$}),Ys=Ie.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Qs=Oe.merge(ko),ei=Ie.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),JA=Oe.loose(),ti=wo.extend({method:C("tasks/list")}),ri=$o.extend({tasks:Y(ko)}),ni=Ie.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),lh=Oe.merge(ko),dh=P({uri:b(),mimeType:be(b()),_meta:pe(b(),xe()).optional()}),fh=dh.extend({text:b()}),Qu=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ph=dh.extend({blob:Qu}),Eo=We(["user","assistant"]),Tn=P({audience:Y(Eo).optional(),priority:se().min(0).max(1).optional(),lastModified:yo.datetime({offset:!0}).optional()}),mh=P({...$n.shape,...bo.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Tn.optional(),_meta:be(Le({}))}),w$=P({...$n.shape,...bo.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Tn.optional(),_meta:be(Le({}))}),oi=wo.extend({method:C("resources/list")}),$$=$o.extend({resources:Y(mh)}),si=wo.extend({method:C("resources/templates/list")}),k$=$o.extend({resourceTemplates:Y(w$)}),el=nt.extend({uri:b()}),S$=el,ii=Ie.extend({method:C("resources/read"),params:S$}),E$=Oe.extend({contents:Y(he([fh,ph]))}),T$=at.extend({method:C("notifications/resources/list_changed"),params:it.optional()}),z$=el,P$=Ie.extend({method:C("resources/subscribe"),params:z$}),R$=el,I$=Ie.extend({method:C("resources/unsubscribe"),params:R$}),O$=it.extend({uri:b()}),C$=at.extend({method:C("notifications/resources/updated"),params:O$}),A$=P({name:b(),description:be(b()),required:be(ze())}),N$=P({...$n.shape,...bo.shape,description:be(b()),arguments:be(Y(A$)),_meta:be(Le({}))}),ai=wo.extend({method:C("prompts/list")}),M$=$o.extend({prompts:Y(N$)}),j$=nt.extend({name:b(),arguments:pe(b(),b()).optional()}),ci=Ie.extend({method:C("prompts/get"),params:j$}),tl=P({type:C("text"),text:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),rl=P({type:C("image"),data:Qu,mimeType:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),nl=P({type:C("audio"),data:Qu,mimeType:b(),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),Z$=P({type:C("tool_use"),name:b(),id:b(),input:pe(b(),xe()),_meta:pe(b(),xe()).optional()}),D$=P({type:C("resource"),resource:he([fh,ph]),annotations:Tn.optional(),_meta:pe(b(),xe()).optional()}),q$=mh.extend({type:C("resource_link")}),ol=he([tl,rl,nl,q$,D$]),L$=P({role:Eo,content:ol}),U$=Oe.extend({description:b().optional(),messages:Y(L$)}),F$=at.extend({method:C("notifications/prompts/list_changed"),params:it.optional()}),H$=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),V$=P({taskSupport:We(["required","optional","forbidden"]).optional()}),hh=P({...$n.shape,...bo.shape,description:b().optional(),inputSchema:P({type:C("object"),properties:pe(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()),outputSchema:P({type:C("object"),properties:pe(b(),Ee).optional(),required:Y(b()).optional()}).catchall(xe()).optional(),annotations:H$.optional(),execution:V$.optional(),_meta:pe(b(),xe()).optional()}),ui=wo.extend({method:C("tools/list")}),B$=$o.extend({tools:Y(hh)}),li=Oe.extend({content:Y(ol).default([]),structuredContent:pe(b(),xe()).optional(),isError:ze().optional()}),WA=li.or(Oe.extend({toolResult:xe()})),J$=vo.extend({name:b(),arguments:pe(b(),xe()).optional()}),zn=Ie.extend({method:C("tools/call"),params:J$}),W$=at.extend({method:C("notifications/tools/list_changed"),params:it.optional()}),KA=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),To=We(["debug","info","notice","warning","error","critical","alert","emergency"]),K$=nt.extend({level:To}),sl=Ie.extend({method:C("logging/setLevel"),params:K$}),G$=it.extend({level:To,logger:b().optional(),data:xe()}),X$=at.extend({method:C("notifications/message"),params:G$}),Y$=P({name:b().optional()}),Q$=P({hints:Y(Y$).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),ek=P({mode:We(["auto","required","none"]).optional()}),tk=P({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Y(ol).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:pe(b(),xe()).optional()}),rk=Hu("type",[tl,rl,nl]),Hs=Hu("type",[tl,rl,nl,Z$,tk]),nk=P({role:Eo,content:he([Hs,Y(Hs)]),_meta:pe(b(),xe()).optional()}),ok=vo.extend({messages:Y(nk),modelPreferences:Q$.optional(),systemPrompt:b().optional(),includeContext:We(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Y(b()).optional(),metadata:Ee.optional(),tools:Y(hh).optional(),toolChoice:ek.optional()}),sk=Ie.extend({method:C("sampling/createMessage"),params:ok}),zo=Oe.extend({model:b(),stopReason:be(We(["endTurn","stopSequence","maxTokens"]).or(b())),role:Eo,content:rk}),il=Oe.extend({model:b(),stopReason:be(We(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Eo,content:he([Hs,Y(Hs)])}),ik=P({type:C("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),ak=P({type:C("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:We(["email","uri","date","date-time"]).optional(),default:b().optional()}),ck=P({type:We(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),uk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),default:b().optional()}),lk=P({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Y(P({const:b(),title:b()})),default:b().optional()}),dk=P({type:C("string"),title:b().optional(),description:b().optional(),enum:Y(b()),enumNames:Y(b()).optional(),default:b().optional()}),fk=he([uk,lk]),pk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:C("string"),enum:Y(b())}),default:Y(b()).optional()}),mk=P({type:C("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Y(P({const:b(),title:b()}))}),default:Y(b()).optional()}),hk=he([pk,mk]),gk=he([dk,fk,hk]),yk=he([gk,ik,ak,ck]),_k=vo.extend({mode:C("form").optional(),message:b(),requestedSchema:P({type:C("object"),properties:pe(b(),yk),required:Y(b()).optional()})}),vk=vo.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),xk=he([_k,vk]),bk=Ie.extend({method:C("elicitation/create"),params:xk}),wk=it.extend({elicitationId:b()}),$k=at.extend({method:C("notifications/elicitation/complete"),params:wk}),Pn=Oe.extend({action:We(["accept","decline","cancel"]),content:Vu(t=>t===null?void 0:t,pe(b(),he([b(),se(),ze(),Y(b())])).optional())}),kk=P({type:C("ref/resource"),uri:b()}),Sk=P({type:C("ref/prompt"),name:b()}),Ek=nt.extend({ref:he([Sk,kk]),argument:P({name:b(),value:b()}),context:P({arguments:pe(b(),b()).optional()}).optional()}),di=Ie.extend({method:C("completion/complete"),params:Ek});Tk=Oe.extend({completion:Le({values:Y(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),zk=P({uri:b().startsWith("file://"),name:b().optional(),_meta:pe(b(),xe()).optional()}),Pk=Ie.extend({method:C("roots/list"),params:nt.optional()}),al=Oe.extend({roots:Y(zk)}),Rk=at.extend({method:C("notifications/roots/list_changed"),params:it.optional()}),GA=he([Gs,Ks,di,sl,ci,ai,oi,si,ii,P$,I$,zn,ui,Ys,ei,ti,ni]),XA=he([Ws,Xs,Yu,Rk,So]),YA=he([Js,zo,il,Pn,al,Qs,ri,En]),QA=he([Gs,sk,bk,Pk,Ys,ei,ti,ni]),eN=he([Ws,Xs,X$,C$,T$,W$,F$,So,$k]),tN=he([Js,g$,Tk,U$,M$,$$,k$,E$,li,B$,Qs,ri,En]),O=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Bu(o.elicitations,r)}return new t(e,r,n)}},Bu=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Oo=T(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var Ro=class{};oe._CodeOrName=Ro;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Br=class extends Ro{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=Br;var ct=class extends Ro{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=ct;oe.nil=new ct("");function Yh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)yl(r,e[n]),r.push(t[++n]);return new ct(r)}oe._=Yh;var gl=new ct("+");function Qh(t,...e){let r=[Io(t[0])],n=0;for(;n<e.length;)r.push(gl),yl(r,e[n]),r.push(gl,Io(t[++n]));return Lk(r),new ct(r)}oe.str=Qh;function yl(t,e){e instanceof ct?t.push(...e._items):e instanceof Br?t.push(e):t.push(Hk(e))}oe.addCodeArg=yl;function Lk(t){let e=1;for(;e<t.length-1;){if(t[e]===gl){let r=Uk(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Uk(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Br||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Br))return`"${t}${e.slice(1)}`}function Fk(t,e){return e.emptyStr()?t:t.emptyStr()?e:Qh`${t}${e}`}oe.strConcat=Fk;function Hk(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Io(Array.isArray(t)?t.join(","):t)}function Vk(t){return new ct(Io(t))}oe.stringify=Vk;function Io(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Io;function Bk(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new ct(`.${t}`):Yh`[${t}]`}oe.getProperty=Bk;function Jk(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=Jk;function Wk(t){return new ct(t.toString())}oe.regexpCode=Wk});var xl=T(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ke=Oo(),_l=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},yi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(yi||(Ge.UsedValueState=yi={}));Ge.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var _i=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ke.Name?e:this.name(e)}name(e){return new Ke.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ge.Scope=_i;var vi=class extends Ke.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ke._)`.${new Ke.Name(r)}[${n}]`}};Ge.ValueScopeName=vi;var Kk=(0,Ke._)`\n`,vl=class extends _i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Kk:Ke.nil}}get(){return this._scope}name(e){return new vi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ke._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ke.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,yi.Started);let l=r(u);if(l){let d=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;s=(0,Ke._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ke._)`${s}${l}${this.opts._n}`;else throw new _l(u);c.set(u,yi.Completed)})}return s}};Ge.ValueScope=vl});var B=T(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var ee=Oo(),_t=xl(),cr=Oo();Object.defineProperty(J,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(J,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(J,"strConcat",{enumerable:!0,get:function(){return cr.strConcat}});Object.defineProperty(J,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(J,"getProperty",{enumerable:!0,get:function(){return cr.getProperty}});Object.defineProperty(J,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:function(){return cr.regexpCode}});Object.defineProperty(J,"Name",{enumerable:!0,get:function(){return cr.Name}});var $i=xl();Object.defineProperty(J,"Scope",{enumerable:!0,get:function(){return $i.Scope}});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:function(){return $i.ValueScope}});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:function(){return $i.ValueScopeName}});Object.defineProperty(J,"varKinds",{enumerable:!0,get:function(){return $i.varKinds}});J.operators={GT:new ee._Code(">"),GTE:new ee._Code(">="),LT:new ee._Code("<"),LTE:new ee._Code("<="),EQ:new ee._Code("==="),NEQ:new ee._Code("!=="),NOT:new ee._Code("!"),OR:new ee._Code("||"),AND:new ee._Code("&&"),ADD:new ee._Code("+")};var Vt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},bl=class extends Vt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=In(this.rhs,e,r)),this}get names(){return this.rhs instanceof ee._CodeOrName?this.rhs.names:{}}},xi=class extends Vt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ee.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=In(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ee.Name?{}:{...this.lhs.names};return wi(e,this.rhs)}},wl=class extends xi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$l=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},kl=class extends Vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Sl=class extends Vt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},El=class extends Vt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=In(this.code,e,r),this}get names(){return this.code instanceof ee._CodeOrName?this.code.names:{}}},Co=class extends Vt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Gk(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Kr(e,r.names),{})}},Bt=class extends Co{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Tl=class extends Co{},Rn=class extends Bt{};Rn.kind="else";var Jr=class t extends Bt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Rn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(eg(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=In(this.condition,e,r),this}get names(){let e=super.names;return wi(e,this.condition),this.else&&Kr(e,this.else.names),e}};Jr.kind="if";var Wr=class extends Bt{};Wr.kind="for";var zl=class extends Wr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=In(this.iteration,e,r),this}get names(){return Kr(super.names,this.iteration.names)}},Pl=class extends Wr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=wi(super.names,this.from);return wi(e,this.to)}},bi=class extends Wr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=In(this.iterable,e,r),this}get names(){return Kr(super.names,this.iterable.names)}},Ao=class extends Bt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ao.kind="func";var No=class extends Co{render(e){return"return "+super.render(e)}};No.kind="return";var Rl=class extends Bt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Kr(e,this.catch.names),this.finally&&Kr(e,this.finally.names),e}},Mo=class extends Bt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Mo.kind="catch";var jo=class extends Bt{render(e){return"finally"+super.render(e)}};jo.kind="finally";var Il=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
-
`:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new Tl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new bl(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new xi(e,r,n))}add(e,r){return this._leafNode(new wl(e,J.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ee.nil&&this._leafNode(new El(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ee.addCodeArg)(r,o));return r.push("}"),new ee._Code(r)}if(e,r,n){if(this._blockNode(new Jr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new Rn)}endIf(){return this._endBlockNode(Jr,Rn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new zl(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Pl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ee.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ee._)`${i}.length`,a=>{this.var(s,(0,ee._)`${i}[${a}]`),n(s)})}return this._for(new bi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ee._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new bi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Wr)}label(e){return this._leafNode(new $l(e))}break(e){return this._leafNode(new kl(e))}return(e){let r=new No;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(No)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Rl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Mo(s),r(s)}return n&&(this._currNode=o.finally=new jo,this.code(n)),this._endBlockNode(Mo,jo)}throw(e){return this._leafNode(new Sl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ee.nil,n,o){return this._blockNode(new Ao(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ao)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};J.CodeGen=Il;function Kr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function wi(t,e){return e instanceof ee._CodeOrName?Kr(t,e.names):t}function In(t,e,r){if(t instanceof ee.Name)return n(t);if(!o(t))return t;return new ee._Code(t._items.reduce((s,i)=>(i instanceof ee.Name&&(i=n(i)),i instanceof ee._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ee._Code&&s._items.some(i=>i instanceof ee.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Gk(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function eg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ee._)`!${Ol(t)}`}J.not=eg;var Xk=tg(J.operators.AND);function Yk(...t){return t.reduce(Xk)}J.and=Yk;var Qk=tg(J.operators.OR);function eS(...t){return t.reduce(Qk)}J.or=eS;function tg(t){return(e,r)=>e===ee.nil?r:r===ee.nil?e:(0,ee._)`${Ol(e)} ${t} ${Ol(r)}`}function Ol(t){return t instanceof ee.Name?t:(0,ee._)`(${t})`}});var re=T(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var le=B(),tS=Oo();function rS(t){let e={};for(let r of t)e[r]=!0;return e}W.toHash=rS;function nS(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(og(t,e),!sg(e,t.self.RULES.all))}W.alwaysValidSchema=nS;function og(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||cg(t,`unknown keyword: "${s}"`)}W.checkUnknownRules=og;function sg(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}W.schemaHasRules=sg;function oS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}W.schemaHasRulesButRef=oS;function sS({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}W.schemaRefOrVal=sS;function iS(t){return ig(decodeURIComponent(t))}W.unescapeFragment=iS;function aS(t){return encodeURIComponent(Al(t))}W.escapeFragment=aS;function Al(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=Al;function ig(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=ig;function cS(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}W.eachItem=cS;function rg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}W.mergeEvaluated={props:rg({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),Nl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ag}),items:rg({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ag(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Nl(t,r,e),r}W.evaluatedPropsToName=ag;function Nl(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}W.setEvaluated=Nl;var ng={};function uS(t,e){return t.scopeValue("func",{ref:e,code:ng[e.code]||(ng[e.code]=new tS._Code(e.code))})}W.useFunc=uS;var Cl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Cl||(W.Type=Cl={}));function lS(t,e,r){if(t instanceof le.Name){let n=e===Cl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Al(t)}W.getErrorPath=lS;function cg(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=cg});var Jt=T(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var Me=B(),dS={data:new Me.Name("data"),valCxt:new Me.Name("valCxt"),instancePath:new Me.Name("instancePath"),parentData:new Me.Name("parentData"),parentDataProperty:new Me.Name("parentDataProperty"),rootData:new Me.Name("rootData"),dynamicAnchors:new Me.Name("dynamicAnchors"),vErrors:new Me.Name("vErrors"),errors:new Me.Name("errors"),this:new Me.Name("this"),self:new Me.Name("self"),scope:new Me.Name("scope"),json:new Me.Name("json"),jsonPos:new Me.Name("jsonPos"),jsonLen:new Me.Name("jsonLen"),jsonPart:new Me.Name("jsonPart")};Ml.default=dS});var Zo=T(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var ne=B(),ki=re(),Fe=Jt();je.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};je.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function fS(t,e=je.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=dg(t,e,r);n??(i||a)?ug(s,c):lg(o,(0,ne._)`[${c}]`)}je.reportError=fS;function pS(t,e=je.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=dg(t,e,r);ug(o,a),s||i||lg(n,Fe.default.vErrors)}je.reportExtraError=pS;function mS(t,e){t.assign(Fe.default.errors,e),t.if((0,ne._)`${Fe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Fe.default.vErrors}.length`,e),()=>t.assign(Fe.default.vErrors,null)))}je.resetErrorsCount=mS;function hS({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Fe.default.errors,a=>{t.const(i,(0,ne._)`${Fe.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Fe.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}je.extendErrors=hS;function ug(t,e){let r=t.const("err",e);t.if((0,ne._)`${Fe.default.vErrors} === null`,()=>t.assign(Fe.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Fe.default.vErrors}.push(${r})`),t.code((0,ne._)`${Fe.default.errors}++`)}function lg(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var Gr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function dg(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:gS(t,e,r)}function gS(t,e,r={}){let{gen:n,it:o}=t,s=[yS(o,r),_S(t,r)];return vS(t,e,s),n.object(...s)}function yS({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,ki.getErrorPath)(e,ki.Type.Str)}`:t;return[Fe.default.instancePath,(0,ne.strConcat)(Fe.default.instancePath,r)]}function _S({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Gr.schemaPath,o]}function vS(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Gr.keyword,o],[Gr.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([Gr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Gr.schema,i],[Gr.parentSchema,(0,ne._)`${l}${d}`],[Fe.default.data,s]),u&&n.push([Gr.propertyName,u])}});var pg=T(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.boolOrEmptySchema=On.topBoolOrEmptySchema=void 0;var xS=Zo(),bS=B(),wS=Jt(),$S={message:"boolean schema is false"};function kS(t){let{gen:e,schema:r,validateName:n}=t;r===!1?fg(t,!1):typeof r=="object"&&r.$async===!0?e.return(wS.default.data):(e.assign((0,bS._)`${n}.errors`,null),e.return(!0))}On.topBoolOrEmptySchema=kS;function SS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),fg(t)):r.var(e,!0)}On.boolOrEmptySchema=SS;function fg(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,xS.reportError)(o,$S,void 0,e)}});var jl=T(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.getRules=Cn.isJSONType=void 0;var ES=["string","number","integer","boolean","null","object","array"],TS=new Set(ES);function zS(t){return typeof t=="string"&&TS.has(t)}Cn.isJSONType=zS;function PS(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Cn.getRules=PS});var Zl=T(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.shouldUseRule=ur.shouldUseGroup=ur.schemaHasRulesForType=void 0;function RS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&mg(t,n)}ur.schemaHasRulesForType=RS;function mg(t,e){return e.rules.some(r=>hg(t,r))}ur.shouldUseGroup=mg;function hg(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ur.shouldUseRule=hg});var Do=T(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.reportTypeError=Ze.checkDataTypes=Ze.checkDataType=Ze.coerceAndCheckDataType=Ze.getJSONTypes=Ze.getSchemaTypes=Ze.DataType=void 0;var IS=jl(),OS=Zl(),CS=Zo(),F=B(),gg=re(),An;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(An||(Ze.DataType=An={}));function AS(t){let e=yg(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ze.getSchemaTypes=AS;function yg(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(IS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ze.getJSONTypes=yg;function NS(t,e){let{gen:r,data:n,opts:o}=t,s=MS(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,OS.schemaHasRulesForType)(t,e[0]));if(i){let a=ql(e,n,o.strictNumbers,An.Wrong);r.if(a,()=>{s.length?jS(t,e,s):Ll(t)})}return i}Ze.coerceAndCheckDataType=NS;var _g=new Set(["string","number","integer","boolean","null"]);function MS(t,e){return e?t.filter(r=>_g.has(r)||e==="array"&&r==="array"):[]}function jS(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,F._)`typeof ${o}`),a=n.let("coerced",(0,F._)`undefined`);s.coerceTypes==="array"&&n.if((0,F._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,F._)`${o}[0]`).assign(i,(0,F._)`typeof ${o}`).if(ql(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,F._)`${a} !== undefined`);for(let u of r)(_g.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ll(t),n.endIf(),n.if((0,F._)`${a} !== undefined`,()=>{n.assign(o,a),ZS(t,a)});function c(u){switch(u){case"string":n.elseIf((0,F._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,F._)`"" + ${o}`).elseIf((0,F._)`${o} === null`).assign(a,(0,F._)`""`);return;case"number":n.elseIf((0,F._)`${i} == "boolean" || ${o} === null
|
|
32
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
33
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
34
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,F._)`[${o}]`)}}}function ZS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,F._)`${e} !== undefined`,()=>t.assign((0,F._)`${e}[${r}]`,n))}function Dl(t,e,r,n=An.Correct){let o=n===An.Correct?F.operators.EQ:F.operators.NEQ,s;switch(t){case"null":return(0,F._)`${e} ${o} null`;case"array":s=(0,F._)`Array.isArray(${e})`;break;case"object":s=(0,F._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,F._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,F._)`typeof ${e} ${o} ${t}`}return n===An.Correct?s:(0,F.not)(s);function i(a=F.nil){return(0,F.and)((0,F._)`typeof ${e} == "number"`,a,r?(0,F._)`isFinite(${e})`:F.nil)}}Ze.checkDataType=Dl;function ql(t,e,r,n){if(t.length===1)return Dl(t[0],e,r,n);let o,s=(0,gg.toHash)(t);if(s.array&&s.object){let i=(0,F._)`typeof ${e} != "object"`;o=s.null?i:(0,F._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=F.nil;s.number&&delete s.integer;for(let i in s)o=(0,F.and)(o,Dl(i,e,r,n));return o}Ze.checkDataTypes=ql;var DS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,F._)`{type: ${t}}`:(0,F._)`{type: ${e}}`};function Ll(t){let e=qS(t);(0,CS.reportError)(e,DS)}Ze.reportTypeError=Ll;function qS(t){let{gen:e,data:r,schema:n}=t,o=(0,gg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var xg=T(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.assignDefaults=void 0;var Nn=B(),LS=re();function US(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)vg(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>vg(t,s,o.default))}Si.assignDefaults=US;function vg(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Nn._)`${s}${(0,Nn.getProperty)(e)}`;if(o){(0,LS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Nn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Nn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Nn._)`${a} = ${(0,Nn.stringify)(r)}`)}});var ut=T(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=B(),Ul=re(),lr=Jt(),FS=re();function HS(t,e){let{gen:r,data:n,it:o}=t;r.if(Hl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=HS;function VS({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Hl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=VS;function BS(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=BS;function bg(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=bg;function Fl(t,e,r){return(0,ge._)`${bg(t)}.call(${e}, ${r})`}ue.isOwnProperty=Fl;function JS(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Fl(t,e,r)}`:o}ue.propertyInData=JS;function Hl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Fl(t,e,r))):o}ue.noPropertyInData=Hl;function wg(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=wg;function WS(t,e){return wg(e).filter(r=>!(0,Ul.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=WS;function KS({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[lr.default.instancePath,(0,ge.strConcat)(lr.default.instancePath,s)],[lr.default.parentData,i.parentData],[lr.default.parentDataProperty,i.parentDataProperty],[lr.default.rootData,lr.default.rootData]];i.opts.dynamicRef&&d.push([lr.default.dynamicAnchors,lr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=KS;var GS=(0,ge._)`new RegExp`;function XS({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?GS:(0,FS.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=XS;function YS(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ul.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=YS;function QS(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ul.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=QS});var Sg=T(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.validateKeywordUsage=Rt.validSchemaType=Rt.funcKeywordCode=Rt.macroKeywordCode=void 0;var He=B(),Xr=Jt(),eE=ut(),tE=Zo();function rE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=kg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:He.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rt.macroKeywordCode=rE;function nE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;sE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=kg(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&$g(t),y(()=>t.error());else{let _=e.async?m():f();e.modifying&&$g(t),y(()=>oE(t,_))}}function m(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,He._)`await `),v=>n.assign(d,!1).if((0,He._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,He._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,He._)`${l}.errors`;return n.assign(_,null),h(He.nil),_}function h(_=e.async?(0,He._)`await `:He.nil){let v=c.opts.passContext?Xr.default.this:Xr.default.self,g=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,He._)`${_}${(0,eE.callValidateCode)(t,l,v,g)}`,e.modifying)}function y(_){var v;n.if((0,He.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Rt.funcKeywordCode=nE;function $g(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,He._)`${n.parentData}[${n.parentDataProperty}]`))}function oE(t,e){let{gen:r}=t;r.if((0,He._)`Array.isArray(${e})`,()=>{r.assign(Xr.default.vErrors,(0,He._)`${Xr.default.vErrors} === null ? ${e} : ${Xr.default.vErrors}.concat(${e})`).assign(Xr.default.errors,(0,He._)`${Xr.default.vErrors}.length`),(0,tE.extendErrors)(t)},()=>t.error())}function sE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function kg(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,He.stringify)(r)})}function iE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Rt.validSchemaType=iE;function aE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Rt.validateKeywordUsage=aE});var Tg=T(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.extendSubschemaMode=dr.extendSubschemaData=dr.getSubschema=void 0;var It=B(),Eg=re();function cE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,It._)`${t.schemaPath}${(0,It.getProperty)(e)}${(0,It.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Eg.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dr.getSubschema=cE;function uE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,It._)`${e.data}${(0,It.getProperty)(r)}`,!0);c(p),t.errorPath=(0,It.str)`${u}${(0,Eg.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,It._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof It.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}dr.extendSubschemaData=uE;function lE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}dr.extendSubschemaMode=lE});var Vl=T((yZ,zg)=>{"use strict";zg.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Rg=T((_Z,Pg)=>{"use strict";var fr=Pg.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ei(e,n,o,t,"",t)};fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};fr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ei(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in fr.arrayKeywords)for(var p=0;p<d.length;p++)Ei(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in fr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Ei(t,e,r,d[m],o+"/"+l+"/"+dE(m),s,o,l,n,m)}else(l in fr.keywords||t.allKeys&&!(l in fr.skipKeywords))&&Ei(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function dE(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var qo=T(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var fE=re(),pE=Vl(),mE=Rg(),hE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gE(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Bl(t):e?Ig(t)<=e:!1}Xe.inlineRef=gE;var yE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Bl(t){for(let e in t){if(yE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Bl)||typeof r=="object"&&Bl(r))return!0}return!1}function Ig(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!hE.has(r)&&(typeof t[r]=="object"&&(0,fE.eachItem)(t[r],n=>e+=Ig(n)),e===1/0))return 1/0}return e}function Og(t,e="",r){r!==!1&&(e=Mn(e));let n=t.parse(e);return Cg(t,n)}Xe.getFullPath=Og;function Cg(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=Cg;var _E=/#\/?$/;function Mn(t){return t?t.replace(_E,""):""}Xe.normalizeId=Mn;function vE(t,e,r){return r=Mn(r),t.resolve(e,r)}Xe.resolveUrl=vE;var xE=/^[a-z_][-a-z0-9._]*$/i;function bE(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Mn(t[r]||e),s={"":o},i=Og(n,o,!1),a={},c=new Set;return mE(t,{allKeys:!0},(d,p,m,f)=>{if(f===void 0)return;let h=i+p,y=s[f];typeof d[r]=="string"&&(y=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[p]=y;function _(g){let x=this.opts.uriResolver.resolve;if(g=Mn(y?x(y,g):g),c.has(g))throw l(g);c.add(g);let $=this.refs[g];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,g):g!==Mn(h)&&(g[0]==="#"?(u(d,a[g],g),a[g]=d):this.refs[g]=h),g}function v(g){if(typeof g=="string"){if(!xE.test(g))throw new Error(`invalid anchor "${g}"`);_.call(this,`#${g}`)}}}),a;function u(d,p,m){if(p!==void 0&&!pE(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=bE});var Fo=T(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.getData=pr.KeywordCxt=pr.validateFunctionCode=void 0;var Zg=pg(),Ag=Do(),Wl=Zl(),Ti=Do(),wE=xg(),Uo=Sg(),Jl=Tg(),A=B(),q=Jt(),$E=qo(),Wt=re(),Lo=Zo();function kE(t){if(Lg(t)&&(Ug(t),qg(t))){TE(t);return}Dg(t,()=>(0,Zg.topBoolOrEmptySchema)(t))}pr.validateFunctionCode=kE;function Dg({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,A._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,A._)`"use strict"; ${Ng(r,o)}`),EE(t,o),t.code(s)}):t.func(e,(0,A._)`${q.default.data}, ${SE(o)}`,n.$async,()=>t.code(Ng(r,o)).code(s))}function SE(t){return(0,A._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,A._)`, ${q.default.dynamicAnchors}={}`:A.nil}}={}`}function EE(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,A._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,A._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,A._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,A._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,A._)`""`),t.var(q.default.parentData,(0,A._)`undefined`),t.var(q.default.parentDataProperty,(0,A._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,A._)`{}`)})}function TE(t){let{schema:e,opts:r,gen:n}=t;Dg(t,()=>{r.$comment&&e.$comment&&Hg(t),OE(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&zE(t),Fg(t),NE(t)})}function zE(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,A._)`${r}.evaluated`),e.if((0,A._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,A._)`${t.evaluated}.props`,(0,A._)`undefined`)),e.if((0,A._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,A._)`${t.evaluated}.items`,(0,A._)`undefined`))}function Ng(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,A._)`/*# sourceURL=${r} */`:A.nil}function PE(t,e){if(Lg(t)&&(Ug(t),qg(t))){RE(t,e);return}(0,Zg.boolOrEmptySchema)(t,e)}function qg({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Lg(t){return typeof t.schema!="boolean"}function RE(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Hg(t),CE(t),AE(t);let s=n.const("_errs",q.default.errors);Fg(t,s),n.var(e,(0,A._)`${s} === ${q.default.errors}`)}function Ug(t){(0,Wt.checkUnknownRules)(t),IE(t)}function Fg(t,e){if(t.opts.jtd)return Mg(t,[],!1,e);let r=(0,Ag.getSchemaTypes)(t.schema),n=(0,Ag.coerceAndCheckDataType)(t,r);Mg(t,r,!n,e)}function IE(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Wt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function OE(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Wt.checkStrictMode)(t,"default is ignored in the schema root")}function CE(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$E.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function AE(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Hg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,A._)`${q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,A.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,A._)`${q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function NE(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,A._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,A._)`new ${o}(${q.default.vErrors})`)):(e.assign((0,A._)`${n}.errors`,q.default.vErrors),s.unevaluated&&ME(t),e.return((0,A._)`${q.default.errors} === 0`))}function ME({gen:t,evaluated:e,props:r,items:n}){r instanceof A.Name&&t.assign((0,A._)`${e}.props`,r),n instanceof A.Name&&t.assign((0,A._)`${e}.items`,n)}function Mg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Wt.schemaHasRulesButRef)(s,l))){o.block(()=>Bg(t,"$ref",l.all.$ref.definition));return}c.jtd||jE(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Wl.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ti.checkDataType)(p.type,i,c.strictNumbers)),jg(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ti.reportTypeError)(t)),o.endIf()):jg(t,p),a||o.if((0,A._)`${q.default.errors} === ${n||0}`))}}function jg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,wE.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Wl.shouldUseRule)(n,s)&&Bg(t,s.keyword,s.definition,e.type)})}function jE(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ZE(t,e),t.opts.allowUnionTypes||DE(t,e),qE(t,t.dataTypes))}function ZE(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Vg(t.dataTypes,r)||Kl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),UE(t,e)}}function DE(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kl(t,"use allowUnionTypes to allow union type keyword")}function qE(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Wl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>LE(e,i))&&Kl(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function LE(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Vg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function UE(t,e){let r=[];for(let n of t.dataTypes)Vg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Kl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Wt.checkStrictMode)(t,e,t.opts.strictTypes)}var zi=class{constructor(e,r,n){if((0,Uo.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Wt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Jg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Uo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,A.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,A.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,A._)`${r} !== undefined && (${(0,A.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Lo.reportExtraError:Lo.reportError)(this,this.def.error,r)}$dataError(){(0,Lo.reportError)(this,this.def.$dataError||Lo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Lo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=A.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=A.nil,r=A.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,A.or)((0,A._)`${o} === undefined`,r)),e!==A.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,A.or)(i(),a());function i(){if(n.length){if(!(r instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,A._)`${(0,Ti.checkDataTypes)(c,r,s.opts.strictNumbers,Ti.DataType.Wrong)}`}return A.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,A._)`!${c}(${r})`}return A.nil}}subschema(e,r){let n=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(n,this.it,e),(0,Jl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return PE(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Wt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Wt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,A.Name)),!0}};pr.KeywordCxt=zi;function Bg(t,e,r,n){let o=new zi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Uo.funcKeywordCode)(o,r):"macro"in r?(0,Uo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Uo.funcKeywordCode)(o,r)}var FE=/^\/(?:[^~]|~0|~1)*$/,HE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!FE.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=q.default.rootData}else{let u=HE.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,A._)`${s}${(0,A.getProperty)((0,Wt.unescapeJsonPointer)(u))}`,i=(0,A._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}pr.getData=Jg});var Pi=T(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var Gl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xl.default=Gl});var Ho=T(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Yl=qo(),Ql=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Yl.resolveUrl)(e,r,n),this.missingSchema=(0,Yl.normalizeId)((0,Yl.getFullPath)(e,this.missingRef))}};ed.default=Ql});var Ii=T(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var vt=B(),VE=Pi(),Yr=Jt(),xt=qo(),Wg=re(),BE=Fo(),jn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,xt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=jn;function rd(t){let e=Kg.call(this,t);if(e)return e;let r=(0,xt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:VE.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Yr.default.data,parentData:Yr.default.parentData,parentDataProperty:Yr.default.parentDataProperty,dataNames:[Yr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,BE.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Yr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Yr.default.self}`,`${Yr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof vt.Name?void 0:f,items:h instanceof vt.Name?void 0:h,dynamicProps:f instanceof vt.Name,dynamicItems:h instanceof vt.Name},m.source&&(m.source.evaluated=(0,vt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}lt.compileSchema=rd;function JE(t,e,r){var n;r=(0,xt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=GE.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new jn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=WE.call(this,s)}lt.resolveRef=JE;function WE(t){return(0,xt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:rd.call(this,t)}function Kg(t){for(let e of this._compilations)if(KE(e,t))return e}lt.getCompilingSchema=Kg;function KE(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function GE(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ri.call(this,t,e)}function Ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,xt._getFullPath)(this.opts.uriResolver,r),o=(0,xt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return td.call(this,r,t);let s=(0,xt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ri.call(this,t,i);return typeof a?.schema!="object"?void 0:td.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||rd.call(this,i),s===(0,xt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,xt.resolveUrl)(this.opts.uriResolver,o,u)),new jn({schema:a,schemaId:c,root:t,baseId:o})}return td.call(this,r,i)}}lt.resolveSchema=Ri;var XE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function td(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Wg.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!XE.has(a)&&u&&(e=(0,xt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Wg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,xt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new jn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Gg=T((kZ,YE)=>{YE.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var cd=T((SZ,ny)=>{"use strict";var QE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),od=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),eT=RegExp.prototype.test.bind(/^\d*$/u),Qr=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Yg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),id=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),tT=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ye=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Ye[e]="%"+t[e>>4]+t[e&15]}function De(t){return t<2048?Ye[192|t>>6]+Ye[128|t&63]:t<65536?Ye[224|t>>12]+Ye[128|t>>6&63]+Ye[128|t&63]:Ye[240|t>>18]+Ye[128|t>>12&63]+Ye[128|t>>6&63]+Ye[128|t&63]}function rT(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var nT=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),oT=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),sT=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),iT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function aT(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!sT(t[e])){if(t[e]==="%"&&e+2<t.length&&Qr(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Xg(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function cT(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!od(c))return;s+=2;continue}if(!nT(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Xg(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return Xg(i)}function nd(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&oT(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(uT(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!aT(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=cT(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function uT(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function lT(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var dT={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fT=/[@/?#:]/g,pT=/[@/?#]/g;function Qg(t,e){let r=e?pT:fT;return r.lastIndex=0,t.replace(r,n=>dT[n])}function ey(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&sd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function mT(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&sd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Yg(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ry(o)?n:Ye[o];else if(o<55296||o>57343)e+=De(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=De(65536+(o-55296<<10)+(s-56320)),r++):e+=De(65533)}else e+=De(65533)}}return e}function hT(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(Qr(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Yg(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Ye[i];else if(i<55296||i>57343)r+=De(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=De(65536+(i-55296<<10)+(a-56320)),o++):r+=De(65533)}else r+=De(65533)}}return r}function ad(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(Qr(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Ye[s];else if(s<55296||s>57343)r+=De(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=De(65536+(s-55296<<10)+(i-56320)),n++):r+=De(65533)}else r+=De(65533)}}return r}function ty(t){return ad(t,tT)}function gT(t){return ad(t,id)}function yT(t){return ad(t,id)}function ry(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function _T(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(Qr(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));sd(i)?e+=i:e+="%"+s,r+=2;continue}}if(id(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=ry(o)?n:Ye[o];else if(o<55296||o>57343)e+=De(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=De(65536+(o-55296<<10)+(s-56320)),r++):e+=De(65533)}else e+=De(65533)}}return e}function vT(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Qr(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function xT(t){let e=[];if(t.userinfo!==void 0&&(e.push(ty(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!od(r)){let n=nd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ey(r,!0),n=nd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Qg(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!eT(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}ny.exports={nonSimpleDomain:iT,recomposeAuthority:xT,reescapeHostDelimiters:Qg,normalizePercentEncoding:ey,normalizePathEncoding:mT,serializePathEncoding:hT,normalizeQueryFragmentEncoding:_T,encodeUserinfo:ty,encodeQuery:gT,encodeFragment:yT,escapePreservingEscapes:vT,removeDotSegments:lT,isIPv4:od,isUUID:QE,normalizeIPv6:nd,stringArrayToHexStripped:rT}});var cy=T((EZ,ay)=>{"use strict";var{isUUID:bT}=cd(),wT=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,$T=["http","https","ws","wss","urn","urn:uuid"];function kT(t){return $T.indexOf(t)!==-1}function ud(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function oy(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sy(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ST(t){return t.secure=ud(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ET(t){if((t.port===(ud(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function TT(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(wT);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=ld(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zT(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=ld(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function PT(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!bT(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function RT(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var iy={scheme:"http",domainHost:!0,parse:oy,serialize:sy},IT={scheme:"https",domainHost:iy.domainHost,parse:oy,serialize:sy},Oi={scheme:"ws",domainHost:!0,parse:ST,serialize:ET},OT={scheme:"wss",domainHost:Oi.domainHost,parse:Oi.parse,serialize:Oi.serialize},CT={scheme:"urn",parse:TT,serialize:zT,skipNormalize:!0},AT={scheme:"urn:uuid",parse:PT,serialize:RT,skipNormalize:!0},Ci={http:iy,https:IT,ws:Oi,wss:OT,urn:CT,"urn:uuid":AT};Object.setPrototypeOf(Ci,null);function ld(t){return t&&(Ci[t]||Ci[t.toLowerCase()])||void 0}ay.exports={wsIsSecure:ud,SCHEMES:Ci,isValidSchemeName:kT,getSchemeHandler:ld}});var by=T((TZ,Mi)=>{"use strict";var{normalizeIPv6:py,removeDotSegments:Bo,recomposeAuthority:NT,normalizePercentEncoding:dd,normalizePathEncoding:MT,serializePathEncoding:uy,normalizeQueryFragmentEncoding:ly,encodeQuery:jT,encodeFragment:ZT,reescapeHostDelimiters:DT,isIPv4:my,nonSimpleDomain:qT}=cd(),{SCHEMES:hy,getSchemeHandler:fd}=cy(),gy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,yy="URI scheme is malformed.";function dy(t){let e=unescape(String(t));if(!gy.test(e))throw new TypeError(yy);return e}function LT(t,e){return typeof t=="string"?t=KT(t,e):typeof t=="object"&&(t=Ni(en(t,e),e)),t}function UT(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Ai(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=Ai(e,n);if(s||d||i||p||a||m||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let y=_y(o,l,n,!0),_=fd(r&&r.scheme||y.scheme),v=y.host,g=v!==void 0&&v!==""&&(my(v)||py(v).isIPV6);vy(y,r||{},_,g);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(y.error&&!x)throw new Error(y.error);return n.skipEscape=!0,en(y,n)}function _y(t,e,r,n){let o={};return n||(t=Ni(en(t,r),r),e=Ni(en(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Bo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Bo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Bo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function FT(t,e,r){let n=fy(t,r),o=fy(e,r);return n!==void 0&&o!==void 0&&n===o}function en(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[];r.scheme&&(r.scheme=dy(r.scheme));let s=fd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=dd(r.path):r.path=uy(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=dy(r.scheme),o.push(r.scheme,":"));let c=NT(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=Bo(u)),a&&(u=uy(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",jT(r.query)),r.fragment!==void 0&&o.push("#",ZT(r.fragment)),o.join("")}var HT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,VT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,BT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function JT(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Vo(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function pd(t){return t[0]==="["&&t[t.length-1]==="]"}function WT(t){let e=t[4];return Vo(t[3])||e!==void 0&&!pd(e)&&Vo(e)||Vo(t[6])||Vo(t[7])||Vo(t[8])}function vy(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!pd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&qT(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Ai(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(VT);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(BT);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(HT);if(m){if(n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0){let y=unescape(n.scheme);gy.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||yy,u=!0)}s=WT(m),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let f=JT(n,m);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(my(n.host)===!1){let _=pd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,g=py(n.host);l=g.isIPV6||g.isIPVFuture===!0,c=v&&(!_||g.error===!0),n.host=l?g.host:g.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=fd(r.scheme||n.scheme);if(c||(a=vy(n,r,h,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=l?n.host:dd(n.host,!0);l||(y=dd(y.toLowerCase())),n.host=DT(y,l)}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=MT(n.path)),n.query&&(n.query=ly(n.query)),n.fragment&&(n.fragment=ly(n.fragment))),h&&h.parse&&(h.parse(n,r),h===hy.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ni(t,e){return Ai(t,e).parsed}function KT(t,e){return xy(t,e).normalized}function xy(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Ai(t,e);return{normalized:n||o||s||i||a?t:en(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function fy(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:en(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=xy(r,e);return o||s||i||a||c?void 0:n}var md={SCHEMES:hy,normalize:LT,resolve:UT,resolveComponent:_y,equal:FT,serialize:en,parse:Ni};Mi.exports=md;Mi.exports.default=md;Mi.exports.fastUri=md});var $y=T(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var wy=by();wy.code='require("ajv/dist/runtime/uri").default';hd.default=wy});var Iy=T(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var GT=Fo();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return GT.KeywordCxt}});var Zn=B();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var XT=Pi(),zy=Ho(),YT=jl(),Jo=Ii(),QT=B(),Wo=qo(),ji=Do(),yd=re(),ky=Gg(),ez=$y(),Py=(t,e)=>new RegExp(t,e);Py.code="new RegExp";var tz=["removeAdditional","useDefaults","coerceTypes"],rz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),nz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},oz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sy=200;function sz(t){var e,r,n,o,s,i,a,c,u,l,d,p,m,f,h,y,_,v,g,x,$,D,R,ie,ae;let Te=t.strict,L=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=L===!0||L===void 0?1:L||0,$t=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Py,xr=(o=t.uriResolver)!==null&&o!==void 0?o:ez.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Te)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:Te)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:$t}:{optimize:_e,regExp:$t},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Sy,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Sy,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(g=t.inlineRefs)!==null&&g!==void 0?g:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(ie=t.unicodeRegExp)!==null&&ie!==void 0?ie:!0,int32range:(ae=t.int32range)!==null&&ae!==void 0?ae:!0,uriResolver:xr}}var Ko=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...sz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new QT.ValueScope({scope:{},prefixes:rz,es5:r,lines:n}),this.logger=dz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,YT.getRules)(),Ey.call(this,nz,e,"NOT SUPPORTED"),Ey.call(this,oz,e,"DEPRECATED","warn"),this._metaOpts=uz.call(this),e.formats&&az.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&cz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),iz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=ky;n==="id"&&(o={...ky},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof zy.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Wo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Ty.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Jo.SchemaEnv({schema:{},schemaId:n});if(r=Jo.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Ty.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Wo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(pz.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;hz.call(this,r);let o={...r,type:(0,ji.getJSONTypes)(r.type),schemaType:(0,ji.getJSONTypes)(r.schemaType)};return(0,yd.eachItem)(n,o.type.length===0?s=>gd.call(this,s,o):s=>o.type.forEach(i=>gd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=Ry(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Wo.normalizeId)(i||n);let u=Wo.getSchemaRefs.call(this,e,n);return c=new Jo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Jo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Jo.compileSchema.call(this,e)}finally{this.opts=r}}};Ko.ValidationError=XT.default;Ko.MissingRefError=zy.default;Ce.default=Ko;function Ey(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Ty(t){return t=(0,Wo.normalizeId)(t),this.schemas[t]||this.refs[t]}function iz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function az(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function cz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function uz(){let t={...this.opts};for(let e of tz)delete t[e];return t}var lz={log(){},warn(){},error(){}};function dz(t){if(t===!1)return lz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var fz=/^[a-z_$][a-z0-9_$:-]*$/i;function pz(t,e){let{RULES:r}=this;if((0,yd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!fz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ji.getJSONTypes)(e.type),schemaType:(0,ji.getJSONTypes)(e.schemaType)}};e.before?mz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function mz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function hz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Ry(e)),t.validateSchema=this.compile(e,!0))}var gz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ry(t){return{anyOf:[t,gz]}}});var Oy=T(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var yz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};_d.default=yz});var My=T(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.callRef=tn.getValidate=void 0;var _z=Ho(),Cy=ut(),Qe=B(),Dn=Jt(),Ay=Ii(),Zi=re(),vz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Ay.resolveRef.call(c,u,o,r);if(l===void 0)throw new _z.default(n.opts.uriResolver,o,r);if(l instanceof Ay.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return Di(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Di(t,(0,Qe._)`${f}.validate`,u,u.$async)}function p(f){let h=Ny(t,f);Di(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Qe.stringify)(f)}:{ref:f}),y=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function Ny(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}tn.getValidate=Ny;function Di(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Dn.default.this:Qe.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,Cy.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,Qe._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Cy.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,Qe._)`${f}.errors`;o.assign(Dn.default.vErrors,(0,Qe._)`${Dn.default.vErrors} === null ? ${h} : ${Dn.default.vErrors}.concat(${h})`),o.assign(Dn.default.errors,(0,Qe._)`${Dn.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Zi.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,Qe._)`${f}.evaluated.props`);s.props=Zi.mergeEvaluated.props(o,_,s.props,Qe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Zi.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,Qe._)`${f}.evaluated.items`);s.items=Zi.mergeEvaluated.items(o,_,s.items,Qe.Name)}}}tn.callRef=Di;tn.default=vz});var jy=T(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var xz=Oy(),bz=My(),wz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xz.default,bz.default];vd.default=wz});var Zy=T(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var qi=B(),mr=qi.operators,Li={maximum:{okStr:"<=",ok:mr.LTE,fail:mr.GT},minimum:{okStr:">=",ok:mr.GTE,fail:mr.LT},exclusiveMaximum:{okStr:"<",ok:mr.LT,fail:mr.GTE},exclusiveMinimum:{okStr:">",ok:mr.GT,fail:mr.LTE}},$z={message:({keyword:t,schemaCode:e})=>(0,qi.str)`must be ${Li[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qi._)`{comparison: ${Li[t].okStr}, limit: ${e}}`},kz={keyword:Object.keys(Li),type:"number",schemaType:"number",$data:!0,error:$z,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,qi._)`${r} ${Li[e].fail} ${n} || isNaN(${r})`)}};xd.default=kz});var Dy=T(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Go=B(),Sz={message:({schemaCode:t})=>(0,Go.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Go._)`{multipleOf: ${t}}`},Ez={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Sz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Go._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Go._)`${i} !== parseInt(${i})`;t.fail$data((0,Go._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};bd.default=Ez});var Ly=T(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});function qy(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}wd.default=qy;qy.code='require("ajv/dist/runtime/ucs2length").default'});var Uy=T($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var rn=B(),Tz=re(),zz=Ly(),Pz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,rn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,rn._)`{limit: ${t}}`},Rz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Pz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?rn.operators.GT:rn.operators.LT,i=o.opts.unicode===!1?(0,rn._)`${r}.length`:(0,rn._)`${(0,Tz.useFunc)(t.gen,zz.default)}(${r})`;t.fail$data((0,rn._)`${i} ${s} ${n}`)}};$d.default=Rz});var Fy=T(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Iz=ut(),Oz=re(),qn=B(),Cz={message:({schemaCode:t})=>(0,qn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qn._)`{pattern: ${t}}`},Az={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Cz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,qn._)`new RegExp`:(0,Oz.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,qn._)`!${l}`)}else{let c=(0,Iz.usePattern)(t,o);t.fail$data((0,qn._)`!${c}.test(${r})`)}}};kd.default=Az});var Hy=T(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Xo=B(),Nz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Xo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Xo._)`{limit: ${t}}`},Mz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Nz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Xo.operators.GT:Xo.operators.LT;t.fail$data((0,Xo._)`Object.keys(${r}).length ${o} ${n}`)}};Sd.default=Mz});var Vy=T(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Yo=ut(),Qo=B(),jz=re(),Zz={message:({params:{missingProperty:t}})=>(0,Qo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Qo._)`{missingProperty: ${t}}`},Dz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Zz,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(m?.[h]===void 0&&!f.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,jz.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Qo.nil,d);else for(let m of r)(0,Yo.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,Yo.checkMissingProp)(t,r,m)),(0,Yo.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Yo.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,Yo.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Qo.not)(f),()=>{t.error(),e.break()})},Qo.nil)}}};Ed.default=Dz});var By=T(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var es=B(),qz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,es.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,es._)`{limit: ${t}}`},Lz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:qz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?es.operators.GT:es.operators.LT;t.fail$data((0,es._)`${r}.length ${o} ${n}`)}};Td.default=Lz});var Ui=T(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Jy=Vl();Jy.code='require("ajv/dist/runtime/equal").default';zd.default=Jy});var Wy=T(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var Pd=Do(),Ae=B(),Uz=re(),Fz=Ui(),Hz={message:({params:{i:t,j:e}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ae._)`{i: ${t}, j: ${e}}`},Vz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Hz,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Pd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ae._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Ae._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,Ae._)`${f} > 1`,()=>(d()?p:m)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let y=e.name("item"),_=(0,Pd.checkDataTypes)(u,y,a.opts.strictNumbers,Pd.DataType.Wrong),v=e.const("indices",(0,Ae._)`{}`);e.for((0,Ae._)`;${f}--;`,()=>{e.let(y,(0,Ae._)`${r}[${f}]`),e.if(_,(0,Ae._)`continue`),u.length>1&&e.if((0,Ae._)`typeof ${y} == "string"`,(0,Ae._)`${y} += "_"`),e.if((0,Ae._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(h,(0,Ae._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ae._)`${v}[${y}] = ${f}`)})}function m(f,h){let y=(0,Uz.useFunc)(e,Fz.default),_=e.name("outer");e.label(_).for((0,Ae._)`;${f}--;`,()=>e.for((0,Ae._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Ae._)`${y}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Rd.default=Vz});var Ky=T(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var Id=B(),Bz=re(),Jz=Ui(),Wz={message:"must be equal to constant",params:({schemaCode:t})=>(0,Id._)`{allowedValue: ${t}}`},Kz={keyword:"const",$data:!0,error:Wz,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Id._)`!${(0,Bz.useFunc)(e,Jz.default)}(${r}, ${o})`):t.fail((0,Id._)`${s} !== ${r}`)}};Od.default=Kz});var Gy=T(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var ts=B(),Gz=re(),Xz=Ui(),Yz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ts._)`{allowedValues: ${t}}`},Qz={keyword:"enum",schemaType:"array",$data:!0,error:Yz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Gz.useFunc)(e,Xz.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,ts.or)(...o.map((f,h)=>p(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,ts._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,ts._)`${u()}(${r}, ${m}[${f}])`:(0,ts._)`${r} === ${h}`}}};Cd.default=Qz});var Xy=T(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var eP=Zy(),tP=Dy(),rP=Uy(),nP=Fy(),oP=Hy(),sP=Vy(),iP=By(),aP=Wy(),cP=Ky(),uP=Gy(),lP=[eP.default,tP.default,rP.default,nP.default,oP.default,sP.default,iP.default,aP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cP.default,uP.default];Ad.default=lP});var Md=T(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.validateAdditionalItems=void 0;var nn=B(),Nd=re(),dP={message:({params:{len:t}})=>(0,nn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,nn._)`{limit: ${t}}`},fP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Nd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yy(t,n)}};function Yy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,nn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,nn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Nd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,nn._)`${a} <= ${e.length}`);r.if((0,nn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Nd.Type.Num},u),i.allErrors||r.if((0,nn.not)(u),()=>r.break())})}}rs.validateAdditionalItems=Yy;rs.default=fP});var jd=T(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.validateTuple=void 0;var Qy=B(),Fi=re(),pP=ut(),mP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return e_(t,"additionalItems",e);r.items=!0,!(0,Fi.alwaysValidSchema)(r,e)&&t.ok((0,pP.validateArray)(t))}};function e_(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Fi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Qy._)`${s}.length`);r.forEach((d,p)=>{(0,Fi.alwaysValidSchema)(a,d)||(n.if((0,Qy._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,f=r.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Fi.checkStrictMode)(a,y,p.strictTuples)}}}ns.validateTuple=e_;ns.default=mP});var t_=T(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var hP=jd(),gP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,hP.validateTuple)(t,"items")};Zd.default=gP});var n_=T(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var r_=B(),yP=re(),_P=ut(),vP=Md(),xP={message:({params:{len:t}})=>(0,r_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,r_._)`{limit: ${t}}`},bP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,yP.alwaysValidSchema)(n,e)&&(o?(0,vP.validateAdditionalItems)(t,o):t.ok((0,_P.validateArray)(t)))}};Dd.default=bP});var o_=T(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var dt=B(),Hi=re(),wP={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},$P={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Hi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Hi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Hi.alwaysValidSchema)(s,r)){let h=(0,dt._)`${l} >= ${i}`;a!==void 0&&(h=(0,dt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);m(h,()=>e.if(h,()=>f(y)))}function m(h,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Hi.Type.Num,compositeRule:!0},h),y()})}function f(h){e.code((0,dt._)`${h}++`),a===void 0?e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};qd.default=$P});var a_=T(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Ld=B(),kP=re(),os=ut();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ld.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ld._)`{property: ${t},
|
|
30
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let m=n.external.registry.get(d[0])?.id;if(e!==d[0]&&m){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let p=this.seen.get(d),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,f))}p.isParent||this.override({zodSchema:d,jsonSchema:m,path:p.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var uh=X(()=>{});var Fe=X(()=>{Sn();bc();mc();Xm();Ds();Ec();At();Zs();Bs();gu();Tc();ah();ih();ch();uh()});var sl=X(()=>{Fe()});var zo={};fo(zo,{ZodISODate:()=>ph,ZodISODateTime:()=>fh,ZodISODuration:()=>hh,ZodISOTime:()=>mh,date:()=>al,datetime:()=>il,duration:()=>ul,time:()=>cl});function il(t){return th(fh,t)}function al(t){return rh(ph,t)}function cl(t){return nh(mh,t)}function ul(t){return oh(hh,t)}var fh,ph,mh,hh,ll=X(()=>{Fe();dl();fh=w("ZodISODateTime",(t,e)=>{Vm.init(t,e),ve.init(t,e)});ph=w("ZodISODate",(t,e)=>{Jm.init(t,e),ve.init(t,e)});mh=w("ZodISOTime",(t,e)=>{Km.init(t,e),ve.init(t,e)});hh=w("ZodISODuration",(t,e)=>{Wm.init(t,e),ve.init(t,e)})});var gh,zM,Po,fl=X(()=>{Fe();Fe();gh=(t,e)=>{Ms.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>pc(t,r)},flatten:{value:r=>fc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},zM=w("ZodError",gh),Po=w("ZodError",gh,{Parent:Error})});var yh,_h,vh,xh,pl=X(()=>{Fe();fl();yh=hc(Po),_h=yc(Po),vh=vc(Po),xh=xc(Po)});function b(t){return yu(E$,t)}function se(t){return Du(Sh,t)}function wh(t){return Lu(B$,t)}function ze(t){return qu(V$,t)}function Th(t){return Fu(J$,t)}function xe(){return Uu(K$)}function G$(t){return Hu(W$,t)}function Q(t,e){return sh(X$,t,e)}function P(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new Eh(r)}function Ue(t,e){return new Eh({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...Y.normalizeParams(e)})}function he(t,e){return new zh({type:"union",options:t,...Y.normalizeParams(e)})}function gl(t,e,r){return new Y$({type:"union",options:e,discriminator:t,...Y.normalizeParams(r)})}function ri(t,e){return new Q$({type:"intersection",left:t,right:e})}function me(t,e,r){return new ek({type:"record",keyType:t,valueType:e,...Y.normalizeParams(r)})}function Xe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ml({type:"enum",entries:r,...Y.normalizeParams(e)})}function N(t,e){return new tk({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}function Ph(t){return new rk({type:"transform",transform:t})}function be(t){return new Rh({type:"optional",innerType:t})}function $h(t){return new nk({type:"nullable",innerType:t})}function sk(t,e){return new ok({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ak(t,e){return new ik({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ck(t,e){return new Ih({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}function lk(t,e){return new uk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function hl(t,e){return new dk({type:"pipe",in:t,out:e})}function pk(t){return new fk({type:"readonly",innerType:t})}function mk(t){let e=new Re({check:"custom"});return e._zod.check=t,e}function Oh(t,e){return tl(Ch,t??(()=>!0),e)}function hk(t,e={}){return rl(Ch,t,e)}function gk(t){let e=mk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Y.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(Y.issue(o))}},t(r.value,r)));return e}function yl(t,e){return hl(Ph(t),e)}var $e,kh,E$,ve,z$,bh,ti,P$,R$,I$,C$,O$,A$,N$,M$,j$,Z$,D$,L$,q$,F$,U$,H$,Sh,B$,V$,J$,K$,W$,X$,Eh,zh,Y$,Q$,ek,ml,tk,rk,Rh,nk,ok,ik,Ih,uk,dk,fk,Ch,dl=X(()=>{Fe();Fe();sl();ll();pl();$e=w("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>yh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>vh(t,r,n),t.parseAsync=async(r,n)=>_h(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>xh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(hk(r,n)),t.superRefine=r=>t.check(gk(r)),t.overwrite=r=>t.check(Yr(r)),t.optional=()=>be(t),t.nullable=()=>$h(t),t.nullish=()=>be($h(t)),t.nonoptional=r=>ck(t,r),t.array=()=>Q(t),t.or=r=>he([t,r]),t.and=r=>ri(t,r),t.transform=r=>hl(t,Ph(r)),t.default=r=>sk(t,r),t.prefault=r=>ak(t,r),t.catch=r=>lk(t,r),t.pipe=r=>hl(t,r),t.readonly=()=>pk(t),t.describe=r=>{let n=t.clone();return dr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return dr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return dr.get(t);let n=t.clone();return dr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kh=w("_ZodString",(t,e)=>{ko.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Bu(...n)),t.includes=(...n)=>t.check(Ku(...n)),t.startsWith=(...n)=>t.check(Wu(...n)),t.endsWith=(...n)=>t.check(Gu(...n)),t.min=(...n)=>t.check(zn(...n)),t.max=(...n)=>t.check(Gs(...n)),t.length=(...n)=>t.check(Xs(...n)),t.nonempty=(...n)=>t.check(zn(1,...n)),t.lowercase=n=>t.check(Vu(n)),t.uppercase=n=>t.check(Ju(n)),t.trim=()=>t.check(Yu()),t.normalize=(...n)=>t.check(Xu(...n)),t.toLowerCase=()=>t.check(Qu()),t.toUpperCase=()=>t.check(el())}),E$=w("ZodString",(t,e)=>{ko.init(t,e),kh.init(t,e),t.email=r=>t.check(_u(z$,r)),t.url=r=>t.check($u(P$,r)),t.jwt=r=>t.check(Zu(H$,r)),t.emoji=r=>t.check(ku(R$,r)),t.guid=r=>t.check(Vs(bh,r)),t.uuid=r=>t.check(vu(ti,r)),t.uuidv4=r=>t.check(xu(ti,r)),t.uuidv6=r=>t.check(bu(ti,r)),t.uuidv7=r=>t.check(wu(ti,r)),t.nanoid=r=>t.check(Su(I$,r)),t.guid=r=>t.check(Vs(bh,r)),t.cuid=r=>t.check(Tu(C$,r)),t.cuid2=r=>t.check(Eu(O$,r)),t.ulid=r=>t.check(zu(A$,r)),t.base64=r=>t.check(Nu(q$,r)),t.base64url=r=>t.check(Mu(F$,r)),t.xid=r=>t.check(Pu(N$,r)),t.ksuid=r=>t.check(Ru(M$,r)),t.ipv4=r=>t.check(Iu(j$,r)),t.ipv6=r=>t.check(Cu(Z$,r)),t.cidrv4=r=>t.check(Ou(D$,r)),t.cidrv6=r=>t.check(Au(L$,r)),t.e164=r=>t.check(ju(U$,r)),t.datetime=r=>t.check(il(r)),t.date=r=>t.check(al(r)),t.time=r=>t.check(cl(r)),t.duration=r=>t.check(ul(r))});ve=w("ZodStringFormat",(t,e)=>{pe.init(t,e),kh.init(t,e)}),z$=w("ZodEmail",(t,e)=>{Ic.init(t,e),ve.init(t,e)}),bh=w("ZodGUID",(t,e)=>{Pc.init(t,e),ve.init(t,e)}),ti=w("ZodUUID",(t,e)=>{Rc.init(t,e),ve.init(t,e)}),P$=w("ZodURL",(t,e)=>{Cc.init(t,e),ve.init(t,e)}),R$=w("ZodEmoji",(t,e)=>{Oc.init(t,e),ve.init(t,e)}),I$=w("ZodNanoID",(t,e)=>{Ac.init(t,e),ve.init(t,e)}),C$=w("ZodCUID",(t,e)=>{Nc.init(t,e),ve.init(t,e)}),O$=w("ZodCUID2",(t,e)=>{Mc.init(t,e),ve.init(t,e)}),A$=w("ZodULID",(t,e)=>{jc.init(t,e),ve.init(t,e)}),N$=w("ZodXID",(t,e)=>{Zc.init(t,e),ve.init(t,e)}),M$=w("ZodKSUID",(t,e)=>{Dc.init(t,e),ve.init(t,e)}),j$=w("ZodIPv4",(t,e)=>{Lc.init(t,e),ve.init(t,e)}),Z$=w("ZodIPv6",(t,e)=>{qc.init(t,e),ve.init(t,e)}),D$=w("ZodCIDRv4",(t,e)=>{Fc.init(t,e),ve.init(t,e)}),L$=w("ZodCIDRv6",(t,e)=>{Uc.init(t,e),ve.init(t,e)}),q$=w("ZodBase64",(t,e)=>{Hc.init(t,e),ve.init(t,e)}),F$=w("ZodBase64URL",(t,e)=>{Bc.init(t,e),ve.init(t,e)}),U$=w("ZodE164",(t,e)=>{Vc.init(t,e),ve.init(t,e)}),H$=w("ZodJWT",(t,e)=>{Jc.init(t,e),ve.init(t,e)}),Sh=w("ZodNumber",(t,e)=>{Fs.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(Ks(n,o)),t.gte=(n,o)=>t.check(Eo(n,o)),t.min=(n,o)=>t.check(Eo(n,o)),t.lt=(n,o)=>t.check(Js(n,o)),t.lte=(n,o)=>t.check(To(n,o)),t.max=(n,o)=>t.check(To(n,o)),t.int=n=>t.check(wh(n)),t.safe=n=>t.check(wh(n)),t.positive=n=>t.check(Ks(0,n)),t.nonnegative=n=>t.check(Eo(0,n)),t.negative=n=>t.check(Js(0,n)),t.nonpositive=n=>t.check(To(0,n)),t.multipleOf=(n,o)=>t.check(Ws(n,o)),t.step=(n,o)=>t.check(Ws(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});B$=w("ZodNumberFormat",(t,e)=>{Kc.init(t,e),Sh.init(t,e)});V$=w("ZodBoolean",(t,e)=>{Wc.init(t,e),$e.init(t,e)});J$=w("ZodNull",(t,e)=>{Gc.init(t,e),$e.init(t,e)});K$=w("ZodUnknown",(t,e)=>{Xc.init(t,e),$e.init(t,e)});W$=w("ZodNever",(t,e)=>{Yc.init(t,e),$e.init(t,e)});X$=w("ZodArray",(t,e)=>{Qc.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(zn(r,n)),t.nonempty=r=>t.check(zn(1,r)),t.max=(r,n)=>t.check(Gs(r,n)),t.length=(r,n)=>t.check(Xs(r,n)),t.unwrap=()=>t.element});Eh=w("ZodObject",(t,e)=>{Us.init(t,e),$e.init(t,e),Y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Xe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xe()}),t.loose=()=>t.clone({...t._zod.def,catchall:xe()}),t.strict=()=>t.clone({...t._zod.def,catchall:G$()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Y.extend(t,r),t.merge=r=>Y.merge(t,r),t.pick=r=>Y.pick(t,r),t.omit=r=>Y.omit(t,r),t.partial=(...r)=>Y.partial(Rh,t,r[0]),t.required=(...r)=>Y.required(Ih,t,r[0])});zh=w("ZodUnion",(t,e)=>{Hs.init(t,e),$e.init(t,e),t.options=e.options});Y$=w("ZodDiscriminatedUnion",(t,e)=>{zh.init(t,e),eu.init(t,e)});Q$=w("ZodIntersection",(t,e)=>{tu.init(t,e),$e.init(t,e)});ek=w("ZodRecord",(t,e)=>{ru.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});ml=w("ZodEnum",(t,e)=>{nu.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new ml({...e,checks:[],...Y.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new ml({...e,checks:[],...Y.normalizeParams(o),entries:s})}});tk=w("ZodLiteral",(t,e)=>{ou.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});rk=w("ZodTransform",(t,e)=>{su.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(Y.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Rh=w("ZodOptional",(t,e)=>{iu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});nk=w("ZodNullable",(t,e)=>{au.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});ok=w("ZodDefault",(t,e)=>{cu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});ik=w("ZodPrefault",(t,e)=>{uu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Ih=w("ZodNonOptional",(t,e)=>{lu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});uk=w("ZodCatch",(t,e)=>{du.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});dk=w("ZodPipe",(t,e)=>{fu.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});fk=w("ZodReadonly",(t,e)=>{pu.init(t,e),$e.init(t,e)});Ch=w("ZodCustom",(t,e)=>{mu.init(t,e),$e.init(t,e)})});var Ah=X(()=>{});var Nh=X(()=>{});var Mh=X(()=>{Fe();dl();sl();fl();pl();Ah();Fe();Qm();Bs();ll();Nh();ot(Ym())});var jh=X(()=>{Mh()});var Zh=X(()=>{jh()});function Qh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function eg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var vl,Dh,Cn,mr,oi,Te,Lh,qh,HM,vk,xk,xl,it,Ro,Fh,Ie,ut,lt,Ce,si,Uh,Gt,Hh,Bh,bl,Xt,M,wl,On,Io,BM,ii,bk,ai,wk,Co,In,Vh,$k,kk,Sk,Tk,Ek,zk,ci,$l,Pk,Rk,kl,ui,Ik,Ck,li,Ok,Oo,Ao,Ak,No,An,Nk,Mo,di,fi,pi,VM,mi,hi,gi,Jh,Kh,Wh,Sl,Gh,jo,Nn,Xh,Mk,yi,jk,_i,Zk,Tl,Dk,vi,Lk,qk,Fk,Uk,Hk,Bk,Vk,Jk,Kk,Wk,xi,Gk,Xk,bi,El,zl,Pl,Yk,Qk,eS,Rl,tS,rS,nS,oS,sS,Yh,wi,iS,$i,JM,aS,Mn,cS,KM,Zo,uS,Il,lS,dS,fS,pS,mS,hS,gS,ni,yS,_S,vS,Do,Cl,xS,bS,wS,$S,kS,SS,TS,ES,zS,PS,RS,IS,CS,OS,AS,NS,MS,jS,jn,ZS,DS,LS,ki,qS,FS,US,Ol,HS,WM,GM,XM,YM,QM,ej,I,_l,hr=X(()=>{Zh();vl="2025-11-25",Dh="2025-03-26",Cn=[vl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],mr="io.modelcontextprotocol/related-task",oi="2.0",Te=Oh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Lh=he([b(),se().int()]),qh=b(),HM=Ue({ttl:se().optional(),pollInterval:se().optional()}),vk=P({ttl:se().optional()}),xk=P({taskId:b()}),xl=Ue({progressToken:Lh.optional(),[mr]:xk.optional()}),it=P({_meta:xl.optional()}),Ro=it.extend({task:vk.optional()}),Fh=t=>Ro.safeParse(t).success,Ie=P({method:b(),params:it.loose().optional()}),ut=P({_meta:xl.optional()}),lt=P({method:b(),params:ut.loose().optional()}),Ce=Ue({_meta:xl.optional()}),si=he([b(),se().int()]),Uh=P({jsonrpc:N(oi),id:si,...Ie.shape}).strict(),Gt=t=>Uh.safeParse(t).success,Hh=P({jsonrpc:N(oi),...lt.shape}).strict(),Bh=t=>Hh.safeParse(t).success,bl=P({jsonrpc:N(oi),id:si,result:Ce}).strict(),Xt=t=>bl.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(M||(M={}));wl=P({jsonrpc:N(oi),id:si.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),On=t=>wl.safeParse(t).success,Io=he([Uh,Hh,bl,wl]),BM=he([bl,wl]),ii=Ce.strict(),bk=ut.extend({requestId:si.optional(),reason:b().optional()}),ai=lt.extend({method:N("notifications/cancelled"),params:bk}),wk=P({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Xe(["light","dark"]).optional()}),Co=P({icons:Q(wk).optional()}),In=P({name:b(),title:b().optional()}),Vh=In.extend({...In.shape,...Co.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),$k=ri(P({applyDefaults:ze().optional()}),me(b(),xe())),kk=yl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ri(P({form:$k.optional(),url:Te.optional()}),me(b(),xe()).optional())),Sk=Ue({list:Te.optional(),cancel:Te.optional(),requests:Ue({sampling:Ue({createMessage:Te.optional()}).optional(),elicitation:Ue({create:Te.optional()}).optional()}).optional()}),Tk=Ue({list:Te.optional(),cancel:Te.optional(),requests:Ue({tools:Ue({call:Te.optional()}).optional()}).optional()}),Ek=P({experimental:me(b(),Te).optional(),sampling:P({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:kk.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:Sk.optional(),extensions:me(b(),Te).optional()}),zk=it.extend({protocolVersion:b(),capabilities:Ek,clientInfo:Vh}),ci=Ie.extend({method:N("initialize"),params:zk}),$l=t=>ci.safeParse(t).success,Pk=P({experimental:me(b(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:Tk.optional(),extensions:me(b(),Te).optional()}),Rk=Ce.extend({protocolVersion:b(),capabilities:Pk,serverInfo:Vh,instructions:b().optional()}),kl=lt.extend({method:N("notifications/initialized"),params:ut.optional()}),ui=Ie.extend({method:N("ping"),params:it.optional()}),Ik=P({progress:se(),total:be(se()),message:be(b())}),Ck=P({...ut.shape,...Ik.shape,progressToken:Lh}),li=lt.extend({method:N("notifications/progress"),params:Ck}),Ok=it.extend({cursor:qh.optional()}),Oo=Ie.extend({params:Ok.optional()}),Ao=Ce.extend({nextCursor:qh.optional()}),Ak=Xe(["working","input_required","completed","failed","cancelled"]),No=P({taskId:b(),status:Ak,ttl:he([se(),Th()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),An=Ce.extend({task:No}),Nk=ut.merge(No),Mo=lt.extend({method:N("notifications/tasks/status"),params:Nk}),di=Ie.extend({method:N("tasks/get"),params:it.extend({taskId:b()})}),fi=Ce.merge(No),pi=Ie.extend({method:N("tasks/result"),params:it.extend({taskId:b()})}),VM=Ce.loose(),mi=Oo.extend({method:N("tasks/list")}),hi=Ao.extend({tasks:Q(No)}),gi=Ie.extend({method:N("tasks/cancel"),params:it.extend({taskId:b()})}),Jh=Ce.merge(No),Kh=P({uri:b(),mimeType:be(b()),_meta:me(b(),xe()).optional()}),Wh=Kh.extend({text:b()}),Sl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Gh=Kh.extend({blob:Sl}),jo=Xe(["user","assistant"]),Nn=P({audience:Q(jo).optional(),priority:se().min(0).max(1).optional(),lastModified:zo.datetime({offset:!0}).optional()}),Xh=P({...In.shape,...Co.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Nn.optional(),_meta:be(Ue({}))}),Mk=P({...In.shape,...Co.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Nn.optional(),_meta:be(Ue({}))}),yi=Oo.extend({method:N("resources/list")}),jk=Ao.extend({resources:Q(Xh)}),_i=Oo.extend({method:N("resources/templates/list")}),Zk=Ao.extend({resourceTemplates:Q(Mk)}),Tl=it.extend({uri:b()}),Dk=Tl,vi=Ie.extend({method:N("resources/read"),params:Dk}),Lk=Ce.extend({contents:Q(he([Wh,Gh]))}),qk=lt.extend({method:N("notifications/resources/list_changed"),params:ut.optional()}),Fk=Tl,Uk=Ie.extend({method:N("resources/subscribe"),params:Fk}),Hk=Tl,Bk=Ie.extend({method:N("resources/unsubscribe"),params:Hk}),Vk=ut.extend({uri:b()}),Jk=lt.extend({method:N("notifications/resources/updated"),params:Vk}),Kk=P({name:b(),description:be(b()),required:be(ze())}),Wk=P({...In.shape,...Co.shape,description:be(b()),arguments:be(Q(Kk)),_meta:be(Ue({}))}),xi=Oo.extend({method:N("prompts/list")}),Gk=Ao.extend({prompts:Q(Wk)}),Xk=it.extend({name:b(),arguments:me(b(),b()).optional()}),bi=Ie.extend({method:N("prompts/get"),params:Xk}),El=P({type:N("text"),text:b(),annotations:Nn.optional(),_meta:me(b(),xe()).optional()}),zl=P({type:N("image"),data:Sl,mimeType:b(),annotations:Nn.optional(),_meta:me(b(),xe()).optional()}),Pl=P({type:N("audio"),data:Sl,mimeType:b(),annotations:Nn.optional(),_meta:me(b(),xe()).optional()}),Yk=P({type:N("tool_use"),name:b(),id:b(),input:me(b(),xe()),_meta:me(b(),xe()).optional()}),Qk=P({type:N("resource"),resource:he([Wh,Gh]),annotations:Nn.optional(),_meta:me(b(),xe()).optional()}),eS=Xh.extend({type:N("resource_link")}),Rl=he([El,zl,Pl,eS,Qk]),tS=P({role:jo,content:Rl}),rS=Ce.extend({description:b().optional(),messages:Q(tS)}),nS=lt.extend({method:N("notifications/prompts/list_changed"),params:ut.optional()}),oS=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),sS=P({taskSupport:Xe(["required","optional","forbidden"]).optional()}),Yh=P({...In.shape,...Co.shape,description:b().optional(),inputSchema:P({type:N("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()),outputSchema:P({type:N("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()).optional(),annotations:oS.optional(),execution:sS.optional(),_meta:me(b(),xe()).optional()}),wi=Oo.extend({method:N("tools/list")}),iS=Ao.extend({tools:Q(Yh)}),$i=Ce.extend({content:Q(Rl).default([]),structuredContent:me(b(),xe()).optional(),isError:ze().optional()}),JM=$i.or(Ce.extend({toolResult:xe()})),aS=Ro.extend({name:b(),arguments:me(b(),xe()).optional()}),Mn=Ie.extend({method:N("tools/call"),params:aS}),cS=lt.extend({method:N("notifications/tools/list_changed"),params:ut.optional()}),KM=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),Zo=Xe(["debug","info","notice","warning","error","critical","alert","emergency"]),uS=it.extend({level:Zo}),Il=Ie.extend({method:N("logging/setLevel"),params:uS}),lS=ut.extend({level:Zo,logger:b().optional(),data:xe()}),dS=lt.extend({method:N("notifications/message"),params:lS}),fS=P({name:b().optional()}),pS=P({hints:Q(fS).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),mS=P({mode:Xe(["auto","required","none"]).optional()}),hS=P({type:N("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(Rl).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:me(b(),xe()).optional()}),gS=gl("type",[El,zl,Pl]),ni=gl("type",[El,zl,Pl,Yk,hS]),yS=P({role:jo,content:he([ni,Q(ni)]),_meta:me(b(),xe()).optional()}),_S=Ro.extend({messages:Q(yS),modelPreferences:pS.optional(),systemPrompt:b().optional(),includeContext:Xe(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Q(b()).optional(),metadata:Te.optional(),tools:Q(Yh).optional(),toolChoice:mS.optional()}),vS=Ie.extend({method:N("sampling/createMessage"),params:_S}),Do=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens"]).or(b())),role:jo,content:gS}),Cl=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:jo,content:he([ni,Q(ni)])}),xS=P({type:N("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),bS=P({type:N("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:Xe(["email","uri","date","date-time"]).optional(),default:b().optional()}),wS=P({type:Xe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),$S=P({type:N("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),kS=P({type:N("string"),title:b().optional(),description:b().optional(),oneOf:Q(P({const:b(),title:b()})),default:b().optional()}),SS=P({type:N("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),TS=he([$S,kS]),ES=P({type:N("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:N("string"),enum:Q(b())}),default:Q(b()).optional()}),zS=P({type:N("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Q(P({const:b(),title:b()}))}),default:Q(b()).optional()}),PS=he([ES,zS]),RS=he([SS,TS,PS]),IS=he([RS,xS,bS,wS]),CS=Ro.extend({mode:N("form").optional(),message:b(),requestedSchema:P({type:N("object"),properties:me(b(),IS),required:Q(b()).optional()})}),OS=Ro.extend({mode:N("url"),message:b(),elicitationId:b(),url:b().url()}),AS=he([CS,OS]),NS=Ie.extend({method:N("elicitation/create"),params:AS}),MS=ut.extend({elicitationId:b()}),jS=lt.extend({method:N("notifications/elicitation/complete"),params:MS}),jn=Ce.extend({action:Xe(["accept","decline","cancel"]),content:yl(t=>t===null?void 0:t,me(b(),he([b(),se(),ze(),Q(b())])).optional())}),ZS=P({type:N("ref/resource"),uri:b()}),DS=P({type:N("ref/prompt"),name:b()}),LS=it.extend({ref:he([DS,ZS]),argument:P({name:b(),value:b()}),context:P({arguments:me(b(),b()).optional()}).optional()}),ki=Ie.extend({method:N("completion/complete"),params:LS});qS=Ce.extend({completion:Ue({values:Q(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),FS=P({uri:b().startsWith("file://"),name:b().optional(),_meta:me(b(),xe()).optional()}),US=Ie.extend({method:N("roots/list"),params:it.optional()}),Ol=Ce.extend({roots:Q(FS)}),HS=lt.extend({method:N("notifications/roots/list_changed"),params:ut.optional()}),WM=he([ui,ci,ki,Il,bi,xi,yi,_i,vi,Uk,Bk,Mn,wi,di,pi,mi,gi]),GM=he([ai,li,kl,HS,Mo]),XM=he([ii,Do,Cl,jn,Ol,fi,hi,An]),YM=he([ui,vS,NS,US,di,pi,mi,gi]),QM=he([ai,li,dS,Jk,qk,cS,nS,Mo,jS]),ej=he([ii,Rk,qS,rS,Gk,jk,Zk,Lk,$i,iS,fi,hi,An]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===M.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new _l(o.elicitations,r)}return new t(e,r,n)}},_l=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Uo=E(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var qo=class{};oe._CodeOrName=qo;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var tn=class extends qo{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=tn;var dt=class extends qo{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof tn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=dt;oe.nil=new dt("");function Ng(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ul(r,e[n]),r.push(t[++n]);return new dt(r)}oe._=Ng;var Fl=new dt("+");function Mg(t,...e){let r=[Fo(t[0])],n=0;for(;n<e.length;)r.push(Fl),Ul(r,e[n]),r.push(Fl,Fo(t[++n]));return tT(r),new dt(r)}oe.str=Mg;function Ul(t,e){e instanceof dt?t.push(...e._items):e instanceof tn?t.push(e):t.push(oT(e))}oe.addCodeArg=Ul;function tT(t){let e=1;for(;e<t.length-1;){if(t[e]===Fl){let r=rT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function rT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof tn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof tn))return`"${t}${e.slice(1)}`}function nT(t,e){return e.emptyStr()?t:t.emptyStr()?e:Mg`${t}${e}`}oe.strConcat=nT;function oT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Fo(Array.isArray(t)?t.join(","):t)}function sT(t){return new dt(Fo(t))}oe.stringify=sT;function Fo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Fo;function iT(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new dt(`.${t}`):Ng`[${t}]`}oe.getProperty=iT;function aT(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new dt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=aT;function cT(t){return new dt(t.toString())}oe.regexpCode=cT});var Vl=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=Uo(),Hl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ri;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ri||(Qe.UsedValueState=Ri={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Ii=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=Ii;var Ci=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=Ci;var uT=(0,Ye._)`\n`,Bl=class extends Ii{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?uT:Ye.nil}}get(){return this._scope}name(e){return new Ci(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Ri.Started);let d=r(u);if(d){let l=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ye._)`${s}${d}${this.opts._n}`;else throw new Hl(u);c.set(u,Ri.Completed)})}return s}};Qe.ValueScope=Bl});var J=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var te=Uo(),$t=Vl(),yr=Uo();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return yr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return yr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return yr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return yr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return yr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return yr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return yr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return yr.Name}});var Mi=Vl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Mi.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Mi.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Mi.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Mi.varKinds}});K.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Jl=class extends Yt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Dn(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Oi=class extends Yt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Dn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Ni(e,this.rhs)}},Kl=class extends Oi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wl=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gl=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Xl=class extends Yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yl=class extends Yt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Dn(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Ho=class extends Yt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(lT(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>on(e,r.names),{})}},Qt=class extends Ho{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ql=class extends Ho{},Zn=class extends Qt{};Zn.kind="else";var rn=class t extends Qt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Zn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(jg(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Dn(this.condition,e,r),this}get names(){let e=super.names;return Ni(e,this.condition),this.else&&on(e,this.else.names),e}};rn.kind="if";var nn=class extends Qt{};nn.kind="for";var ed=class extends nn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Dn(this.iteration,e,r),this}get names(){return on(super.names,this.iteration.names)}},td=class extends nn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ni(super.names,this.from);return Ni(e,this.to)}},Ai=class extends nn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Dn(this.iterable,e,r),this}get names(){return on(super.names,this.iterable.names)}},Bo=class extends Qt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Bo.kind="func";var Vo=class extends Ho{render(e){return"return "+super.render(e)}};Vo.kind="return";var rd=class extends Qt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&on(e,this.catch.names),this.finally&&on(e,this.finally.names),e}},Jo=class extends Qt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Jo.kind="catch";var Ko=class extends Qt{render(e){return"finally"+super.render(e)}};Ko.kind="finally";var nd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
31
|
+
`:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Ql]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Jl(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Oi(e,r,n))}add(e,r){return this._leafNode(new Kl(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Yl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new rn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new rn(e))}else(){return this._elseNode(new Zn)}endIf(){return this._endBlockNode(rn,Zn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ed(e),r)}forRange(e,r,n,o,s=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new td(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new Ai("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ai("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(nn)}label(e){return this._leafNode(new Wl(e))}break(e){return this._leafNode(new Gl(e))}return(e){let r=new Vo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new rd;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Jo(s),r(s)}return n&&(this._currNode=o.finally=new Ko,this.code(n)),this._endBlockNode(Jo,Ko)}throw(e){return this._leafNode(new Xl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new Bo(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Bo)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof rn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=nd;function on(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ni(t,e){return e instanceof te._CodeOrName?on(t,e.names):t}function Dn(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function lT(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function jg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${od(t)}`}K.not=jg;var dT=Zg(K.operators.AND);function fT(...t){return t.reduce(dT)}K.and=fT;var pT=Zg(K.operators.OR);function mT(...t){return t.reduce(pT)}K.or=mT;function Zg(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${od(e)} ${t} ${od(r)}`}function od(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var de=J(),hT=Uo();function gT(t){let e={};for(let r of t)e[r]=!0;return e}W.toHash=gT;function yT(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(qg(t,e),!Fg(e,t.self.RULES.all))}W.alwaysValidSchema=yT;function qg(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Bg(t,`unknown keyword: "${s}"`)}W.checkUnknownRules=qg;function Fg(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}W.schemaHasRules=Fg;function _T(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}W.schemaHasRulesButRef=_T;function vT({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}W.schemaRefOrVal=vT;function xT(t){return Ug(decodeURIComponent(t))}W.unescapeFragment=xT;function bT(t){return encodeURIComponent(id(t))}W.escapeFragment=bT;function id(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=id;function Ug(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=Ug;function wT(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}W.eachItem=wT;function Dg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof de.Name?(s instanceof de.Name?t(o,s,i):e(o,s,i),i):s instanceof de.Name?(e(o,i,s),s):r(s,i);return a===de.Name&&!(c instanceof de.Name)?n(o,c):c}}W.mergeEvaluated={props:Dg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),ad(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Hg}),items:Dg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Hg(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&ad(t,r,e),r}W.evaluatedPropsToName=Hg;function ad(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}W.setEvaluated=ad;var Lg={};function $T(t,e){return t.scopeValue("func",{ref:e,code:Lg[e.code]||(Lg[e.code]=new hT._Code(e.code))})}W.useFunc=$T;var sd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(sd||(W.Type=sd={}));function kT(t,e,r){if(t instanceof de.Name){let n=e===sd.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+id(t)}W.getErrorPath=kT;function Bg(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=Bg});var er=E(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var je=J(),ST={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};cd.default=ST});var Wo=E(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var ne=J(),ji=re(),Be=er();Ze.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function TT(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Kg(t,e,r);n??(i||a)?Vg(s,c):Jg(o,(0,ne._)`[${c}]`)}Ze.reportError=TT;function ET(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Kg(t,e,r);Vg(o,a),s||i||Jg(n,Be.default.vErrors)}Ze.reportExtraError=ET;function zT(t,e){t.assign(Be.default.errors,e),t.if((0,ne._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ze.resetErrorsCount=zT;function PT({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,ne._)`${Be.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ze.extendErrors=PT;function Vg(t,e){let r=t.const("err",e);t.if((0,ne._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Be.default.vErrors}.push(${r})`),t.code((0,ne._)`${Be.default.errors}++`)}function Jg(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var sn={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function Kg(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:RT(t,e,r)}function RT(t,e,r={}){let{gen:n,it:o}=t,s=[IT(o,r),CT(t,r)];return OT(t,e,s),n.object(...s)}function IT({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,ji.getErrorPath)(e,ji.Type.Str)}`:t;return[Be.default.instancePath,(0,ne.strConcat)(Be.default.instancePath,r)]}function CT({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,ji.getErrorPath)(r,ji.Type.Str)}`),[sn.schemaPath,o]}function OT(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([sn.keyword,o],[sn.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([sn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([sn.schema,i],[sn.parentSchema,(0,ne._)`${d}${l}`],[Be.default.data,s]),u&&n.push([sn.propertyName,u])}});var Gg=E(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.boolOrEmptySchema=Ln.topBoolOrEmptySchema=void 0;var AT=Wo(),NT=J(),MT=er(),jT={message:"boolean schema is false"};function ZT(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Wg(t,!1):typeof r=="object"&&r.$async===!0?e.return(MT.default.data):(e.assign((0,NT._)`${n}.errors`,null),e.return(!0))}Ln.topBoolOrEmptySchema=ZT;function DT(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Wg(t)):r.var(e,!0)}Ln.boolOrEmptySchema=DT;function Wg(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,AT.reportError)(o,jT,void 0,e)}});var ud=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.getRules=qn.isJSONType=void 0;var LT=["string","number","integer","boolean","null","object","array"],qT=new Set(LT);function FT(t){return typeof t=="string"&&qT.has(t)}qn.isJSONType=FT;function UT(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}qn.getRules=UT});var ld=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.shouldUseRule=_r.shouldUseGroup=_r.schemaHasRulesForType=void 0;function HT({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Xg(t,n)}_r.schemaHasRulesForType=HT;function Xg(t,e){return e.rules.some(r=>Yg(t,r))}_r.shouldUseGroup=Xg;function Yg(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}_r.shouldUseRule=Yg});var Go=E(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var BT=ud(),VT=ld(),JT=Wo(),B=J(),Qg=re(),Fn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Fn||(De.DataType=Fn={}));function KT(t){let e=ey(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}De.getSchemaTypes=KT;function ey(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(BT.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=ey;function WT(t,e){let{gen:r,data:n,opts:o}=t,s=GT(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,VT.schemaHasRulesForType)(t,e[0]));if(i){let a=fd(e,n,o.strictNumbers,Fn.Wrong);r.if(a,()=>{s.length?XT(t,e,s):pd(t)})}return i}De.coerceAndCheckDataType=WT;var ty=new Set(["string","number","integer","boolean","null"]);function GT(t,e){return e?t.filter(r=>ty.has(r)||e==="array"&&r==="array"):[]}function XT(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,B._)`typeof ${o}`),a=n.let("coerced",(0,B._)`undefined`);s.coerceTypes==="array"&&n.if((0,B._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,B._)`${o}[0]`).assign(i,(0,B._)`typeof ${o}`).if(fd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,B._)`${a} !== undefined`);for(let u of r)(ty.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),pd(t),n.endIf(),n.if((0,B._)`${a} !== undefined`,()=>{n.assign(o,a),YT(t,a)});function c(u){switch(u){case"string":n.elseIf((0,B._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,B._)`"" + ${o}`).elseIf((0,B._)`${o} === null`).assign(a,(0,B._)`""`);return;case"number":n.elseIf((0,B._)`${i} == "boolean" || ${o} === null
|
|
32
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,B._)`+${o}`);return;case"integer":n.elseIf((0,B._)`${i} === "boolean" || ${o} === null
|
|
33
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,B._)`+${o}`);return;case"boolean":n.elseIf((0,B._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,B._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,B._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,B._)`${i} === "string" || ${i} === "number"
|
|
34
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,B._)`[${o}]`)}}}function YT({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,B._)`${e} !== undefined`,()=>t.assign((0,B._)`${e}[${r}]`,n))}function dd(t,e,r,n=Fn.Correct){let o=n===Fn.Correct?B.operators.EQ:B.operators.NEQ,s;switch(t){case"null":return(0,B._)`${e} ${o} null`;case"array":s=(0,B._)`Array.isArray(${e})`;break;case"object":s=(0,B._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,B._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,B._)`typeof ${e} ${o} ${t}`}return n===Fn.Correct?s:(0,B.not)(s);function i(a=B.nil){return(0,B.and)((0,B._)`typeof ${e} == "number"`,a,r?(0,B._)`isFinite(${e})`:B.nil)}}De.checkDataType=dd;function fd(t,e,r,n){if(t.length===1)return dd(t[0],e,r,n);let o,s=(0,Qg.toHash)(t);if(s.array&&s.object){let i=(0,B._)`typeof ${e} != "object"`;o=s.null?i:(0,B._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=B.nil;s.number&&delete s.integer;for(let i in s)o=(0,B.and)(o,dd(i,e,r,n));return o}De.checkDataTypes=fd;var QT={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,B._)`{type: ${t}}`:(0,B._)`{type: ${e}}`};function pd(t){let e=eE(t);(0,JT.reportError)(e,QT)}De.reportTypeError=pd;function eE(t){let{gen:e,data:r,schema:n}=t,o=(0,Qg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ny=E(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.assignDefaults=void 0;var Un=J(),tE=re();function rE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)ry(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>ry(t,s,o.default))}Zi.assignDefaults=rE;function ry(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Un._)`${s}${(0,Un.getProperty)(e)}`;if(o){(0,tE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Un._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Un._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Un._)`${a} = ${(0,Un.stringify)(r)}`)}});var ft=E(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ge=J(),md=re(),vr=er(),nE=re();function oE(t,e){let{gen:r,data:n,it:o}=t;r.if(gd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}le.checkReportMissingProp=oE;function sE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(gd(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}le.checkMissingProp=sE;function iE(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=iE;function oy(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=oy;function hd(t,e,r){return(0,ge._)`${oy(t)}.call(${e}, ${r})`}le.isOwnProperty=hd;function aE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${hd(t,e,r)}`:o}le.propertyInData=aE;function gd(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(hd(t,e,r))):o}le.noPropertyInData=gd;function sy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=sy;function cE(t,e){return sy(e).filter(r=>!(0,md.alwaysValidSchema)(t,e[r]))}le.schemaProperties=cE;function uE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,l=[[vr.default.instancePath,(0,ge.strConcat)(vr.default.instancePath,s)],[vr.default.parentData,i.parentData],[vr.default.parentDataProperty,i.parentDataProperty],[vr.default.rootData,vr.default.rootData]];i.opts.dynamicRef&&l.push([vr.default.dynamicAnchors,vr.default.dynamicAnchors]);let p=(0,ge._)`${d}, ${r.object(...l)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}le.callValidateCode=uE;var lE=(0,ge._)`new RegExp`;function dE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?lE:(0,nE.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=dE;function fE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:md.Type.Num},s),e.if((0,ge.not)(s),a)})}}le.validateArray=fE;function pE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,md.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}le.validateUnion=pE});var cy=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.validateKeywordUsage=Mt.validSchemaType=Mt.funcKeywordCode=Mt.macroKeywordCode=void 0;var Ve=J(),an=er(),mE=ft(),hE=Wo();function gE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=ay(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Mt.macroKeywordCode=gE;function yE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;vE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=ay(n,o,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)h(),e.modifying&&iy(t),g(()=>t.error());else{let _=e.async?m():f();e.modifying&&iy(t),g(()=>_E(t,_))}}function m(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,Ve._)`await `),v=>n.assign(l,!1).if((0,Ve._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ve._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Ve._)`${d}.errors`;return n.assign(_,null),h(Ve.nil),_}function h(_=e.async?(0,Ve._)`await `:Ve.nil){let v=c.opts.passContext?an.default.this:an.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Ve._)`${_}${(0,mE.callValidateCode)(t,d,v,y)}`,e.modifying)}function g(_){var v;n.if((0,Ve.not)((v=e.valid)!==null&&v!==void 0?v:l),_)}}Mt.funcKeywordCode=yE;function iy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function _E(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(an.default.vErrors,(0,Ve._)`${an.default.vErrors} === null ? ${e} : ${an.default.vErrors}.concat(${e})`).assign(an.default.errors,(0,Ve._)`${an.default.vErrors}.length`),(0,hE.extendErrors)(t)},()=>t.error())}function vE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ay(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function xE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Mt.validSchemaType=xE;function bE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Mt.validateKeywordUsage=bE});var ly=E(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.extendSubschemaMode=xr.extendSubschemaData=xr.getSubschema=void 0;var jt=J(),uy=re();function wE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}${(0,jt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,uy.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}xr.getSubschema=wE;function $E(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,p=a.let("data",(0,jt._)`${e.data}${(0,jt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,jt.str)`${u}${(0,uy.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,jt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof jt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}xr.extendSubschemaData=$E;function kE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}xr.extendSubschemaMode=kE});var yd=E((g2,dy)=>{"use strict";dy.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var py=E((y2,fy)=>{"use strict";var br=fy.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Di(e,n,o,t,"",t)};br.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};br.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};br.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};br.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Di(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in br.arrayKeywords)for(var p=0;p<l.length;p++)Di(t,e,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in br.propsKeywords){if(l&&typeof l=="object")for(var m in l)Di(t,e,r,l[m],o+"/"+d+"/"+SE(m),s,o,d,n,m)}else(d in br.keywords||t.allKeys&&!(d in br.skipKeywords))&&Di(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function SE(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Xo=E(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var TE=re(),EE=yd(),zE=py(),PE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function RE(t,e=!0){return typeof t=="boolean"?!0:e===!0?!_d(t):e?my(t)<=e:!1}et.inlineRef=RE;var IE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _d(t){for(let e in t){if(IE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(_d)||typeof r=="object"&&_d(r))return!0}return!1}function my(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!PE.has(r)&&(typeof t[r]=="object"&&(0,TE.eachItem)(t[r],n=>e+=my(n)),e===1/0))return 1/0}return e}function hy(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return gy(t,n)}et.getFullPath=hy;function gy(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=gy;var CE=/#\/?$/;function Hn(t){return t?t.replace(CE,""):""}et.normalizeId=Hn;function OE(t,e,r){return r=Hn(r),t.resolve(e,r)}et.resolveUrl=OE;var AE=/^[a-z_][-a-z0-9._]*$/i;function NE(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=hy(n,o,!1),a={},c=new Set;return zE(t,{allKeys:!0},(l,p,m,f)=>{if(f===void 0)return;let h=i+p,g=s[f];typeof l[r]=="string"&&(g=_.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),s[p]=g;function _(y){let x=this.opts.uriResolver.resolve;if(y=Hn(g?x(g,y):y),c.has(y))throw d(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(l,$.schema,y):y!==Hn(h)&&(y[0]==="#"?(u(l,a[y],y),a[y]=l):this.refs[y]=h),y}function v(y){if(typeof y=="string"){if(!AE.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(l,p,m){if(p!==void 0&&!EE(l,p))throw d(m)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}et.getSchemaRefs=NE});var es=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.getData=wr.KeywordCxt=wr.validateFunctionCode=void 0;var by=Gg(),yy=Go(),xd=ld(),Li=Go(),ME=ny(),Qo=cy(),vd=ly(),j=J(),F=er(),jE=Xo(),tr=re(),Yo=Wo();function ZE(t){if(ky(t)&&(Sy(t),$y(t))){qE(t);return}wy(t,()=>(0,by.topBoolOrEmptySchema)(t))}wr.validateFunctionCode=ZE;function wy({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,j._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${_y(r,o)}`),LE(t,o),t.code(s)}):t.func(e,(0,j._)`${F.default.data}, ${DE(o)}`,n.$async,()=>t.code(_y(r,o)).code(s))}function DE(t){return(0,j._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,j._)`, ${F.default.dynamicAnchors}={}`:j.nil}}={}`}function LE(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,j._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,j._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,j._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,j._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,j._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,j._)`""`),t.var(F.default.parentData,(0,j._)`undefined`),t.var(F.default.parentDataProperty,(0,j._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,j._)`{}`)})}function qE(t){let{schema:e,opts:r,gen:n}=t;wy(t,()=>{r.$comment&&e.$comment&&Ey(t),VE(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&FE(t),Ty(t),WE(t)})}function FE(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function _y(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function UE(t,e){if(ky(t)&&(Sy(t),$y(t))){HE(t,e);return}(0,by.boolOrEmptySchema)(t,e)}function $y({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function ky(t){return typeof t.schema!="boolean"}function HE(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Ey(t),JE(t),KE(t);let s=n.const("_errs",F.default.errors);Ty(t,s),n.var(e,(0,j._)`${s} === ${F.default.errors}`)}function Sy(t){(0,tr.checkUnknownRules)(t),BE(t)}function Ty(t,e){if(t.opts.jtd)return vy(t,[],!1,e);let r=(0,yy.getSchemaTypes)(t.schema),n=(0,yy.coerceAndCheckDataType)(t,r);vy(t,r,!n,e)}function BE(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,tr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function VE(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,tr.checkStrictMode)(t,"default is ignored in the schema root")}function JE(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,jE.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function KE(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ey({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,j._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function WE(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,j._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,j._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,F.default.vErrors),s.unevaluated&&GE(t),e.return((0,j._)`${F.default.errors} === 0`))}function GE({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function vy(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,tr.schemaHasRulesButRef)(s,d))){o.block(()=>Py(t,"$ref",d.all.$ref.definition));return}c.jtd||XE(t,e),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,xd.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Li.checkDataType)(p.type,i,c.strictNumbers)),xy(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Li.reportTypeError)(t)),o.endIf()):xy(t,p),a||o.if((0,j._)`${F.default.errors} === ${n||0}`))}}function xy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,ME.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,xd.shouldUseRule)(n,s)&&Py(t,s.keyword,s.definition,e.type)})}function XE(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(YE(t,e),t.opts.allowUnionTypes||QE(t,e),ez(t,t.dataTypes))}function YE(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{zy(t.dataTypes,r)||bd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),rz(t,e)}}function QE(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&bd(t,"use allowUnionTypes to allow union type keyword")}function ez(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,xd.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>tz(e,i))&&bd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function tz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function zy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function rz(t,e){let r=[];for(let n of t.dataTypes)zy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function bd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,tr.checkStrictMode)(t,e,t.opts.strictTypes)}var qi=class{constructor(e,r,n){if((0,Qo.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,tr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Ry(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Qo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,j.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,j.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,j._)`${r} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Yo.reportExtraError:Yo.reportError)(this,this.def.error,r)}$dataError(){(0,Yo.reportError)(this,this.def.$dataError||Yo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Yo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,j.or)((0,j._)`${o} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Li.checkDataTypes)(c,r,s.opts.strictNumbers,Li.DataType.Wrong)}`}return j.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,vd.getSubschema)(this.it,e);(0,vd.extendSubschemaData)(n,this.it,e),(0,vd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return UE(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=tr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=tr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,j.Name)),!0}};wr.KeywordCxt=qi;function Py(t,e,r,n){let o=new qi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Qo.funcKeywordCode)(o,r):"macro"in r?(0,Qo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Qo.funcKeywordCode)(o,r)}var nz=/^\/(?:[^~]|~0|~1)*$/,oz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ry(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!nz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=oz.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,j._)`${s}${(0,j.getProperty)((0,tr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}wr.getData=Ry});var Fi=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var wd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};$d.default=wd});var ts=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var kd=Xo(),Sd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,kd.resolveUrl)(e,r,n),this.missingSchema=(0,kd.normalizeId)((0,kd.getFullPath)(e,this.missingRef))}};Td.default=Sd});var Hi=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var kt=J(),sz=Fi(),cn=er(),St=Xo(),Iy=re(),iz=es(),Bn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,St.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Bn;function zd(t){let e=Cy.call(this,t);if(e)return e;let r=(0,St.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:sz.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:cn.default.data,parentData:cn.default.parentData,parentDataProperty:cn.default.parentDataProperty,dataNames:[cn.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,iz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(cn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${cn.default.self}`,`${cn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof kt.Name?void 0:f,items:h instanceof kt.Name?void 0:h,dynamicProps:f instanceof kt.Name,dynamicItems:h instanceof kt.Name},m.source&&(m.source.evaluated=(0,kt.stringify)(m.evaluated))}return t.validate=m,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}pt.compileSchema=zd;function az(t,e,r){var n;r=(0,St.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=lz.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Bn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=cz.call(this,s)}pt.resolveRef=az;function cz(t){return(0,St.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:zd.call(this,t)}function Cy(t){for(let e of this._compilations)if(uz(e,t))return e}pt.getCompilingSchema=Cy;function uz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function lz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ui.call(this,t,e)}function Ui(t,e){let r=this.opts.uriResolver.parse(e),n=(0,St._getFullPath)(this.opts.uriResolver,r),o=(0,St.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ed.call(this,r,t);let s=(0,St.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ui.call(this,t,i);return typeof a?.schema!="object"?void 0:Ed.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||zd.call(this,i),s===(0,St.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,St.resolveUrl)(this.opts.uriResolver,o,u)),new Bn({schema:a,schemaId:c,root:t,baseId:o})}return Ed.call(this,r,i)}}pt.resolveSchema=Ui;var dz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ed(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Iy.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!dz.has(a)&&u&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Iy.schemaHasRulesButRef)(r,this.RULES)){let a=(0,St.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ui.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Bn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Oy=E(($2,fz)=>{fz.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ad=E((k2,Ly)=>{"use strict";var pz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Rd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),mz=RegExp.prototype.test.bind(/^\d*$/u),un=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Id=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ny=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Cd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),hz=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)tt[e]="%"+t[e>>4]+t[e&15]}function Le(t){return t<2048?tt[192|t>>6]+tt[128|t&63]:t<65536?tt[224|t>>12]+tt[128|t>>6&63]+tt[128|t&63]:tt[240|t>>18]+tt[128|t>>12&63]+tt[128|t>>6&63]+tt[128|t&63]}function gz(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var yz=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),_z=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),vz=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),xz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function bz(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!vz(t[e])){if(t[e]==="%"&&e+2<t.length&&un(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Ay(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function wz(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!Rd(c))return;s+=2;continue}if(!yz(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Ay(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return Ay(i)}function Pd(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&_z(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if($z(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!bz(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=wz(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function $z(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function kz(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var Sz={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Tz=/[@/?#:]/g,Ez=/[@/?#]/g;function My(t,e){let r=e?Ez:Tz;return r.lastIndex=0,t.replace(r,n=>Sz[n])}function jy(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(un(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Id(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function zz(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(un(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Id(i)?e+=i:e+="%"+s,r+=2;continue}}if(Ny(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Dy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function Pz(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(un(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Ny(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=Le(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Le(65536+(i-55296<<10)+(a-56320)),o++):r+=Le(65533)}else r+=Le(65533)}}return r}function Od(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(un(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=Le(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Le(65536+(s-55296<<10)+(i-56320)),n++):r+=Le(65533)}else r+=Le(65533)}}return r}function Zy(t){return Od(t,hz)}function Rz(t){return Od(t,Cd)}function Iz(t){return Od(t,Cd)}function Dy(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function Cz(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(un(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Id(i)?e+=i:e+="%"+s,r+=2;continue}}if(Cd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Dy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function Oz(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(un(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Az(t){let e=[];if(t.userinfo!==void 0&&(e.push(Zy(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Rd(r)){let n=Pd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=jy(r,!0),n=Pd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=My(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!mz(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}Ly.exports={nonSimpleDomain:xz,recomposeAuthority:Az,reescapeHostDelimiters:My,normalizePercentEncoding:jy,normalizePathEncoding:zz,serializePathEncoding:Pz,normalizeQueryFragmentEncoding:Cz,encodeUserinfo:Zy,encodeQuery:Rz,encodeFragment:Iz,escapePreservingEscapes:Oz,removeDotSegments:kz,isIPv4:Rd,isUUID:pz,normalizeIPv6:Pd,stringArrayToHexStripped:gz}});var By=E((S2,Hy)=>{"use strict";var{isUUID:Nz}=Ad(),Mz=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,jz=["http","https","ws","wss","urn","urn:uuid"];function Zz(t){return jz.indexOf(t)!==-1}function Nd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function qy(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Fy(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Dz(t){return t.secure=Nd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Lz(t){if((t.port===(Nd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function qz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Mz);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Md(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Fz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Md(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Uz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Nz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Hz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Uy={scheme:"http",domainHost:!0,parse:qy,serialize:Fy},Bz={scheme:"https",domainHost:Uy.domainHost,parse:qy,serialize:Fy},Bi={scheme:"ws",domainHost:!0,parse:Dz,serialize:Lz},Vz={scheme:"wss",domainHost:Bi.domainHost,parse:Bi.parse,serialize:Bi.serialize},Jz={scheme:"urn",parse:qz,serialize:Fz,skipNormalize:!0},Kz={scheme:"urn:uuid",parse:Uz,serialize:Hz,skipNormalize:!0},Vi={http:Uy,https:Bz,ws:Bi,wss:Vz,urn:Jz,"urn:uuid":Kz};Object.setPrototypeOf(Vi,null);function Md(t){return t&&(Vi[t]||Vi[t.toLowerCase()])||void 0}Hy.exports={wsIsSecure:Nd,SCHEMES:Vi,isValidSchemeName:Zz,getSchemeHandler:Md}});var o_=E((T2,Wi)=>{"use strict";var{normalizeIPv6:Gy,removeDotSegments:ns,recomposeAuthority:Wz,normalizePercentEncoding:jd,normalizePathEncoding:Gz,serializePathEncoding:Vy,normalizeQueryFragmentEncoding:Jy,encodeQuery:Xz,encodeFragment:Yz,reescapeHostDelimiters:Qz,isIPv4:Xy,nonSimpleDomain:eP}=Ad(),{SCHEMES:Yy,getSchemeHandler:Zd}=By(),Qy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,e_="URI scheme is malformed.";function Ky(t){let e=unescape(String(t));if(!Qy.test(e))throw new TypeError(e_);return e}function tP(t,e){return typeof t=="string"?t=uP(t,e):typeof t=="object"&&(t=Ki(ln(t,e),e)),t}function rP(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Ji(t,n),{parsed:d,malformedAuthorityOrPort:l,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=Ji(e,n);if(s||l||i||p||a||m||c||f||u||h)throw new Error(o.error||d.error||"URI is malformed.");let g=t_(o,d,n,!0),_=Zd(r&&r.scheme||g.scheme),v=g.host,y=v!==void 0&&v!==""&&(Xy(v)||Gy(v).isIPV6);r_(g,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(g.error&&!x)throw new Error(g.error);return n.skipEscape=!0,ln(g,n)}function t_(t,e,r,n){let o={};return n||(t=Ki(ln(t,r),r),e=Ki(ln(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ns(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ns(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ns(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ns(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function nP(t,e,r){let n=Wy(t,r),o=Wy(e,r);return n!==void 0&&o!==void 0&&n===o}function ln(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[];r.scheme&&(r.scheme=Ky(r.scheme));let s=Zd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=jd(r.path):r.path=Vy(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=Ky(r.scheme),o.push(r.scheme,":"));let c=Wz(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=ns(u)),a&&(u=Vy(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",Xz(r.query)),r.fragment!==void 0&&o.push("#",Yz(r.fragment)),o.join("")}var oP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,iP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function aP(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function rs(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function Dd(t){return t[0]==="["&&t[t.length-1]==="]"}function cP(t){let e=t[4];return rs(t[3])||e!==void 0&&!Dd(e)&&rs(e)||rs(t[6])||rs(t[7])||rs(t[8])}function r_(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!Dd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&eP(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Ji(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,d=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let l=t.match(sP);l!==null&&l[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(iP);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(oP);if(m){if(n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0){let g=unescape(n.scheme);Qy.test(g)?n.scheme=g.toLowerCase():(n.error=n.error||e_,u=!0)}s=cP(m),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let f=aP(n,m);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(Xy(n.host)===!1){let _=Dd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=Gy(n.host);d=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=d?y.host:y.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",o=!0)}else d=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=Zd(r.scheme||n.scheme);if(c||(a=r_(n,r,h,d)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=d?n.host:jd(n.host,!0);d||(g=jd(g.toLowerCase())),n.host=Qz(g,d)}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=Gz(n.path)),n.query&&(n.query=Jy(n.query)),n.fragment&&(n.fragment=Jy(n.fragment))),h&&h.parse&&(h.parse(n,r),h===Yy.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ki(t,e){return Ji(t,e).parsed}function uP(t,e){return n_(t,e).normalized}function n_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Ji(t,e);return{normalized:n||o||s||i||a?t:ln(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function Wy(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:ln(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=n_(r,e);return o||s||i||a||c?void 0:n}var Ld={SCHEMES:Yy,normalize:tP,resolve:rP,resolveComponent:t_,equal:nP,serialize:ln,parse:Ki};Wi.exports=Ld;Wi.exports.default=Ld;Wi.exports.fastUri=Ld});var i_=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var s_=o_();s_.code='require("ajv/dist/runtime/uri").default';qd.default=s_});var m_=E(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var lP=es();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return lP.KeywordCxt}});var Vn=J();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return Vn._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return Vn.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return Vn.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return Vn.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return Vn.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return Vn.CodeGen}});var dP=Fi(),d_=ts(),fP=ud(),os=Hi(),pP=J(),ss=Xo(),Gi=Go(),Ud=re(),a_=Oy(),mP=i_(),f_=(t,e)=>new RegExp(t,e);f_.code="new RegExp";var hP=["removeAdditional","useDefaults","coerceTypes"],gP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yP={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},_P={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},c_=200;function vP(t){var e,r,n,o,s,i,a,c,u,d,l,p,m,f,h,g,_,v,y,x,$,C,R,ae,ce;let Ee=t.strict,U=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=U===!0||U===void 0?1:U||0,Pt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:f_,Rr=(o=t.uriResolver)!==null&&o!==void 0?o:mP.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ee)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ee)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Ee)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:Ee)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:Ee)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:Pt}:{optimize:_e,regExp:Pt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:c_,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:c_,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:Rr}}var is=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...vP(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new pP.ValueScope({scope:{},prefixes:gP,es5:r,lines:n}),this.logger=SP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,fP.getRules)(),u_.call(this,yP,e,"NOT SUPPORTED"),u_.call(this,_P,e,"DEPRECATED","warn"),this._metaOpts=$P.call(this),e.formats&&bP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xP.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=a_;n==="id"&&(o={...a_},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof d_.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ss.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=l_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new os.SchemaEnv({schema:{},schemaId:n});if(r=os.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=l_.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ss.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(EP.call(this,n,r),!r)return(0,Ud.eachItem)(n,s=>Fd.call(this,s)),this;PP.call(this,r);let o={...r,type:(0,Gi.getJSONTypes)(r.type),schemaType:(0,Gi.getJSONTypes)(r.schemaType)};return(0,Ud.eachItem)(n,o.type.length===0?s=>Fd.call(this,s,o):s=>o.type.forEach(i=>Fd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=p_(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ss.normalizeId)(i||n);let u=ss.getSchemaRefs.call(this,e,n);return c=new os.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):os.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{os.compileSchema.call(this,e)}finally{this.opts=r}}};is.ValidationError=dP.default;is.MissingRefError=d_.default;Oe.default=is;function u_(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function l_(t){return t=(0,ss.normalizeId)(t),this.schemas[t]||this.refs[t]}function xP(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function bP(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wP(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function $P(){let t={...this.opts};for(let e of hP)delete t[e];return t}var kP={log(){},warn(){},error(){}};function SP(t){if(t===!1)return kP;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var TP=/^[a-z_$][a-z0-9_$:-]*$/i;function EP(t,e){let{RULES:r}=this;if((0,Ud.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!TP.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Fd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Gi.getJSONTypes)(e.type),schemaType:(0,Gi.getJSONTypes)(e.schemaType)}};e.before?zP.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function zP(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function PP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=p_(e)),t.validateSchema=this.compile(e,!0))}var RP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function p_(t){return{anyOf:[t,RP]}}});var h_=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var IP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Hd.default=IP});var v_=E(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.callRef=dn.getValidate=void 0;var CP=ts(),g_=ft(),rt=J(),Jn=er(),y_=Hi(),Xi=re(),OP={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=y_.resolveRef.call(c,u,o,r);if(d===void 0)throw new CP.default(n.opts.uriResolver,o,r);if(d instanceof y_.SchemaEnv)return p(d);return m(d);function l(){if(s===u)return Yi(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Yi(t,(0,rt._)`${f}.validate`,u,u.$async)}function p(f){let h=__(t,f);Yi(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,rt.stringify)(f)}:{ref:f}),g=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:rt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(_),t.ok(g)}}};function __(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}dn.getValidate=__;function Yi(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Jn.default.this:rt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,rt._)`await ${(0,g_.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,rt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function l(){t.result((0,g_.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,rt._)`${f}.errors`;o.assign(Jn.default.vErrors,(0,rt._)`${Jn.default.vErrors} === null ? ${h} : ${Jn.default.vErrors}.concat(${h})`),o.assign(Jn.default.errors,(0,rt._)`${Jn.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Xi.mergeEvaluated.props(o,g.props,s.props));else{let _=o.var("props",(0,rt._)`${f}.evaluated.props`);s.props=Xi.mergeEvaluated.props(o,_,s.props,rt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Xi.mergeEvaluated.items(o,g.items,s.items));else{let _=o.var("items",(0,rt._)`${f}.evaluated.items`);s.items=Xi.mergeEvaluated.items(o,_,s.items,rt.Name)}}}dn.callRef=Yi;dn.default=OP});var x_=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var AP=h_(),NP=v_(),MP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",AP.default,NP.default];Bd.default=MP});var b_=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Qi=J(),$r=Qi.operators,ea={maximum:{okStr:"<=",ok:$r.LTE,fail:$r.GT},minimum:{okStr:">=",ok:$r.GTE,fail:$r.LT},exclusiveMaximum:{okStr:"<",ok:$r.LT,fail:$r.GTE},exclusiveMinimum:{okStr:">",ok:$r.GT,fail:$r.LTE}},jP={message:({keyword:t,schemaCode:e})=>(0,Qi.str)`must be ${ea[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qi._)`{comparison: ${ea[t].okStr}, limit: ${e}}`},ZP={keyword:Object.keys(ea),type:"number",schemaType:"number",$data:!0,error:jP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Qi._)`${r} ${ea[e].fail} ${n} || isNaN(${r})`)}};Vd.default=ZP});var w_=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var as=J(),DP={message:({schemaCode:t})=>(0,as.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,as._)`{multipleOf: ${t}}`},LP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:DP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,as._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,as._)`${i} !== parseInt(${i})`;t.fail$data((0,as._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Jd.default=LP});var k_=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});function $_(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Kd.default=$_;$_.code='require("ajv/dist/runtime/ucs2length").default'});var S_=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var fn=J(),qP=re(),FP=k_(),UP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,fn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,fn._)`{limit: ${t}}`},HP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:UP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?fn.operators.GT:fn.operators.LT,i=o.opts.unicode===!1?(0,fn._)`${r}.length`:(0,fn._)`${(0,qP.useFunc)(t.gen,FP.default)}(${r})`;t.fail$data((0,fn._)`${i} ${s} ${n}`)}};Wd.default=HP});var T_=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var BP=ft(),VP=re(),Kn=J(),JP={message:({schemaCode:t})=>(0,Kn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Kn._)`{pattern: ${t}}`},KP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:JP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Kn._)`new RegExp`:(0,VP.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Kn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Kn._)`!${d}`)}else{let c=(0,BP.usePattern)(t,o);t.fail$data((0,Kn._)`!${c}.test(${r})`)}}};Gd.default=KP});var E_=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var cs=J(),WP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,cs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},GP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:WP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`Object.keys(${r}).length ${o} ${n}`)}};Xd.default=GP});var z_=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var us=ft(),ls=J(),XP=re(),YP={message:({params:{missingProperty:t}})=>(0,ls.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ls._)`{missingProperty: ${t}}`},QP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:YP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(m?.[h]===void 0&&!f.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,XP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ls.nil,l);else for(let m of r)(0,us.checkReportMissingProp)(t,m)}function d(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,us.checkMissingProp)(t,r,m)),(0,us.reportMissingProp)(t,m),e.else()}function l(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,us.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,us.propertyInData)(e,o,m,a.ownProperties)),e.if((0,ls.not)(f),()=>{t.error(),e.break()})},ls.nil)}}};Yd.default=QP});var P_=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var ds=J(),eR={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ds.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ds._)`{limit: ${t}}`},tR={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:eR,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ds.operators.GT:ds.operators.LT;t.fail$data((0,ds._)`${r}.length ${o} ${n}`)}};Qd.default=tR});var ta=E(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var R_=yd();R_.code='require("ajv/dist/runtime/equal").default';ef.default=R_});var I_=E(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var tf=Go(),Ae=J(),rR=re(),nR=ta(),oR={message:({params:{i:t,j:e}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ae._)`{i: ${t}, j: ${e}}`},sR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:oR,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,tf.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Ae._)`${i} === false`),t.ok(c);function d(){let f=e.let("i",(0,Ae._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,Ae._)`${f} > 1`,()=>(l()?p:m)(f,h))}function l(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let g=e.name("item"),_=(0,tf.checkDataTypes)(u,g,a.opts.strictNumbers,tf.DataType.Wrong),v=e.const("indices",(0,Ae._)`{}`);e.for((0,Ae._)`;${f}--;`,()=>{e.let(g,(0,Ae._)`${r}[${f}]`),e.if(_,(0,Ae._)`continue`),u.length>1&&e.if((0,Ae._)`typeof ${g} == "string"`,(0,Ae._)`${g} += "_"`),e.if((0,Ae._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,Ae._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Ae._)`${v}[${g}] = ${f}`)})}function m(f,h){let g=(0,rR.useFunc)(e,nR.default),_=e.name("outer");e.label(_).for((0,Ae._)`;${f}--;`,()=>e.for((0,Ae._)`${h} = ${f}; ${h}--;`,()=>e.if((0,Ae._)`${g}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};rf.default=sR});var C_=E(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var nf=J(),iR=re(),aR=ta(),cR={message:"must be equal to constant",params:({schemaCode:t})=>(0,nf._)`{allowedValue: ${t}}`},uR={keyword:"const",$data:!0,error:cR,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,nf._)`!${(0,iR.useFunc)(e,aR.default)}(${r}, ${o})`):t.fail((0,nf._)`${s} !== ${r}`)}};of.default=uR});var O_=E(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var fs=J(),lR=re(),dR=ta(),fR={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,fs._)`{allowedValues: ${t}}`},pR={keyword:"enum",schemaType:"array",$data:!0,error:fR,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,lR.useFunc)(e,dR.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);d=(0,fs.or)(...o.map((f,h)=>p(m,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,m=>e.if((0,fs._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,fs._)`${u()}(${r}, ${m}[${f}])`:(0,fs._)`${r} === ${h}`}}};sf.default=pR});var A_=E(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var mR=b_(),hR=w_(),gR=S_(),yR=T_(),_R=E_(),vR=z_(),xR=P_(),bR=I_(),wR=C_(),$R=O_(),kR=[mR.default,hR.default,gR.default,yR.default,_R.default,vR.default,xR.default,bR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wR.default,$R.default];af.default=kR});var uf=E(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateAdditionalItems=void 0;var pn=J(),cf=re(),SR={message:({params:{len:t}})=>(0,pn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pn._)`{limit: ${t}}`},TR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:SR,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,cf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}N_(t,n)}};function N_(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,pn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,pn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,cf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,pn._)`${a} <= ${e.length}`);r.if((0,pn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:cf.Type.Num},u),i.allErrors||r.if((0,pn.not)(u),()=>r.break())})}}ps.validateAdditionalItems=N_;ps.default=TR});var lf=E(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateTuple=void 0;var M_=J(),ra=re(),ER=ft(),zR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return j_(t,"additionalItems",e);r.items=!0,!(0,ra.alwaysValidSchema)(r,e)&&t.ok((0,ER.validateArray)(t))}};function j_(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ra.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,M_._)`${s}.length`);r.forEach((l,p)=>{(0,ra.alwaysValidSchema)(a,l)||(n.if((0,M_._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:m}=a,f=r.length,h=f===l.minItems&&(f===l.maxItems||l[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,ra.checkStrictMode)(a,g,p.strictTuples)}}}ms.validateTuple=j_;ms.default=zR});var Z_=E(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var PR=lf(),RR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,PR.validateTuple)(t,"items")};df.default=RR});var L_=E(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var D_=J(),IR=re(),CR=ft(),OR=uf(),AR={message:({params:{len:t}})=>(0,D_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,D_._)`{limit: ${t}}`},NR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:AR,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,IR.alwaysValidSchema)(n,e)&&(o?(0,OR.validateAdditionalItems)(t,o):t.ok((0,CR.validateArray)(t)))}};ff.default=NR});var q_=E(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var mt=J(),na=re(),MR={message:({params:{min:t,max:e}})=>e===void 0?(0,mt.str)`must contain at least ${t} valid item(s)`:(0,mt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,mt._)`{minContains: ${t}}`:(0,mt._)`{minContains: ${t}, maxContains: ${e}}`},jR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:MR,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,mt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,na.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,na.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,na.alwaysValidSchema)(s,r)){let h=(0,mt._)`${d} >= ${i}`;a!==void 0&&(h=(0,mt._)`${h} && ${d} <= ${a}`),t.pass(h);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?m(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,mt._)`${o}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>f(g)))}function m(h,g){e.forRange("i",0,d,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:na.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,mt._)`${h}++`),a===void 0?e.if((0,mt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,mt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,mt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};pf.default=jR});var H_=E(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateSchemaDeps=Zt.validatePropertyDeps=Zt.error=void 0;var mf=J(),ZR=re(),hs=ft();Zt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,mf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,mf._)`{property: ${t},
|
|
35
35
|
missingProperty: ${n},
|
|
36
36
|
depsCount: ${e},
|
|
37
|
-
deps: ${r}}`};var SP={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=EP(t);s_(t,e),i_(t,r)}};function EP({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function s_(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,os.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,os.checkReportMissingProp)(t,u)}):(r.if((0,Ld._)`${c} && (${(0,os.checkMissingProp)(t,a,s)})`),(0,os.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=s_;function i_(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,kP.alwaysValidSchema)(s,e[a])||(r.if((0,os.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=i_;Ot.default=SP});var u_=T(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var c_=B(),TP=re(),zP={message:"property name must be valid",params:({params:t})=>(0,c_._)`{propertyName: ${t.propertyName}}`},PP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,TP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,c_.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=PP});var Hd=T(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Vi=ut(),bt=B(),RP=Jt(),Bi=re(),IP={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},OP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Bi.alwaysValidSchema)(i,r))return;let u=(0,Vi.allSchemaProperties)(n.properties),l=(0,Vi.allSchemaProperties)(n.patternProperties);d(),t.ok((0,bt._)`${s} === ${RP.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?f(y):e.if(p(y),()=>f(y))})}function p(y){let _;if(u.length>8){let v=(0,Bi.schemaRefOrVal)(i,n.properties,"properties");_=(0,Vi.isOwnProperty)(e,v,y)}else u.length?_=(0,bt.or)(...u.map(v=>(0,bt._)`${y} === ${v}`)):_=bt.nil;return l.length&&(_=(0,bt.or)(_,...l.map(v=>(0,bt._)`${(0,Vi.usePattern)(t,v)}.test(${y})`))),(0,bt.not)(_)}function m(y){e.code((0,bt._)`delete ${o}[${y}]`)}function f(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Bi.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(y,_,!1),e.if((0,bt.not)(_),()=>{t.reset(),m(y)})):(h(y,_),a||e.if((0,bt.not)(_),()=>e.break()))}}function h(y,_,v){let g={keyword:"additionalProperties",dataProp:y,dataPropType:Bi.Type.Str};v===!1&&Object.assign(g,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(g,_)}}};Fd.default=OP});var f_=T(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var CP=Fo(),l_=ut(),Vd=re(),d_=Hd(),AP={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&d_.default.code(new CP.KeywordCxt(s,d_.default,"additionalProperties"));let i=(0,l_.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Vd.mergeEvaluated.props(e,(0,Vd.toHash)(i),s.props));let a=i.filter(d=>!(0,Vd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,l_.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Bd.default=AP});var g_=T(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var p_=ut(),Ji=B(),m_=re(),h_=re(),NP={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,p_.allSchemaProperties)(r),c=a.filter(h=>(0,m_.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ji.Name)&&(s.props=(0,h_.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function m(h){for(let y in u)new RegExp(h).test(y)&&(0,m_.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,y=>{e.if((0,Ji._)`${(0,p_.usePattern)(t,h)}.test(${y})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:h_.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ji._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Ji.not)(l),()=>e.break())})})}}};Jd.default=NP});var y_=T(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var MP=re(),jP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,MP.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Wd.default=jP});var __=T(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var ZP=ut(),DP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ZP.validateUnion,error:{message:"must match a schema in anyOf"}};Kd.default=DP});var v_=T(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Wi=B(),qP=re(),LP={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wi._)`{passingSchemas: ${t.passing}}`},UP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:LP,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,qP.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wi._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wi._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wi.Name)})})}}};Gd.default=UP});var x_=T(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var FP=re(),HP={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,FP.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Xd.default=HP});var $_=T(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Ki=B(),w_=re(),VP={message:({params:t})=>(0,Ki.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ki._)`{failingKeyword: ${t.ifClause}}`},BP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VP,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,w_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=b_(n,"then"),s=b_(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ki.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ki._)`${l}`):t.setParams({ifClause:l})}}}};function b_(t,e){let r=t.schema[e];return r!==void 0&&!(0,w_.alwaysValidSchema)(t,r)}Yd.default=BP});var k_=T(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var JP=re(),WP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,JP.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qd.default=WP});var S_=T(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var KP=Md(),GP=t_(),XP=jd(),YP=n_(),QP=o_(),eR=a_(),tR=u_(),rR=Hd(),nR=f_(),oR=g_(),sR=y_(),iR=__(),aR=v_(),cR=x_(),uR=$_(),lR=k_();function dR(t=!1){let e=[sR.default,iR.default,aR.default,cR.default,uR.default,lR.default,tR.default,rR.default,eR.default,nR.default,oR.default];return t?e.push(GP.default,YP.default):e.push(KP.default,XP.default),e.push(QP.default),e}ef.default=dR});var E_=T(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ke=B(),fR={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},pR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:fR,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ke._)`${f}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${h}.type || "string"`).assign(_,(0,ke._)`${h}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,h)),t.fail$data((0,ke.or)(v(),g()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function g(){let x=l.$async?(0,ke._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${$}`}}function m(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[h,y,_]=g(f);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function g($){let D=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:$,code:D});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${R}.validate`]:["string",$,R]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};tf.default=pR});var T_=T(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var mR=E_(),hR=[mR.default];rf.default=hR});var z_=T(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.contentVocabulary=Ln.metadataVocabulary=void 0;Ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var R_=T(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var gR=jy(),yR=Xy(),_R=S_(),vR=T_(),P_=z_(),xR=[gR.default,yR.default,(0,_R.default)(),vR.default,P_.metadataVocabulary,P_.contentVocabulary];nf.default=xR});var O_=T(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.DiscrError=void 0;var I_;(function(t){t.Tag="tag",t.Mapping="mapping"})(I_||(Gi.DiscrError=I_={}))});var A_=T(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var Un=B(),of=O_(),C_=Ii(),bR=Ho(),wR=re(),$R={message:({params:{discrError:t,tagName:e}})=>t===of.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Un._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},kR={keyword:"discriminator",type:"object",schemaType:"object",error:$R,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Un._)`${r}${(0,Un.getProperty)(a)}`);e.if((0,Un._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:of.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,Un._)`${u} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:of.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,Un.Name),f}function p(){var m;let f={},h=_(o),y=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,wR.schemaHasRulesButRef)($,s.self.RULES)){let R=$.$ref;if($=C_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),$ instanceof C_.SchemaEnv&&($=$.schema),$===void 0)throw new bR.default(s.opts.uriResolver,s.baseId,R)}let D=(m=$?.properties)===null||m===void 0?void 0:m[a];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||_($)),v(D,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,$){if(x.const)g(x.const,$);else if(x.enum)for(let D of x.enum)g(D,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function g(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};sf.default=kR});var N_=T((hD,SR)=>{SR.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var cf=T((ye,af)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var ER=Iy(),TR=R_(),zR=A_(),M_=N_(),PR=["/properties"],Xi="http://json-schema.org/draft-07/schema",Fn=class extends ER.default{_addVocabularies(){super._addVocabularies(),TR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(zR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(M_,PR):M_;this.addMetaSchema(e,Xi,!1),this.refs["http://json-schema.org/schema"]=Xi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xi)?Xi:void 0)}};ye.Ajv=Fn;af.exports=ye=Fn;af.exports.Ajv=Fn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Fn;var RR=Fo();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return RR.KeywordCxt}});var Hn=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var IR=Pi();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return IR.default}});var OR=Ho();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return OR.default}})});var H_=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.formatNames=At.fastFormats=At.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}At.fullFormats={date:Ct(q_,ff),time:Ct(lf(!0),pf),"date-time":Ct(j_(!0),U_),"iso-time":Ct(lf(),L_),"iso-date-time":Ct(j_(),F_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ZR,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:VR,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:DR,int32:{type:"number",validate:UR},int64:{type:"number",validate:FR},float:{type:"number",validate:D_},double:{type:"number",validate:D_},password:!0,binary:!0};At.fastFormats={...At.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ff),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pf),"date-time":Ct(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,U_),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,L_),"iso-date-time":Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,F_),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};At.formatNames=Object.keys(At.fullFormats);function CR(t){return t%4===0&&(t%100!==0||t%400===0)}var AR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function q_(t){let e=AR.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&CR(r)?29:NR[n])}function ff(t,e){if(t&&e)return t>e?1:t<e?-1:0}var uf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lf(t){return function(r){let n=uf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function pf(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function L_(t,e){if(!(t&&e))return;let r=uf.exec(t),n=uf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var df=/t|\s/i;function j_(t){let e=lf(t);return function(n){let o=n.split(df);return o.length===2&&q_(o[0])&&e(o[1])}}function U_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function F_(t,e){if(!(t&&e))return;let[r,n]=t.split(df),[o,s]=e.split(df),i=ff(r,o);if(i!==void 0)return i||pf(n,s)}var MR=/\/|:/,jR=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ZR(t){return MR.test(t)&&jR.test(t)}var Z_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DR(t){return Z_.lastIndex=0,Z_.test(t)}var qR=-(2**31),LR=2**31-1;function UR(t){return Number.isInteger(t)&&t<=LR&&t>=qR}function FR(t){return Number.isInteger(t)}function D_(){return!0}var HR=/[^\\]\\Z/;function VR(t){if(HR.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var V_=T(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.formatLimitDefinition=void 0;var BR=cf(),wt=B(),hr=wt.operators,Yi={formatMaximum:{okStr:"<=",ok:hr.LTE,fail:hr.GT},formatMinimum:{okStr:">=",ok:hr.GTE,fail:hr.LT},formatExclusiveMaximum:{okStr:"<",ok:hr.LT,fail:hr.GTE},formatExclusiveMinimum:{okStr:">",ok:hr.GT,fail:hr.LTE}},JR={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${Yi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${Yi[t].okStr}, limit: ${e}}`};Vn.formatLimitDefinition={keyword:Object.keys(Yi),type:"string",schemaType:"string",$data:!0,error:JR,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new BR.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,wt._)`${p}[${c.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${m} != "object"`,(0,wt._)`${m} instanceof RegExp`,(0,wt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,wt._)`${p}.compare(${r}, ${n}) ${Yi[o].fail} 0`}},dependencies:["format"]};var WR=t=>(t.addKeyword(Vn.formatLimitDefinition),t);Vn.default=WR});var K_=T((ss,W_)=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var Bn=H_(),KR=V_(),mf=B(),B_=new mf.Name("fullFormats"),GR=new mf.Name("fastFormats"),hf=(t,e={keywords:!0})=>{if(Array.isArray(e))return J_(t,e,Bn.fullFormats,B_),t;let[r,n]=e.mode==="fast"?[Bn.fastFormats,GR]:[Bn.fullFormats,B_],o=e.formats||Bn.formatNames;return J_(t,o,r,n),e.keywords&&(0,KR.default)(t),t};hf.get=(t,e="full")=>{let n=(e==="fast"?Bn.fastFormats:Bn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function J_(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,mf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}W_.exports=ss=hf;Object.defineProperty(ss,"__esModule",{value:!0});ss.default=hf});var Dv={};eo(Dv,{findEmbeddingModel:()=>Zv,ollamaUrl:()=>Rf,semanticRerank:()=>zI});import{createHash as yI}from"node:crypto";import{existsSync as _I,mkdirSync as vI,readFileSync as xI,writeFileSync as bI}from"node:fs";import{homedir as wI}from"node:os";import{join as Pf}from"node:path";function Rf(t=process.env.OLLAMA_HOST){let e=(t??"").trim(),r="http",n="11434",o=e.indexOf("://");o>=0&&(r=e.slice(0,o),e=e.slice(o+3),r==="http"?n="80":r==="https"&&(n="443"));let s=e.indexOf("/"),i=s>=0?e.slice(s).replace(/\/+$/,""):"",a=s>=0?e.slice(0,s):e,c=/^(\[[^\]]*\]|[^:]*):([^:]*)$/.exec(a);return c?(a=c[1],/^\d+$/.test(c[2])&&Number(c[2])<=65535&&(n=c[2])):a.includes(":")&&!a.startsWith("[")&&(a=`[${a}]`),!a||a==="0.0.0.0"?a="127.0.0.1":a==="[::]"&&(a="[::1]"),`${r}://${a}:${n}${i}`}async function jv(t,e,r=6e4){let n=await fetch(Rf()+t,{method:e?"POST":"GET",headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0,signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()}async function Zv(t){let r=((await jv("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>$I.test(n))}function pa(){return Pf(process.env.XDG_CACHE_HOME??Pf(wI(),".cache"),"context-doctor","embeddings.json")}function kI(){try{return _I(pa())?JSON.parse(xI(pa(),"utf8")):{}}catch{return{}}}function SI(t){try{let e=Object.keys(t);if(e.length>Mv)for(let r of e.slice(0,e.length-Mv))delete t[r];vI(Pf(pa(),".."),{recursive:!0}),bI(pa(),JSON.stringify(t))}catch{}}async function EI(t,e){let r=[];for(let n=0;n<e.length;n+=Nv){let o=await jv("/api/embed",{model:t,input:e.slice(n,n+Nv),truncate:!0});r.push(...o.embeddings)}return r}function TI(t,e){let r=0,n=0,o=0;for(let s=0;s<t.length;s++)r+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return n&&o?r/Math.sqrt(n*o):0}async function zI(t,e,r={}){let n;try{n=await Zv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${Rf()} (keyword ranking only)`}}if(!n)return{used:!1,note:"semantic ranking off: Ollama has no embedding model; run `ollama pull nomic-embed-text` (keyword ranking only)"};let o=kI(),s=f=>yI("sha1").update(n+"\0"+f).digest("hex"),i=t.map(f=>(f.heading?f.heading+`
|
|
38
|
-
`:"")+f.text),a=[...new Set(i.filter(f=>!o[s(f)]))],c,u;try{let f=await EI(n,[e,...a]);u=f[0],a.forEach((h,y)=>o[s(h)]=f[y+1]),c=i.map(h=>o[s(h)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&SI(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,h)=>h.score-f.score).map((f,h)=>[f,h])),p=t.map((f,h)=>({c:f,s:TI(u,c[h])})).sort((f,h)=>h.s-f.s),m=new Map(p.map((f,h)=>[f.c,h]));for(let f of t){let h=d.get(f);f.score=(h===void 0?0:1/(l+h))+1/(l+m.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var $I,Nv,Mv,qv=G(()=>{"use strict";$I=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Nv=64,Mv=5e4});var Kv,Gv=G(()=>{Kv="x-hono-already-sent"});var Xv,Yv=G(()=>{Xv=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{Http2ServerRequest as Xn,constants as sO}from"node:http2";import{Readable as Qv}from"node:stream";async function zO(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function f0(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(u){o(u)}}}function o0(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:f0(t.getReader(),e)}var Nt,iO,aO,cO,uO,lO,dO,Yn,i0,a0,fO,pO,Nf,Mf,c0,Uf,e0,_a,t0,mO,vr,Kt,Qn,ds,u0,l0,us,jf,Zf,_r,ya,Xt,r0,ls,va,fs,hO,gO,yO,_O,vO,xO,bO,Ff,wO,n0,$O,jt,kO,yr,Df,Gn,Gt,xa,Mt,SO,EO,TO,qf,ba,s0,PO,RO,p0,IO,OO,CO,m0,wa,Lf,h0,g0,AO,Hf,NO,MO,jO,ZO,DO,X2,y0=G(()=>{Gv();Yv();Nt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},iO=/^\/[!#$&-;=?-\[\]_a-z~]*$/,aO=/\/\.\.?(?:[/?#]|$)/,cO=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,uO=(t,e,r)=>{let n=`${t}://${e}${r}`;if(cO.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Nt("Invalid URL");return!iO.test(r)||aO.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Nt("Invalid host header");return o.href}},lO=t=>t instanceof Nt?t:new Nt(t.message,{cause:t}),dO=global.Request,Yn=class extends dO{constructor(t,e){if(typeof t=="object"&&vr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[Xt]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[vr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},i0=t=>{let e=[],r=t.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&e.push([s,r[n+1]])}return new Headers(e)},a0=Symbol("wrapBodyStream"),fO=new Set(["latin1","binary","hex","base64","base64url"]),pO=t=>t===null||fO.has(t),Nf=Symbol("bodyBufferedBeforeDisconnect"),Mf=Symbol("bodyBufferedLengthBeforeDisconnect"),c0=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Uf=t=>!(t instanceof Xn)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&pO(t.readableEncoding),e0=t=>{if(t.readableDidRead||!Uf(t))return;let e=t;e[Mf]??=t.readableLength},_a=(t,e)=>{if(t.readableDidRead&&!e||!Uf(t))return;let r=t;if(r[Nf]!==void 0)return r[Nf];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Mf]!==void 0&&t.readableLength!==r[Mf])n=va();else{let s=e??[],i=t.read();i!==null&&s.push(c0(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=va())}}return r[Nf]=n,n},t0=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},mO=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new Yn(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[a0]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=_a(n);if(l!==void 0){t0(a,l);return}}i||=Qv.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else{let i=_a(n);i!==void 0?s.body=new ReadableStream({start(a){t0(a,i)}}):s.body=Qv.toWeb(n)}return new Yn(e,s)},vr=Symbol("getRequestCache"),Kt=Symbol("requestCache"),Qn=Symbol("incomingKey"),ds=Symbol("urlKey"),u0=Symbol("methodKey"),l0=Symbol("headersKey"),us=Symbol("abortControllerKey"),jf=Symbol("getAbortController"),Zf=Symbol("abortRequest"),_r=Symbol("bodyBuffer"),ya=Symbol("bodyReadPromise"),Xt=Symbol("bodyConsumedDirectly"),r0=Symbol("bodyLockReader"),ls=Symbol("abortReason"),va=()=>new TypeError("Body is unusable"),fs=()=>Promise.reject(va()),hO=new TextDecoder,gO=t=>{if(t[Xt])return fs();t[Xt]=!0},yO=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),_O=t=>(t[l0]||=i0(t[Qn])).get("content-type")||"",vO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xO=t=>{if(typeof t!="string"||t.length===0)return"GET";switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return t}let e=t.toUpperCase();switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e;default:return t}},bO=t=>{if(!vO.test(t))return new TypeError(`'${t}' is not a valid HTTP method.`);let e=t.toUpperCase();if(e==="CONNECT"||e==="TRACK"||e==="TRACE"&&t!=="TRACE")return new TypeError(`'${t}' HTTP method is unsupported.`)},Ff=(t,e,r)=>{if(t[Xt])return fs();let n=t.method;if(n==="GET"||n==="HEAD")return t[vr]()[e]();let o=bO(n);if(o)return Promise.reject(o);if(t[Kt]&&n!=="TRACE")return t[Kt][e]();let s=gO(t);if(s)return s;let i=wO(t);if(i){let a=Promise.resolve(r(i,t));return t[_r]=void 0,a}return $O(t).then(a=>{let c=r(a,t);return t[_r]=void 0,c})},wO=t=>{let e=t[Qn];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},n0=(t,e)=>{if(e.errored)return e.errored;let r=t[ls];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},$O=t=>{if(t[_r])return Promise.resolve(t[_r]);if(t[ya])return t[ya];let e=t[Qn];if(e.readableDidRead)return fs();let r=_a(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[_r]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,f(),h())},u=h=>{let y=e.errored??h;return!Uf(e)||y&&y.code!=="ECONNRESET"?!1:(c(()=>{let _=_a(e,i);_ instanceof Error?s(_):_===void 0?s(h??n0(t,e)):(t[_r]=_,o(_))}),!0)},l=h=>{i.push(c0(h,e.readableEncoding))},d=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[_r]=h,o(h)})},p=h=>{u(h)||c(()=>{s(h)})},m=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(n0(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",p),e.off("close",m),t[ya]=void 0};e.on("data",l),e.on("end",d),e.on("error",p),e.on("close",m),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?p(e.errored):e.destroyed&&m())})});return t[ya]=n,n},jt={get method(){return this[u0]},get url(){return this[ds]},get headers(){return this[l0]||=i0(this[Qn])},[Zf](t){this[ls]===void 0&&(this[ls]=t);let e=this[us];e&&!e.signal.aborted&&e.abort(t)},[jf](){return this[us]||=new AbortController,this[ls]!==void 0&&!this[us].signal.aborted&&this[us].abort(this[ls]),this[us]},[vr](){let t=this[jf]();if(this[Kt])return this[Kt];let e=this.method;if(this[Xt]&&!(e==="GET"||e==="HEAD")){this[_r]=void 0;let r={method:e==="TRACE"?"GET":e,headers:this.headers,signal:t.signal};e!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new Yn(this[ds],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[Kt]=n}return this[Kt]=mO(this.method,this[ds],this.headers,this[Qn],t)},get body(){if(!this[Xt])return this[vr]().body;let t=this[vr]();return!this[r0]&&t.body&&(this[r0]=t.body.getReader()),t.body},get bodyUsed(){return this[Xt]?!0:this[Kt]?this[Kt].bodyUsed:!1}};Object.defineProperty(jt,"signal",{get(){return this[jf]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(jt,t,{get(){return this[vr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(jt,t,{value:function(){if(this[Xt]){if(t==="clone")throw va();return fs()}return this[vr]()[t]()}})});Object.defineProperty(jt,"text",{value:function(){return Ff(this,"text",t=>hO.decode(t))}});Object.defineProperty(jt,"arrayBuffer",{value:function(){return Ff(this,"arrayBuffer",t=>yO(t))}});Object.defineProperty(jt,"blob",{value:function(){return Ff(this,"blob",(t,e)=>{let r=_O(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(jt,"json",{value:function(){return this[Xt]?fs():this.text().then(JSON.parse)}});Object.defineProperty(jt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Kt]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(jt,Yn.prototype);kO=(t,e)=>{let r=Object.create(jt);r[Qn]=t,r[u0]=xO(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Xn)throw new Nt("Absolute URL for :path is not allowed in HTTP/2");try{r[ds]=new URL(n).href}catch(i){throw new Nt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof Xn?t.authority:t.headers.host)||e;if(!o)throw new Nt("Missing host header");let s;if(t instanceof Xn){if(s=t.scheme,!(s==="http"||s==="https"))throw new Nt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[ds]=uO(s,o,n)}catch(i){throw i instanceof Nt?i:new Nt("Invalid URL",{cause:i})}return r},yr="text/plain; charset=UTF-8",Df=Symbol("responseCache"),Gn=Symbol("getResponseCache"),Gt=Symbol("cache"),xa=global.Response,Mt=class d0{#e;#t;[Gn](){let e=this[Gt],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Gt],this[Df]||=new xa(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof xa){let o=r[Df];if(o){this.#t=o,this[Gn]();return}this.#t=r instanceof d0?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(e==null||typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[Gt]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[Gt];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":yr}))),e[2]):this[Gn]().headers}get status(){return this[Gt]?.[0]??this[Gn]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{get(){return this[Gn]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Mt.prototype,t,{value:function(){return this[Gn]()[t]()}})});Object.defineProperty(Mt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Df]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Mt,xa);Object.setPrototypeOf(Mt.prototype,xa.prototype);SO=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,EO=t=>t instanceof URL?t.href:SO.test(t)?t:new URL(t).href,TO=new Set([301,302,303,307,308]);Object.defineProperty(Mt,"redirect",{value:function(e,r=302){if(!TO.has(r))throw new RangeError("Invalid status code");return new Mt(null,{status:r,headers:{location:EO(e)}})},writable:!0,configurable:!0});Object.defineProperty(Mt,"json",{value:function(e,r){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new Mt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});qf=(t,e)=>{let r={};if(t instanceof Headers||(t=new Headers(t??void 0)),t.has("set-cookie")){let n=[];for(let[o,s]of t)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of t)r[n]=o;return e&&(r["content-type"]??=e),r},ba=Symbol("outgoingEnded"),s0=Symbol("incomingDraining"),PO=500,RO=64*1024*1024,p0=t=>{let e=t;if(t.destroyed||e[s0])return;if(e[s0]=!0,t instanceof Xn){try{t.stream?.close?.(sO.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),t.off("data",i),t.off("end",n),t.off("error",n)},o=()=>{n();let a=t.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},s=setTimeout(o,PO);s.unref?.();let i=a=>{r+=a.length,r>RO&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},IO=(t,e,r,n)=>()=>{e.errored?(e0(e),t[Zf](e.errored.toString())):r.writableFinished||(e0(e),t[Zf]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{p0(e)})})},OO=t=>{if(!(Gt in t))return!1;let e=t[Gt][1];return e===null||typeof e=="string"||e instanceof Uint8Array},CO=()=>new Response(null,{status:400}),m0=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),wa=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},Lf=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},h0=async(t,e)=>{let[r,n,o]=t[Gt];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":yr,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":yr,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":yr}),Lf(e),await o0(n,e)?.catch(i=>wa(i,e))),e[ba]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=qf(o,n===null?void 0:yr);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=qf(i,n===null?void 0:yr)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(Lf(e),await o0(n,e)?.catch(i=>wa(i,e))),e[ba]?.()},g0=t=>typeof t.then=="function",AO=async(t,e,r={})=>{if(g0(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(m0);if(Gt in t)return h0(t,e);let n=qf(t.headers,t.body===null?void 0:yr);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let u=0;u<c;u++){a||=o.read();let l=await zO(a).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,l.value&&s.push(l.value),l.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&Lf(e),await f0(o,e,a))}else n[Kv]||(e.writeHead(t.status,n),e.end());e[ba]?.()},Hf=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Yn&&(Object.defineProperty(global,"Request",{value:Yn}),Object.defineProperty(global,"Response",{value:Mt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",IO(i,n,o,a)))};try{if(i=kO(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[a0]=!0,n instanceof Xn&&(o[ba]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!g0(s)&&OO(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||p0(n)}),h0(s,o);u()}catch(l){if(s)return wa(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:lO(l)),!s)return}else i?s=m0(l):s=CO()}try{return await AO(s,o,e)}catch(l){return wa(l,o)}}},NO=globalThis.CloseEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},MO=globalThis.ErrorEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},jO=()=>Symbol("connection"),ZO=Symbol("CONNECTION_SYMBOL_KEY"),DO=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),X2=Xv(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[DO];if(!o||!n.incoming)return new Response(null,{status:500});let s=jO();return n[ZO]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let f of m)try{e?.onMessage?.(new MessageEvent("message",{data:p?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,p)=>{l(d,p)}),i.on("close",(d,p)=>{try{e?.onClose?.(new NO("close",{code:d,reason:p.toString()}),u)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{e?.onError?.(new MO("error",{error:d}),u)}catch(p){(r?.onError??console.error)(p)}})})(),new Response})});var b0=T(Vf=>{"use strict";var _0=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,qO=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,v0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,LO=/\\([\u000b\u0020-\u00ff])/g,UO=/([\\"])/g,x0=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Vf.format=FO;Vf.parse=HO;function FO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!x0.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!v0.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+BO(e[o])}return n}function HO(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?VO(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!x0.test(n))throw new TypeError("invalid media type");var o=new JO(n.toLowerCase());if(r!==-1){var s,i,a;for(_0.lastIndex=r;i=_0.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(LO,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function VO(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function BO(t){var e=String(t);if(v0.test(e))return e;if(e.length>0&&!qO.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(UO,"\\$1")+'"'}function JO(t){this.parameters=Object.create(null),this.type=t}});function WO(t){if(t)try{return w0.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function $0(t){return t==="application/json"?!0:WO(t)==="application/json"}var w0,k0=G(()=>{w0=Sa(b0(),1)});function S0(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var E0=G(()=>{});var $a,T0=G(()=>{k0();E0();Vr();$a=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??15e3}startKeepAlive(e,r){if(this._closed)return;let n=S0(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
37
|
+
deps: ${r}}`};var DR={keyword:"dependencies",type:"object",schemaType:"object",error:Zt.error,code(t){let[e,r]=LR(t);F_(t,e),U_(t,r)}};function LR({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function F_(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,hs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,hs.checkReportMissingProp)(t,u)}):(r.if((0,mf._)`${c} && (${(0,hs.checkMissingProp)(t,a,s)})`),(0,hs.reportMissingProp)(t,s),r.else())}}Zt.validatePropertyDeps=F_;function U_(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,ZR.alwaysValidSchema)(s,e[a])||(r.if((0,hs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Zt.validateSchemaDeps=U_;Zt.default=DR});var V_=E(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var B_=J(),qR=re(),FR={message:"property name must be valid",params:({params:t})=>(0,B_._)`{propertyName: ${t.propertyName}}`},UR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:FR,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,qR.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,B_.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};hf.default=UR});var yf=E(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var oa=ft(),Tt=J(),HR=er(),sa=re(),BR={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},VR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:BR,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,sa.alwaysValidSchema)(i,r))return;let u=(0,oa.allSchemaProperties)(n.properties),d=(0,oa.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Tt._)`${s} === ${HR.default.errors}`);function l(){e.forIn("key",o,g=>{!u.length&&!d.length?f(g):e.if(p(g),()=>f(g))})}function p(g){let _;if(u.length>8){let v=(0,sa.schemaRefOrVal)(i,n.properties,"properties");_=(0,oa.isOwnProperty)(e,v,g)}else u.length?_=(0,Tt.or)(...u.map(v=>(0,Tt._)`${g} === ${v}`)):_=Tt.nil;return d.length&&(_=(0,Tt.or)(_,...d.map(v=>(0,Tt._)`${(0,oa.usePattern)(t,v)}.test(${g})`))),(0,Tt.not)(_)}function m(g){e.code((0,Tt._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,sa.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(g,_,!1),e.if((0,Tt.not)(_),()=>{t.reset(),m(g)})):(h(g,_),a||e.if((0,Tt.not)(_),()=>e.break()))}}function h(g,_,v){let y={keyword:"additionalProperties",dataProp:g,dataPropType:sa.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};gf.default=VR});var W_=E(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var JR=es(),J_=ft(),_f=re(),K_=yf(),KR={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&K_.default.code(new JR.KeywordCxt(s,K_.default,"additionalProperties"));let i=(0,J_.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=_f.mergeEvaluated.props(e,(0,_f.toHash)(i),s.props));let a=i.filter(l=>!(0,_f.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,J_.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};vf.default=KR});var Q_=E(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var G_=ft(),ia=J(),X_=re(),Y_=re(),WR={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,G_.allSchemaProperties)(r),c=a.filter(h=>(0,X_.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof ia.Name)&&(s.props=(0,Y_.evaluatedPropsToName)(e,s.props));let{props:l}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(d,!0),f(h),e.if(d))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,X_.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,g=>{e.if((0,ia._)`${(0,G_.usePattern)(t,h)}.test(${g})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Y_.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,ia._)`${l}[${g}]`,!0):!_&&!s.allErrors&&e.if((0,ia.not)(d),()=>e.break())})})}}};xf.default=WR});var e0=E(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var GR=re(),XR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,GR.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};bf.default=XR});var t0=E(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var YR=ft(),QR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:YR.validateUnion,error:{message:"must match a schema in anyOf"}};wf.default=QR});var r0=E($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var aa=J(),e1=re(),t1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,aa._)`{passingSchemas: ${t.passing}}`},r1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:t1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let p;(0,e1.alwaysValidSchema)(o,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,aa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,aa._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,aa.Name)})})}}};$f.default=r1});var n0=E(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var n1=re(),o1={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,n1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};kf.default=o1});var i0=E(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var ca=J(),s0=re(),s1={message:({params:t})=>(0,ca.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ca._)`{failingKeyword: ${t.ifClause}}`},i1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:s1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,s0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=o0(n,"then"),s=o0(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,ca.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,ca._)`${d}`):t.setParams({ifClause:d})}}}};function o0(t,e){let r=t.schema[e];return r!==void 0&&!(0,s0.alwaysValidSchema)(t,r)}Sf.default=i1});var a0=E(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var a1=re(),c1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,a1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Tf.default=c1});var c0=E(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var u1=uf(),l1=Z_(),d1=lf(),f1=L_(),p1=q_(),m1=H_(),h1=V_(),g1=yf(),y1=W_(),_1=Q_(),v1=e0(),x1=t0(),b1=r0(),w1=n0(),$1=i0(),k1=a0();function S1(t=!1){let e=[v1.default,x1.default,b1.default,w1.default,$1.default,k1.default,h1.default,g1.default,m1.default,y1.default,_1.default];return t?e.push(l1.default,f1.default):e.push(u1.default,d1.default),e.push(p1.default),e}Ef.default=S1});var u0=E(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var ke=J(),T1={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},E1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:T1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,ke._)`${f}[${i}]`),g=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,ke._)`${h}.type || "string"`).assign(_,(0,ke._)`${h}.validate`),()=>r.assign(g,(0,ke._)`"string"`).assign(_,h)),t.fail$data((0,ke.or)(v(),y()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=d.$async?(0,ke._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${g} === ${e} && !${$}`}}function m(){let f=l.formats[s];if(!f){v();return}if(f===!0)return;let[h,g,_]=y(f);h===e&&t.pass(x());function v(){if(c.strictSchema===!1){l.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function y($){let C=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:$,code:C});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${R}.validate`]:["string",$,R]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!d.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof g=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};zf.default=E1});var l0=E(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var z1=u0(),P1=[z1.default];Pf.default=P1});var d0=E(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.contentVocabulary=Wn.metadataVocabulary=void 0;Wn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var p0=E(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var R1=x_(),I1=A_(),C1=c0(),O1=l0(),f0=d0(),A1=[R1.default,I1.default,(0,C1.default)(),O1.default,f0.metadataVocabulary,f0.contentVocabulary];Rf.default=A1});var h0=E(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.DiscrError=void 0;var m0;(function(t){t.Tag="tag",t.Mapping="mapping"})(m0||(ua.DiscrError=m0={}))});var y0=E(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var Gn=J(),If=h0(),g0=Hi(),N1=ts(),M1=re(),j1={message:({params:{discrError:t,tagName:e}})=>t===If.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Gn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Z1={keyword:"discriminator",type:"object",schemaType:"object",error:j1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Gn._)`${r}${(0,Gn.getProperty)(a)}`);e.if((0,Gn._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:If.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,Gn._)`${u} === ${f}`),e.assign(c,l(m[f]));e.else(),t.error(!1,{discrError:If.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,Gn.Name),f}function p(){var m;let f={},h=_(o),g=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,M1.schemaHasRulesButRef)($,s.self.RULES)){let R=$.$ref;if($=g0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),$ instanceof g0.SchemaEnv&&($=$.schema),$===void 0)throw new N1.default(s.opts.uriResolver,s.baseId,R)}let C=(m=$?.properties)===null||m===void 0?void 0:m[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_($)),v(C,x)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,$){if(x.const)y(x.const,$);else if(x.enum)for(let C of x.enum)y(C,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};Cf.default=Z1});var _0=E((m4,D1)=>{D1.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Af=E((ye,Of)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var L1=m_(),q1=p0(),F1=y0(),v0=_0(),U1=["/properties"],la="http://json-schema.org/draft-07/schema",Xn=class extends L1.default{_addVocabularies(){super._addVocabularies(),q1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(F1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(v0,U1):v0;this.addMetaSchema(e,la,!1),this.refs["http://json-schema.org/schema"]=la}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(la)?la:void 0)}};ye.Ajv=Xn;Of.exports=ye=Xn;Of.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var H1=es();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return H1.KeywordCxt}});var Yn=J();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var B1=Fi();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return B1.default}});var V1=ts();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return V1.default}})});var E0=E(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.formatNames=Lt.fastFormats=Lt.fullFormats=void 0;function Dt(t,e){return{validate:t,compare:e}}Lt.fullFormats={date:Dt($0,Zf),time:Dt(Mf(!0),Df),"date-time":Dt(x0(!0),S0),"iso-time":Dt(Mf(),k0),"iso-date-time":Dt(x0(),T0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Y1,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:sI,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Q1,int32:{type:"number",validate:rI},int64:{type:"number",validate:nI},float:{type:"number",validate:w0},double:{type:"number",validate:w0},password:!0,binary:!0};Lt.fastFormats={...Lt.fullFormats,date:Dt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zf),time:Dt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Df),"date-time":Dt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,S0),"iso-time":Dt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,k0),"iso-date-time":Dt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,T0),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Lt.formatNames=Object.keys(Lt.fullFormats);function J1(t){return t%4===0&&(t%100!==0||t%400===0)}var K1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,W1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function $0(t){let e=K1.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&J1(r)?29:W1[n])}function Zf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Nf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Mf(t){return function(r){let n=Nf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Df(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function k0(t,e){if(!(t&&e))return;let r=Nf.exec(t),n=Nf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var jf=/t|\s/i;function x0(t){let e=Mf(t);return function(n){let o=n.split(jf);return o.length===2&&$0(o[0])&&e(o[1])}}function S0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function T0(t,e){if(!(t&&e))return;let[r,n]=t.split(jf),[o,s]=e.split(jf),i=Zf(r,o);if(i!==void 0)return i||Df(n,s)}var G1=/\/|:/,X1=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Y1(t){return G1.test(t)&&X1.test(t)}var b0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Q1(t){return b0.lastIndex=0,b0.test(t)}var eI=-(2**31),tI=2**31-1;function rI(t){return Number.isInteger(t)&&t<=tI&&t>=eI}function nI(t){return Number.isInteger(t)}function w0(){return!0}var oI=/[^\\]\\Z/;function sI(t){if(oI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var z0=E(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.formatLimitDefinition=void 0;var iI=Af(),Et=J(),kr=Et.operators,da={formatMaximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},formatMinimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},formatExclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},formatExclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},aI={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${da[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${da[t].okStr}, limit: ${e}}`};Qn.formatLimitDefinition={keyword:Object.keys(da),type:"string",schemaType:"string",$data:!0,error:aI,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new iI.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,Et._)`${p}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${m} != "object"`,(0,Et._)`${m} instanceof RegExp`,(0,Et._)`typeof ${m}.compare != "function"`,l(m)))}function d(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,Et._)`${i.code.formats}${(0,Et.getProperty)(p)}`:void 0});t.fail$data(l(f))}function l(p){return(0,Et._)`${p}.compare(${r}, ${n}) ${da[o].fail} 0`}},dependencies:["format"]};var cI=t=>(t.addKeyword(Qn.formatLimitDefinition),t);Qn.default=cI});var C0=E((gs,I0)=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var eo=E0(),uI=z0(),Lf=J(),P0=new Lf.Name("fullFormats"),lI=new Lf.Name("fastFormats"),qf=(t,e={keywords:!0})=>{if(Array.isArray(e))return R0(t,e,eo.fullFormats,P0),t;let[r,n]=e.mode==="fast"?[eo.fastFormats,lI]:[eo.fullFormats,P0],o=e.formats||eo.formatNames;return R0(t,o,r,n),e.keywords&&(0,uI.default)(t),t};qf.get=(t,e="full")=>{let n=(e==="fast"?eo.fastFormats:eo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function R0(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Lf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}I0.exports=gs=qf;Object.defineProperty(gs,"__esModule",{value:!0});gs.default=qf});var Rv={};fo(Rv,{findEmbeddingModel:()=>Pv,ollamaUrl:()=>ip,semanticRerank:()=>DC});import{createHash as zC}from"node:crypto";import{existsSync as PC,mkdirSync as RC,readFileSync as IC,writeFileSync as CC}from"node:fs";import{homedir as OC}from"node:os";import{join as sp}from"node:path";function ip(t=process.env.OLLAMA_HOST){let e=(t??"").trim(),r="http",n="11434",o=e.indexOf("://");o>=0&&(r=e.slice(0,o),e=e.slice(o+3),r==="http"?n="80":r==="https"&&(n="443"));let s=e.indexOf("/"),i=s>=0?e.slice(s).replace(/\/+$/,""):"",a=s>=0?e.slice(0,s):e,c=/^(\[[^\]]*\]|[^:]*):([^:]*)$/.exec(a);return c?(a=c[1],/^\d+$/.test(c[2])&&Number(c[2])<=65535&&(n=c[2])):a.includes(":")&&!a.startsWith("[")&&(a=`[${a}]`),!a||a==="0.0.0.0"?a="127.0.0.1":a==="[::]"&&(a="[::1]"),`${r}://${a}:${n}${i}`}async function zv(t,e,r=6e4){let n=await fetch(ip()+t,{method:e?"POST":"GET",headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0,signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()}async function Pv(t){let r=((await zv("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>AC.test(n))}function Ia(){return sp(process.env.XDG_CACHE_HOME??sp(OC(),".cache"),"context-doctor","embeddings.json")}function NC(){try{return PC(Ia())?JSON.parse(IC(Ia(),"utf8")):{}}catch{return{}}}function MC(t){try{let e=Object.keys(t);if(e.length>Ev)for(let r of e.slice(0,e.length-Ev))delete t[r];RC(sp(Ia(),".."),{recursive:!0}),CC(Ia(),JSON.stringify(t))}catch{}}async function jC(t,e){let r=[];for(let n=0;n<e.length;n+=Tv){let o=await zv("/api/embed",{model:t,input:e.slice(n,n+Tv),truncate:!0});r.push(...o.embeddings)}return r}function ZC(t,e){let r=0,n=0,o=0;for(let s=0;s<t.length;s++)r+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return n&&o?r/Math.sqrt(n*o):0}async function DC(t,e,r={}){let n;try{n=await Pv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${ip()} (keyword ranking only)`}}if(!n)return{used:!1,note:"semantic ranking off: Ollama has no embedding model; run `ollama pull nomic-embed-text` (keyword ranking only)"};let o=NC(),s=f=>zC("sha1").update(n+"\0"+f).digest("hex"),i=t.map(f=>(f.heading?f.heading+`
|
|
38
|
+
`:"")+f.text),a=[...new Set(i.filter(f=>!o[s(f)]))],c,u;try{let f=await jC(n,[e,...a]);u=f[0],a.forEach((h,g)=>o[s(h)]=f[g+1]),c=i.map(h=>o[s(h)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&MC(o);let d=60,l=new Map([...t].filter(f=>f.score>0).sort((f,h)=>h.score-f.score).map((f,h)=>[f,h])),p=t.map((f,h)=>({c:f,s:ZC(u,c[h])})).sort((f,h)=>h.s-f.s),m=new Map(p.map((f,h)=>[f.c,h]));for(let f of t){let h=l.get(f);f.score=(h===void 0?0:1/(d+h))+1/(d+m.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var AC,Tv,Ev,Iv=X(()=>{"use strict";AC=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Tv=64,Ev=5e4});var cx,ux=X(()=>{cx="x-hono-already-sent"});var lx,dx=X(()=>{lx=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{Http2ServerRequest as co,constants as oA}from"node:http2";import{Readable as fx}from"node:stream";async function EA(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Sx(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(u){o(u)}}}function yx(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Sx(t.getReader(),e)}var Ft,sA,iA,aA,cA,uA,lA,uo,vx,xx,dA,fA,_p,vp,bx,Sp,px,Ua,mx,pA,Pr,nr,lo,ks,wx,$x,ws,xp,bp,zr,Fa,sr,hx,$s,Ha,Ss,mA,hA,gA,yA,_A,vA,xA,Tp,bA,gx,wA,Ht,$A,Er,wp,ao,or,Ba,Ut,kA,SA,TA,$p,Va,_x,zA,PA,Tx,RA,IA,CA,Ex,Ja,kp,zx,Px,OA,Ep,AA,NA,MA,jA,ZA,hq,Rx=X(()=>{ux();dx();Ft=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},sA=/^\/[!#$&-;=?-\[\]_a-z~]*$/,iA=/\/\.\.?(?:[/?#]|$)/,aA=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,cA=(t,e,r)=>{let n=`${t}://${e}${r}`;if(aA.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ft("Invalid URL");return!sA.test(r)||iA.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Ft("Invalid host header");return o.href}},uA=t=>t instanceof Ft?t:new Ft(t.message,{cause:t}),lA=global.Request,uo=class extends lA{constructor(t,e){if(typeof t=="object"&&Pr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[sr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Pr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},vx=t=>{let e=[],r=t.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&e.push([s,r[n+1]])}return new Headers(e)},xx=Symbol("wrapBodyStream"),dA=new Set(["latin1","binary","hex","base64","base64url"]),fA=t=>t===null||dA.has(t),_p=Symbol("bodyBufferedBeforeDisconnect"),vp=Symbol("bodyBufferedLengthBeforeDisconnect"),bx=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Sp=t=>!(t instanceof co)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&fA(t.readableEncoding),px=t=>{if(t.readableDidRead||!Sp(t))return;let e=t;e[vp]??=t.readableLength},Ua=(t,e)=>{if(t.readableDidRead&&!e||!Sp(t))return;let r=t;if(r[_p]!==void 0)return r[_p];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[vp]!==void 0&&t.readableLength!==r[vp])n=Ha();else{let s=e??[],i=t.read();i!==null&&s.push(bx(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=Ha())}}return r[_p]=n,n},mx=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},pA=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new uo(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[xx]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let d=Ua(n);if(d!==void 0){mx(a,d);return}}i||=fx.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else{let i=Ua(n);i!==void 0?s.body=new ReadableStream({start(a){mx(a,i)}}):s.body=fx.toWeb(n)}return new uo(e,s)},Pr=Symbol("getRequestCache"),nr=Symbol("requestCache"),lo=Symbol("incomingKey"),ks=Symbol("urlKey"),wx=Symbol("methodKey"),$x=Symbol("headersKey"),ws=Symbol("abortControllerKey"),xp=Symbol("getAbortController"),bp=Symbol("abortRequest"),zr=Symbol("bodyBuffer"),Fa=Symbol("bodyReadPromise"),sr=Symbol("bodyConsumedDirectly"),hx=Symbol("bodyLockReader"),$s=Symbol("abortReason"),Ha=()=>new TypeError("Body is unusable"),Ss=()=>Promise.reject(Ha()),mA=new TextDecoder,hA=t=>{if(t[sr])return Ss();t[sr]=!0},gA=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),yA=t=>(t[$x]||=vx(t[lo])).get("content-type")||"",_A=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,vA=t=>{if(typeof t!="string"||t.length===0)return"GET";switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return t}let e=t.toUpperCase();switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e;default:return t}},xA=t=>{if(!_A.test(t))return new TypeError(`'${t}' is not a valid HTTP method.`);let e=t.toUpperCase();if(e==="CONNECT"||e==="TRACK"||e==="TRACE"&&t!=="TRACE")return new TypeError(`'${t}' HTTP method is unsupported.`)},Tp=(t,e,r)=>{if(t[sr])return Ss();let n=t.method;if(n==="GET"||n==="HEAD")return t[Pr]()[e]();let o=xA(n);if(o)return Promise.reject(o);if(t[nr]&&n!=="TRACE")return t[nr][e]();let s=hA(t);if(s)return s;let i=bA(t);if(i){let a=Promise.resolve(r(i,t));return t[zr]=void 0,a}return wA(t).then(a=>{let c=r(a,t);return t[zr]=void 0,c})},bA=t=>{let e=t[lo];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},gx=(t,e)=>{if(e.errored)return e.errored;let r=t[$s];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},wA=t=>{if(t[zr])return Promise.resolve(t[zr]);if(t[Fa])return t[Fa];let e=t[lo];if(e.readableDidRead)return Ss();let r=Ua(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[zr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=h=>{a||(a=!0,f(),h())},u=h=>{let g=e.errored??h;return!Sp(e)||g&&g.code!=="ECONNRESET"?!1:(c(()=>{let _=Ua(e,i);_ instanceof Error?s(_):_===void 0?s(h??gx(t,e)):(t[zr]=_,o(_))}),!0)},d=h=>{i.push(bx(h,e.readableEncoding))},l=()=>{c(()=>{let h=i.length===1?i[0]:Buffer.concat(i);t[zr]=h,o(h)})},p=h=>{u(h)||c(()=>{s(h)})},m=()=>{if(e.readableEnded){l();return}u()||c(()=>{s(gx(t,e))})},f=()=>{e.off("data",d),e.off("end",l),e.off("error",p),e.off("close",m),t[Fa]=void 0};e.on("data",d),e.on("end",l),e.on("error",p),e.on("close",m),queueMicrotask(()=>{a||(e.readableEnded?l():e.errored?p(e.errored):e.destroyed&&m())})});return t[Fa]=n,n},Ht={get method(){return this[wx]},get url(){return this[ks]},get headers(){return this[$x]||=vx(this[lo])},[bp](t){this[$s]===void 0&&(this[$s]=t);let e=this[ws];e&&!e.signal.aborted&&e.abort(t)},[xp](){return this[ws]||=new AbortController,this[$s]!==void 0&&!this[ws].signal.aborted&&this[ws].abort(this[$s]),this[ws]},[Pr](){let t=this[xp]();if(this[nr])return this[nr];let e=this.method;if(this[sr]&&!(e==="GET"||e==="HEAD")){this[zr]=void 0;let r={method:e==="TRACE"?"GET":e,headers:this.headers,signal:t.signal};e!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new uo(this[ks],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[nr]=n}return this[nr]=pA(this.method,this[ks],this.headers,this[lo],t)},get body(){if(!this[sr])return this[Pr]().body;let t=this[Pr]();return!this[hx]&&t.body&&(this[hx]=t.body.getReader()),t.body},get bodyUsed(){return this[sr]?!0:this[nr]?this[nr].bodyUsed:!1}};Object.defineProperty(Ht,"signal",{get(){return this[xp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Ht,t,{get(){return this[Pr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Ht,t,{value:function(){if(this[sr]){if(t==="clone")throw Ha();return Ss()}return this[Pr]()[t]()}})});Object.defineProperty(Ht,"text",{value:function(){return Tp(this,"text",t=>mA.decode(t))}});Object.defineProperty(Ht,"arrayBuffer",{value:function(){return Tp(this,"arrayBuffer",t=>gA(t))}});Object.defineProperty(Ht,"blob",{value:function(){return Tp(this,"blob",(t,e)=>{let r=yA(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Ht,"json",{value:function(){return this[sr]?Ss():this.text().then(JSON.parse)}});Object.defineProperty(Ht,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[nr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ht,uo.prototype);$A=(t,e)=>{let r=Object.create(Ht);r[lo]=t,r[wx]=vA(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof co)throw new Ft("Absolute URL for :path is not allowed in HTTP/2");try{r[ks]=new URL(n).href}catch(i){throw new Ft("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof co?t.authority:t.headers.host)||e;if(!o)throw new Ft("Missing host header");let s;if(t instanceof co){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ft("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[ks]=cA(s,o,n)}catch(i){throw i instanceof Ft?i:new Ft("Invalid URL",{cause:i})}return r},Er="text/plain; charset=UTF-8",wp=Symbol("responseCache"),ao=Symbol("getResponseCache"),or=Symbol("cache"),Ba=global.Response,Ut=class kx{#e;#t;[ao](){let e=this[or],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[or],this[wp]||=new Ba(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof Ba){let o=r[wp];if(o){this.#t=o,this[ao]();return}this.#t=r instanceof kx?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(e==null||typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[or]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[or];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Er}))),e[2]):this[ao]().headers}get status(){return this[or]?.[0]??this[ao]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Ut.prototype,t,{get(){return this[ao]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Ut.prototype,t,{value:function(){return this[ao]()[t]()}})});Object.defineProperty(Ut.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[wp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ut,Ba);Object.setPrototypeOf(Ut.prototype,Ba.prototype);kA=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,SA=t=>t instanceof URL?t.href:kA.test(t)?t:new URL(t).href,TA=new Set([301,302,303,307,308]);Object.defineProperty(Ut,"redirect",{value:function(e,r=302){if(!TA.has(r))throw new RangeError("Invalid status code");return new Ut(null,{status:r,headers:{location:SA(e)}})},writable:!0,configurable:!0});Object.defineProperty(Ut,"json",{value:function(e,r){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new Ut(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});$p=(t,e)=>{let r={};if(t instanceof Headers||(t=new Headers(t??void 0)),t.has("set-cookie")){let n=[];for(let[o,s]of t)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of t)r[n]=o;return e&&(r["content-type"]??=e),r},Va=Symbol("outgoingEnded"),_x=Symbol("incomingDraining"),zA=500,PA=64*1024*1024,Tx=t=>{let e=t;if(t.destroyed||e[_x])return;if(e[_x]=!0,t instanceof co){try{t.stream?.close?.(oA.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),t.off("data",i),t.off("end",n),t.off("error",n)},o=()=>{n();let a=t.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},s=setTimeout(o,zA);s.unref?.();let i=a=>{r+=a.length,r>PA&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},RA=(t,e,r,n)=>()=>{e.errored?(px(e),t[bp](e.errored.toString())):r.writableFinished||(px(e),t[bp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{Tx(e)})})},IA=t=>{if(!(or in t))return!1;let e=t[or][1];return e===null||typeof e=="string"||e instanceof Uint8Array},CA=()=>new Response(null,{status:400}),Ex=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Ja=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},kp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},zx=async(t,e)=>{let[r,n,o]=t[or];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":Er,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":Er,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":Er,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Er}),kp(e),await yx(n,e)?.catch(i=>Ja(i,e))),e[Va]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=$p(o,n===null?void 0:Er);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=$p(i,n===null?void 0:Er)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(kp(e),await yx(n,e)?.catch(i=>Ja(i,e))),e[Va]?.()},Px=t=>typeof t.then=="function",OA=async(t,e,r={})=>{if(Px(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(Ex);if(or in t)return zx(t,e);let n=$p(t.headers,t.body===null?void 0:Er);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let u=0;u<c;u++){a||=o.read();let d=await EA(a).catch(l=>{console.error(l),i=!0});if(!d){if(u===1){await new Promise(l=>setTimeout(l)),c=3;continue}break}if(a=void 0,d.value&&s.push(d.value),d.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((u,d)=>u+d.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&kp(e),await Sx(o,e,a))}else n[cx]||(e.writeHead(t.status,n),e.end());e[Va]?.()},Ep=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==uo&&(Object.defineProperty(global,"Request",{value:uo}),Object.defineProperty(global,"Response",{value:Ut})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",RA(i,n,o,a)))};try{if(i=$A(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[xx]=!0,n instanceof co&&(o[Va]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!Px(s)&&IA(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||Tx(n)}),zx(s,o);u()}catch(d){if(s)return Ja(d,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?d:uA(d)),!s)return}else i?s=Ex(d):s=CA()}try{return await OA(s,o,e)}catch(d){return Ja(d,o)}}},AA=globalThis.CloseEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},NA=globalThis.ErrorEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},MA=()=>Symbol("connection"),jA=Symbol("CONNECTION_SYMBOL_KEY"),ZA=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),hq=lx(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[ZA];if(!o||!n.incoming)return new Response(null,{status:500});let s=MA();return n[jA]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(l,p)=>{a.push([l,p])};i.on("message",c);let u={binaryType:"arraybuffer",close(l,p){i.close(l,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(l,p){i.send(l,{compress:p?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(l){(r?.onError??console.error)(l)}let d=(l,p)=>{let m=Array.isArray(l)?l:[l];for(let f of m)try{e?.onMessage?.(new MessageEvent("message",{data:p?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let l of a)d(...l);i.on("message",(l,p)=>{d(l,p)}),i.on("close",(l,p)=>{try{e?.onClose?.(new AA("close",{code:l,reason:p.toString()}),u)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",l=>{try{e?.onError?.(new NA("error",{error:l}),u)}catch(p){(r?.onError??console.error)(p)}})})(),new Response})});var Ax=E(zp=>{"use strict";var Ix=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,DA=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Cx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,LA=/\\([\u000b\u0020-\u00ff])/g,qA=/([\\"])/g,Ox=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;zp.format=FA;zp.parse=UA;function FA(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Ox.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!Cx.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+BA(e[o])}return n}function UA(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?HA(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!Ox.test(n))throw new TypeError("invalid media type");var o=new VA(n.toLowerCase());if(r!==-1){var s,i,a;for(Ix.lastIndex=r;i=Ix.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(LA,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function HA(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function BA(t){var e=String(t);if(Cx.test(e))return e;if(e.length>0&&!DA.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(qA,"\\$1")+'"'}function VA(t){this.parameters=Object.create(null),this.type=t}});function JA(t){if(t)try{return Nx.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Mx(t){return t==="application/json"?!0:JA(t)==="application/json"}var Nx,jx=X(()=>{Nx=Xa(Ax(),1)});function Zx(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Dx=X(()=>{});var Ka,Lx=X(()=>{jx();Dx();hr();Ka=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??15e3}startKeepAlive(e,r){if(this._closed)return;let n=Zx(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
|
|
39
39
|
|
|
40
40
|
`))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
|
|
41
41
|
data:
|
|
@@ -44,56 +44,72 @@ data:
|
|
|
44
44
|
retry: ${this._retryInterval}
|
|
45
45
|
data:
|
|
46
46
|
|
|
47
|
-
`),e.enqueue(r.encode(i)),this._resumableStreams.add(n)}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(e);if(n)return n;let o=this.validateProtocolVersion(e);if(o)return o;if(this._eventStore){let
|
|
47
|
+
`),e.enqueue(r.encode(i)),this._resumableStreams.add(n)}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(e);if(n)return n;let o=this.validateProtocolVersion(e);if(o)return o;if(this._eventStore){let d=e.headers.get("last-event-id");if(d)return this.replayEvents(d)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let s=new TextEncoder,i,a,c=new ReadableStream({start:d=>{i=d},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),u={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};return this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:s,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,s),new Response(c,{headers:u})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(new Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r;if(this._eventStore.getStreamIdForEventId){if(r=await this._eventStore.getStreamIdForEventId(e),!r)return this.onerror?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(r)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(n["mcp-session-id"]=this.sessionId);let o=new TextEncoder,s,i,a,c=!1,u=new ReadableStream({start:l=>{s=l},cancel:()=>{c=!0,i!==void 0&&clearInterval(i),a!==void 0&&this._streamMapping.get(a)?.controller===s&&this._streamMapping.delete(a)}}),d=new Set;if(a=await this._eventStore.replayEventsAfter(e,{send:async(l,p)=>{if(this.writeSSEEvent(s,o,p,l))d.add(l);else{this.onerror?.(new Error("Failed replay events"));try{s.close()}catch{}}}}),this._closed||c){try{s.close()}catch{}return this.createJsonErrorResponse(404,-32001,"Session not found")}return this._streamMapping.get(a)?.cleanup(),this._streamMapping.set(a,{controller:s,encoder:o,replayedEventIds:d,cleanup:()=>{i!==void 0&&clearInterval(i),this._streamMapping.delete(a);try{s.close()}catch{}}}),this._resumableStreams.add(a),i=this.startKeepAlive(s,o),new Response(u,{headers:n})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(e,r,n,o){try{let s=`event: message
|
|
48
48
|
`;return o&&(s+=`id: ${o}
|
|
49
49
|
`),s+=`data: ${JSON.stringify(n)}
|
|
50
50
|
|
|
51
|
-
`,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!$0(o))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>xo.parse(v)):a=[xo.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=a.some(Xu);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let g=this.validateProtocolVersion(e);if(g)return g}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Ft)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(v=>Xu(v)),p=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??rh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let g of a)Ft(g)&&this._requestToStreamMapping.set(g.id,l);for(let g of a)this.onmessage?.(g,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,f,h,y=new ReadableStream({start:v=>{f=v},cancel:()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(l)?.controller===f&&this._streamMapping.delete(l)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)Ft(v)&&(this._streamMapping.set(l,{controller:f,encoder:m,cleanup:()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,m,l,p);for(let v of a){let g,x;Ft(v)&&this._eventStore&&p>="2025-11-25"&&(g=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:g,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let g of a)Ft(g)&&this._requestToStreamMapping.delete(g.id);throw v}return this._streamMapping.get(l)?.controller===f&&(h=this.startKeepAlive(f,m)),new Response(y,{status:200,headers:_})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!kn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${kn.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((Ht(e)||Sn(e))&&(n=e.id),n===void 0){if(Ht(e)||Sn(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i))&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e),s=this._streamMapping.get(o)),s?.controller&&s?.encoder&&(i===void 0||!s.replayedEventIds?.has(i))&&this.writeSSEEvent(s.controller,s.encoder,e,i)&&i!==void 0&&this._resumableStreams.add(o)}if(Ht(e)||Sn(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s){if(this._closed){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(o)){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o);return}for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);throw new Error(`No connection established for request ID: ${String(n)}`)}if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(l=>this._requestResponseMap.get(l));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o)}}}}});var z0={};eo(z0,{StreamableHTTPServerTransport:()=>Bf});var Bf,P0=G(()=>{y0();T0();Bf=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new $a(e),this._requestListener=Hf(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Hf(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var te={};eo(te,{BRAND:()=>lx,DIRTY:()=>wr,EMPTY_PATH:()=>U0,INVALID:()=>M,NEVER:()=>Jx,OK:()=>Ne,ParseStatus:()=>Pe,Schema:()=>V,ZodAny:()=>er,ZodArray:()=>Lt,ZodBigInt:()=>kr,ZodBoolean:()=>Sr,ZodBranded:()=>ro,ZodCatch:()=>Mr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>gs,ZodEffects:()=>st,ZodEnum:()=>Cr,ZodError:()=>Ve,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>_s,ZodIntersection:()=>Rr,ZodIssueCode:()=>k,ZodLazy:()=>Ir,ZodLiteral:()=>Or,ZodMap:()=>mn,ZodNaN:()=>gn,ZodNativeEnum:()=>Ar,ZodNever:()=>mt,ZodNull:()=>zr,ZodNullable:()=>Et,ZodNumber:()=>$r,ZodObject:()=>Je,ZodOptional:()=>Be,ZodParsedType:()=>z,ZodPipeline:()=>no,ZodPromise:()=>tr,ZodReadonly:()=>jr,ZodRecord:()=>ys,ZodSchema:()=>V,ZodSet:()=>hn,ZodString:()=>Qt,ZodSymbol:()=>fn,ZodTransformer:()=>st,ZodTuple:()=>St,ZodType:()=>V,ZodUndefined:()=>Tr,ZodUnion:()=>Pr,ZodUnknown:()=>qt,ZodVoid:()=>pn,addIssueToContext:()=>E,any:()=>vx,array:()=>$x,bigint:()=>mx,boolean:()=>sp,coerce:()=>Bx,custom:()=>rp,date:()=>hx,datetimeRegex:()=>ep,defaultErrorMap:()=>Zt,discriminatedUnion:()=>Ex,effect:()=>Zx,enum:()=>Nx,function:()=>Ox,getErrorMap:()=>un,getParsedType:()=>kt,instanceof:()=>fx,intersection:()=>Tx,isAborted:()=>ms,isAsync:()=>ln,isDirty:()=>hs,isValid:()=>Yt,late:()=>dx,lazy:()=>Cx,literal:()=>Ax,makeIssue:()=>to,map:()=>Rx,nan:()=>px,nativeEnum:()=>Mx,never:()=>bx,null:()=>_x,nullable:()=>qx,number:()=>op,object:()=>Pa,objectUtil:()=>Ea,oboolean:()=>Vx,onumber:()=>Hx,optional:()=>Dx,ostring:()=>Fx,pipeline:()=>Ux,preprocess:()=>Lx,promise:()=>jx,quotelessJson:()=>D0,record:()=>Px,set:()=>Ix,setErrorMap:()=>L0,strictObject:()=>kx,string:()=>np,symbol:()=>gx,transformer:()=>Zx,tuple:()=>zx,undefined:()=>yx,union:()=>Sx,unknown:()=>xx,util:()=>K,void:()=>wx});var K;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var Ea;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ea||(Ea={}));var z=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var k=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),D0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ve=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ve.create=t=>new Ve(t);var q0=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},Zt=q0;var Kf=Zt;function L0(t){Kf=t}function un(){return Kf}var to=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},U0=[];function E(t,e){let r=un(),n=to({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Zt?void 0:Zt].filter(o=>!!o)});t.common.issues.push(n)}var Pe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return M;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return M;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),wr=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ms=t=>t.status==="aborted",hs=t=>t.status==="dirty",Yt=t=>t.status==="valid",ln=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var ot=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Gf=(t,e)=>{if(Yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ve(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return kt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:kt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ln(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Gf(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Yt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ln(o)?o:Promise.resolve(o));return Gf(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new st({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Be.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lt.create(this)}promise(){return tr.create(this,this._def)}or(e){return Pr.create([this,e],this._def)}and(e){return Rr.create(this,e,this._def)}transform(e){return new st({...U(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new ro({typeName:S.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mr({...U(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return no.create(this,e)}readonly(){return jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},F0=/^c[^\s-]{8,}$/i,H0=/^[0-9a-z]+$/,V0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,B0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,J0=/^[a-z0-9_-]{21}$/i,W0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,K0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,X0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ta,Y0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Q0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,tx=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rx=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nx=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ox=new RegExp(`^${Yf}$`);function Qf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function sx(t){return new RegExp(`^${Qf(t)}$`)}function ep(t){let e=`${Yf}T${Qf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ix(t,e){return!!((e==="v4"||!e)&&Y0.test(t)||(e==="v6"||!e)&&ex.test(t))}function ax(t,e){if(!W0.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function cx(t,e){return!!((e==="v4"||!e)&&Q0.test(t)||(e==="v6"||!e)&&tx.test(t))}var Qt=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.string,received:s.parsedType}),M}let n=new Pe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")G0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Ta||(Ta=new RegExp(X0,"u")),Ta.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")B0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")J0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")F0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")H0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")V0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ep(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?ox.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?sx(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?K0.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ix(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ax(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?cx(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?rx.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?nx.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...I.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...I.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...I.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...I.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...I.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...I.errToObj(r)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Qt.create=t=>new Qt({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...U(t)});function ux(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var $r=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.number,received:s.parsedType}),M}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ux(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};$r.create=t=>new $r({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...U(t)});var kr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new Pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.bigint,received:r.parsedType}),M}gte(e,r){return this.setLimit("min",e,!0,I.toString(r))}gt(e,r){return this.setLimit("min",e,!1,I.toString(r))}lte(e,r){return this.setLimit("max",e,!0,I.toString(r))}lt(e,r){return this.setLimit("max",e,!1,I.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};kr.create=t=>new kr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Sr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.boolean,received:n.parsedType}),M}return Ne(e.data)}};Sr.create=t=>new Sr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:z.date,received:s.parsedType}),M}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),M}let n=new Pe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...U(t)});var fn=class extends V{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.symbol,received:n.parsedType}),M}return Ne(e.data)}};fn.create=t=>new fn({typeName:S.ZodSymbol,...U(t)});var Tr=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.undefined,received:n.parsedType}),M}return Ne(e.data)}};Tr.create=t=>new Tr({typeName:S.ZodUndefined,...U(t)});var zr=class extends V{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.null,received:n.parsedType}),M}return Ne(e.data)}};zr.create=t=>new zr({typeName:S.ZodNull,...U(t)});var er=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};er.create=t=>new er({typeName:S.ZodAny,...U(t)});var qt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};qt.create=t=>new qt({typeName:S.ZodUnknown,...U(t)});var mt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:z.never,received:r.parsedType}),M}};mt.create=t=>new mt({typeName:S.ZodNever,...U(t)});var pn=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.void,received:n.parsedType}),M}return Ne(e.data)}};pn.create=t=>new pn({typeName:S.ZodVoid,...U(t)});var Lt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return E(r,{code:k.invalid_type,expected:z.array,received:r.parsedType}),M;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ot(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ot(r,i,r.path,a)));return Pe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:I.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:I.toString(r)}})}nonempty(e){return this.min(1,e)}};Lt.create=(t,e)=>new Lt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...U(e)});function dn(t){if(t instanceof Je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Be.create(dn(n))}return new Je({...t._def,shape:()=>e})}else return t instanceof Lt?new Lt({...t._def,type:dn(t.element)}):t instanceof Be?Be.create(dn(t.unwrap())):t instanceof Et?Et.create(dn(t.unwrap())):t instanceof St?St.create(t.items.map(e=>dn(e))):t}var Je=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:z.object,received:u.parsedType}),M}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ot(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ot(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return dn(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Be;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return tp(K.objectKeys(this.shape))}};Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:S.ZodObject,...U(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:S.ZodObject,...U(e)});var Pr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ve(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),M}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ve(c));return E(r,{code:k.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pr.create=(t,e)=>new Pr({options:t,typeName:S.ZodUnion,...U(e)});var Dt=t=>t instanceof Ir?Dt(t.schema):t instanceof st?Dt(t.innerType()):t instanceof Or?[t.value]:t instanceof Cr?t.options:t instanceof Ar?K.objectValues(t.enum):t instanceof Nr?Dt(t._def.innerType):t instanceof Tr?[void 0]:t instanceof zr?[null]:t instanceof Be?[void 0,...Dt(t.unwrap())]:t instanceof Et?[null,...Dt(t.unwrap())]:t instanceof ro||t instanceof jr?Dt(t.unwrap()):t instanceof Mr?Dt(t._def.innerType):[],gs=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return E(r,{code:k.invalid_type,expected:z.object,received:r.parsedType}),M;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Dt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function za(t,e){let r=kt(t),n=kt(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=K.objectKeys(e),s=K.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=za(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=za(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ms(s)||ms(i))return M;let a=za(s.value,i.value);return a.valid?((hs(s)||hs(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Rr.create=(t,e,r)=>new Rr({left:t,right:e,typeName:S.ZodIntersection,...U(r)});var St=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return E(n,{code:k.invalid_type,expected:z.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ot(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Pe.mergeArray(r,i)):Pe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};St.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:t,typeName:S.ZodTuple,rest:null,...U(e)})};var ys=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return E(n,{code:k.invalid_type,expected:z.object,received:n.parsedType}),M;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ot(n,a,n.path,a)),value:i._parse(new ot(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pe.mergeObjectAsync(r,o):Pe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...U(n)}):new t({keyType:Qt.create(),valueType:e,typeName:S.ZodRecord,...U(r)})}},mn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return E(n,{code:k.invalid_type,expected:z.map,received:n.parsedType}),M;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ot(n,a,n.path,[u,"key"])),value:s._parse(new ot(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return M;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};mn.create=(t,e,r)=>new mn({valueType:e,keyType:t,typeName:S.ZodMap,...U(r)});var hn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return E(n,{code:k.invalid_type,expected:z.set,received:n.parsedType}),M;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return M;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new ot(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:I.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:I.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};hn.create=(t,e)=>new hn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...U(e)});var _s=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return E(r,{code:k.invalid_type,expected:z.function,received:r.parsedType}),M;function n(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return to({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,un(),Zt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tr){let a=this;return Ne(async function(...c){let u=new Ve([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ve([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ve([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:St.create(e).rest(qt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||St.create([]).rest(qt.create()),returns:r||qt.create(),typeName:S.ZodFunction,...U(n)})}},Ir=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ir.create=(t,e)=>new Ir({getter:t,typeName:S.ZodLazy,...U(e)});var Or=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Or.create=(t,e)=>new Or({value:t,typeName:S.ZodLiteral,...U(e)});function tp(t,e){return new Cr({values:t,typeName:S.ZodEnum,...U(e)})}var Cr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:K.joinValues(n),received:r.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),M}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Cr.create=tp;var Ar=class extends V{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=K.objectValues(r);return E(n,{expected:K.joinValues(o),received:n.parsedType,code:k.invalid_type}),M}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=K.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),M}return Ne(e.data)}get enum(){return this._def.values}};Ar.create=(t,e)=>new Ar({values:t,typeName:S.ZodNativeEnum,...U(e)});var tr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:z.promise,received:r.parsedType}),M;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tr.create=(t,e)=>new tr({type:t,typeName:S.ZodPromise,...U(e)});var st=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?wr(c.value):r.value==="dirty"?wr(c.value):c});{if(r.value==="aborted")return M;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?wr(a.value):r.value==="dirty"?wr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yt(i))return M;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Yt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):M);K.assertNever(o)}};st.create=(t,e,r)=>new st({schema:t,typeName:S.ZodEffects,effect:e,...U(r)});st.createWithPreprocess=(t,e,r)=>new st({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...U(r)});var Be=class extends V{_parse(e){return this._getType(e)===z.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:S.ZodOptional,...U(e)});var Et=class extends V{_parse(e){return this._getType(e)===z.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:S.ZodNullable,...U(e)});var Nr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var Mr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ln(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ve(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ve(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var gn=class extends V{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:z.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};gn.create=t=>new gn({typeName:S.ZodNaN,...U(t)});var lx=Symbol("zod_brand"),ro=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},no=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(r.dirty(),wr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?M:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},jr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Yt(o)&&(o.value=Object.freeze(o.value)),o);return ln(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:S.ZodReadonly,...U(e)});function Xf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function rp(t,e={},r){return t?er.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Xf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Xf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):er.create()}var dx={object:Je.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var fx=(t,e={message:`Input not instance of ${t.name}`})=>rp(r=>r instanceof t,e),np=Qt.create,op=$r.create,px=gn.create,mx=kr.create,sp=Sr.create,hx=Er.create,gx=fn.create,yx=Tr.create,_x=zr.create,vx=er.create,xx=qt.create,bx=mt.create,wx=pn.create,$x=Lt.create,Pa=Je.create,kx=Je.strictCreate,Sx=Pr.create,Ex=gs.create,Tx=Rr.create,zx=St.create,Px=ys.create,Rx=mn.create,Ix=hn.create,Ox=_s.create,Cx=Ir.create,Ax=Or.create,Nx=Cr.create,Mx=Ar.create,jx=tr.create,Zx=st.create,Dx=Be.create,qx=Et.create,Lx=st.createWithPreprocess,Ux=no.create,Fx=()=>np().optional(),Hx=()=>op().optional(),Vx=()=>sp().optional(),Bx={string:(t=>Qt.create({...t,coerce:!0})),number:(t=>$r.create({...t,coerce:!0})),boolean:(t=>Sr.create({...t,coerce:!0})),bigint:(t=>kr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var Jx=M;qe();qe();qe();qe();var rw=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ce.init(t,e),t.def=e,t.parse=(r,n)=>Ha(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>qr(t,r,n),t.parseAsync=async(r,n)=>Ba(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Lr(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var nw=w("ZodMiniObject",(t,e)=>{Rs.init(t,e),rw.init(t,e),X.defineLazy(t,"shape",()=>e.shape)});function Ou(t,e){let r={type:"object",get shape(){return X.assignProp(this,"shape",{...t}),this.shape},...X.normalizeParams(e)};return new nw(r)}qe();Os();function Pt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return Ou({});let r=e.every(Pt),n=e.every(o=>!Pt(o));if(r)return Ou(t);if(n)return Pa(t);throw new Error("Mixed Zod versions detected in object shape.")}function or(t,e){return Pt(t)?qr(t,e):t.safeParse(e)}async function qs(t,e){return Pt(t)?await Lr(t,e):await t.safeParseAsync(e)}function sr(t){if(!t)return;let e;if(Pt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function bn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Hr(t)}}if(Pt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function sw(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ls(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${sw(e.path)}`:e.message).join(`
|
|
52
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Tm(t){return t.description}function zm(t){if(Pt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function wn(t){if(Pt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}Vr();function ar(t){return t==="completed"||t==="failed"||t==="cancelled"}var vh=Symbol("Let zodToJsonSchema decide on which parser to use");var _h={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},xh=t=>typeof t=="string"?{..._h,name:t}:{..._h,...t};var bh=t=>{let e=xh(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function cl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Q(t,e,r,n,o){t[e]=r,cl(t,e,n,o)}var fi=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?fi(e,t.currentPath):e.join("/")}}function wh(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Q(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Q(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Q(r,"minItems",t.exactLength.value,t.exactLength.message,e),Q(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function $h(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function kh(){return{type:"boolean"}}function pi(t,e){return Z(t.type._def,e)}var Sh=(t,e)=>Z(t.innerType._def,e);function ul(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ul(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ik(t,e)}}var Ik=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Q(r,"minimum",n.value,n.message,e);break;case"max":Q(r,"maximum",n.value,n.message,e);break}return r};function Eh(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function Th(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):we(e)}function zh(t){return{type:"string",enum:Array.from(t.values)}}var Ok=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ph(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Ok(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Rh(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ll,gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ll===void 0&&(ll=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ll),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function mi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yt(r,"email",n.message,e);break;case"format:idn-email":yt(r,"idn-email",n.message,e);break;case"pattern:zod":Ue(r,gt.email,n.message,e);break}break;case"url":yt(r,"uri",n.message,e);break;case"uuid":yt(r,"uuid",n.message,e);break;case"regex":Ue(r,n.regex,n.message,e);break;case"cuid":Ue(r,gt.cuid,n.message,e);break;case"cuid2":Ue(r,gt.cuid2,n.message,e);break;case"startsWith":Ue(r,RegExp(`^${dl(n.value,e)}`),n.message,e);break;case"endsWith":Ue(r,RegExp(`${dl(n.value,e)}$`),n.message,e);break;case"datetime":yt(r,"date-time",n.message,e);break;case"date":yt(r,"date",n.message,e);break;case"time":yt(r,"time",n.message,e);break;case"duration":yt(r,"duration",n.message,e);break;case"length":Q(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Q(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ue(r,RegExp(dl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&yt(r,"ipv4",n.message,e),n.version!=="v4"&&yt(r,"ipv6",n.message,e);break}case"base64url":Ue(r,gt.base64url,n.message,e);break;case"jwt":Ue(r,gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ue(r,gt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ue(r,gt.ipv6Cidr,n.message,e);break}case"emoji":Ue(r,gt.emoji(),n.message,e);break;case"ulid":{Ue(r,gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{Q(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ue(r,gt.base64,n.message,e);break}}break}case"nanoid":Ue(r,gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function dl(t,e){return e.patternStrategy==="escape"?Ak(t):t}var Ck=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ak(t){let e="";for(let r=0;r<t.length;r++)Ck.has(t[r])||(e+="\\"),e+=t[r];return e}function yt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Q(t,"format",e,r,n)}function Ue(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Ih(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Q(t,"pattern",Ih(e,n),r,n)}function Ih(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
51
|
+
`,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!Mx(o))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>Io.parse(v)):a=[Io.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=a.some($l);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let y=this.validateProtocolVersion(e);if(y)return y}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(Gt)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let d=crypto.randomUUID(),l=a.find(v=>$l(v)),p=l?l.params.protocolVersion:e.headers.get("mcp-protocol-version")??Dh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(d,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(d)}});for(let y of a)Gt(y)&&this._requestToStreamMapping.set(y.id,d);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,f,h,g=new ReadableStream({start:v=>{f=v},cancel:()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(d)?.controller===f&&this._streamMapping.delete(d)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)Gt(v)&&(this._streamMapping.set(d,{controller:f,encoder:m,cleanup:()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(d);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,d));try{await this.writePrimingEvent(f,m,d,p);for(let v of a){let y,x;Gt(v)&&this._eventStore&&p>="2025-11-25"&&(y=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:y,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(d)?.cleanup(),this._resumableStreams.delete(d);for(let y of a)Gt(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(d)?.controller===f&&(h=this.startKeepAlive(f,m)),new Response(g,{status:200,headers:_})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!Cn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Cn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Cn.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((Xt(e)||On(e))&&(n=e.id),n===void 0){if(Xt(e)||On(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i))&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e),s=this._streamMapping.get(o)),s?.controller&&s?.encoder&&(i===void 0||!s.replayedEventIds?.has(i))&&this.writeSSEEvent(s.controller,s.encoder,e,i)&&i!==void 0&&this._resumableStreams.add(o)}if(Xt(e)||On(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s){if(this._closed){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(o)){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o);return}for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);throw new Error(`No connection established for request ID: ${String(n)}`)}if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(d=>this._requestResponseMap.get(d));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o)}}}}});var qx={};fo(qx,{StreamableHTTPServerTransport:()=>Pp});var Pp,Fx=X(()=>{Rx();Lx();Pp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Ka(e),this._requestListener=Ep(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Ep(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var Z={};fo(Z,{BRAND:()=>kb,DIRTY:()=>Cr,EMPTY_PATH:()=>rb,INVALID:()=>D,NEVER:()=>aw,OK:()=>Me,ParseStatus:()=>Pe,Schema:()=>V,ZodAny:()=>cr,ZodArray:()=>Kt,ZodBigInt:()=>Ar,ZodBoolean:()=>Nr,ZodBranded:()=>mo,ZodCatch:()=>Vr,ZodDate:()=>Mr,ZodDefault:()=>Br,ZodDiscriminatedUnion:()=>Ps,ZodEffects:()=>ct,ZodEnum:()=>Ur,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Is,ZodIntersection:()=>Lr,ZodIssueCode:()=>k,ZodLazy:()=>qr,ZodLiteral:()=>Fr,ZodMap:()=>wn,ZodNaN:()=>kn,ZodNativeEnum:()=>Hr,ZodNever:()=>vt,ZodNull:()=>Zr,ZodNullable:()=>Ct,ZodNumber:()=>Or,ZodObject:()=>Ge,ZodOptional:()=>We,ZodParsedType:()=>z,ZodPipeline:()=>ho,ZodPromise:()=>ur,ZodReadonly:()=>Jr,ZodRecord:()=>Rs,ZodSchema:()=>V,ZodSet:()=>$n,ZodString:()=>ar,ZodSymbol:()=>xn,ZodTransformer:()=>ct,ZodTuple:()=>It,ZodType:()=>V,ZodUndefined:()=>jr,ZodUnion:()=>Dr,ZodUnknown:()=>Jt,ZodVoid:()=>bn,addIssueToContext:()=>T,any:()=>Ob,array:()=>jb,bigint:()=>zb,boolean:()=>Fp,coerce:()=>iw,custom:()=>Dp,date:()=>Pb,datetimeRegex:()=>jp,defaultErrorMap:()=>Bt,discriminatedUnion:()=>Lb,effect:()=>Yb,enum:()=>Wb,function:()=>Vb,getErrorMap:()=>yn,getParsedType:()=>Rt,instanceof:()=>Tb,intersection:()=>qb,isAborted:()=>Es,isAsync:()=>_n,isDirty:()=>zs,isValid:()=>ir,late:()=>Sb,lazy:()=>Jb,literal:()=>Kb,makeIssue:()=>po,map:()=>Hb,nan:()=>Eb,nativeEnum:()=>Gb,never:()=>Nb,null:()=>Cb,nullable:()=>ew,number:()=>qp,object:()=>tc,objectUtil:()=>Ya,oboolean:()=>sw,onumber:()=>ow,optional:()=>Qb,ostring:()=>nw,pipeline:()=>rw,preprocess:()=>tw,promise:()=>Xb,quotelessJson:()=>Qx,record:()=>Ub,set:()=>Bb,setErrorMap:()=>tb,strictObject:()=>Zb,string:()=>Lp,symbol:()=>Rb,transformer:()=>Yb,tuple:()=>Fb,undefined:()=>Ib,union:()=>Db,unknown:()=>Ab,util:()=>G,void:()=>Mb});var G;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(G||(G={}));var Ya;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ya||(Ya={}));var z=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var k=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Qx=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ke.create=t=>new Ke(t);var eb=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,G.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${G.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${G.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${G.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:G.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,G.assertNever(t)}return{message:r}},Bt=eb;var Cp=Bt;function tb(t){Cp=t}function yn(){return Cp}var po=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},rb=[];function T(t,e){let r=yn(),n=po({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Bt?void 0:Bt].filter(o=>!!o)});t.common.issues.push(n)}var Pe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return D;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return D;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},D=Object.freeze({status:"aborted"}),Cr=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Es=t=>t.status==="aborted",zs=t=>t.status==="dirty",ir=t=>t.status==="valid",_n=t=>typeof Promise<"u"&&t instanceof Promise;var O;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var at=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Op=(t,e)=>{if(ir(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ke(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return Rt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(_n(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Op(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ir(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ir(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(_n(o)?o:Promise.resolve(o));return Op(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new ct({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return We.create(this,this._def)}nullable(){return Ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return ur.create(this,this._def)}or(e){return Dr.create([this,e],this._def)}and(e){return Lr.create(this,e,this._def)}transform(e){return new ct({...H(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Br({...H(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new mo({typeName:S.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vr({...H(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ho.create(this,e)}readonly(){return Jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nb=/^c[^\s-]{8,}$/i,ob=/^[0-9a-z]+$/,sb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ib=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ab=/^[a-z0-9_-]{21}$/i,cb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ub=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,lb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,db="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qa,fb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,mb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,hb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Np="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",_b=new RegExp(`^${Np}$`);function Mp(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function vb(t){return new RegExp(`^${Mp(t)}$`)}function jp(t){let e=`${Np}T${Mp(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function xb(t,e){return!!((e==="v4"||!e)&&fb.test(t)||(e==="v6"||!e)&&mb.test(t))}function bb(t,e){if(!cb.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function wb(t,e){return!!((e==="v4"||!e)&&pb.test(t)||(e==="v6"||!e)&&hb.test(t))}var ar=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:z.string,received:s.parsedType}),D}let n=new Pe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")lb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Qa||(Qa=new RegExp(db,"u")),Qa.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")ib.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ab.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")nb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")ob.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")sb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?jp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?_b.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?vb(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ub.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?xb(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?bb(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?wb(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?gb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?yb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):G.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...O.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...O.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...O.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...O.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...O.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...O.errToObj(r)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ar.create=t=>new ar({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...H(t)});function $b(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Or=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:z.number,received:s.parsedType}),D}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?$b(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_finite,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Or.create=t=>new Or({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Ar=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new Pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:z.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ar.create=t=>new Ar({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Nr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.boolean,received:n.parsedType}),D}return Me(e.data)}};Nr.create=t=>new Nr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Mr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:z.date,received:s.parsedType}),D}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),D}let n=new Pe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):G.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Mr.create=t=>new Mr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...H(t)});var xn=class extends V{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.symbol,received:n.parsedType}),D}return Me(e.data)}};xn.create=t=>new xn({typeName:S.ZodSymbol,...H(t)});var jr=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.undefined,received:n.parsedType}),D}return Me(e.data)}};jr.create=t=>new jr({typeName:S.ZodUndefined,...H(t)});var Zr=class extends V{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.null,received:n.parsedType}),D}return Me(e.data)}};Zr.create=t=>new Zr({typeName:S.ZodNull,...H(t)});var cr=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};cr.create=t=>new cr({typeName:S.ZodAny,...H(t)});var Jt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};Jt.create=t=>new Jt({typeName:S.ZodUnknown,...H(t)});var vt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:z.never,received:r.parsedType}),D}};vt.create=t=>new vt({typeName:S.ZodNever,...H(t)});var bn=class extends V{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.void,received:n.parsedType}),D}return Me(e.data)}};bn.create=t=>new bn({typeName:S.ZodVoid,...H(t)});var Kt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return T(r,{code:k.invalid_type,expected:z.array,received:r.parsedType}),D;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new at(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new at(r,i,r.path,a)));return Pe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:O.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:O.toString(r)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...H(e)});function vn(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=We.create(vn(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:vn(t.element)}):t instanceof We?We.create(vn(t.unwrap())):t instanceof Ct?Ct.create(vn(t.unwrap())):t instanceof It?It.create(t.items.map(e=>vn(e))):t}var Ge=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=G.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:z.object,received:u.parsedType}),D}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof vt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=s[u],l=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new at(o,l,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof vt){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")a.length>0&&(T(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new at(o,l,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:O.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of G.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return vn(this)}partial(e){let r={};for(let n of G.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof We;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Zp(G.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:vt.create(),typeName:S.ZodObject,...H(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:vt.create(),typeName:S.ZodObject,...H(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:vt.create(),typeName:S.ZodObject,...H(e)});var Dr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ke(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ke(c));return T(r,{code:k.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Dr.create=(t,e)=>new Dr({options:t,typeName:S.ZodUnion,...H(e)});var Vt=t=>t instanceof qr?Vt(t.schema):t instanceof ct?Vt(t.innerType()):t instanceof Fr?[t.value]:t instanceof Ur?t.options:t instanceof Hr?G.objectValues(t.enum):t instanceof Br?Vt(t._def.innerType):t instanceof jr?[void 0]:t instanceof Zr?[null]:t instanceof We?[void 0,...Vt(t.unwrap())]:t instanceof Ct?[null,...Vt(t.unwrap())]:t instanceof mo||t instanceof Jr?Vt(t.unwrap()):t instanceof Vr?Vt(t._def.innerType):[],Ps=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return T(r,{code:k.invalid_type,expected:z.object,received:r.parsedType}),D;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Vt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...H(n)})}};function ec(t,e){let r=Rt(t),n=Rt(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=G.objectKeys(e),s=G.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=ec(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=ec(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Lr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Es(s)||Es(i))return D;let a=ec(s.value,i.value);return a.valid?((zs(s)||zs(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Lr.create=(t,e,r)=>new Lr({left:t,right:e,typeName:S.ZodIntersection,...H(r)});var It=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return T(n,{code:k.invalid_type,expected:z.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new at(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Pe.mergeArray(r,i)):Pe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};It.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new It({items:t,typeName:S.ZodTuple,rest:null,...H(e)})};var Rs=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return T(n,{code:k.invalid_type,expected:z.object,received:n.parsedType}),D;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new at(n,a,n.path,a)),value:i._parse(new at(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pe.mergeObjectAsync(r,o):Pe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...H(n)}):new t({keyType:ar.create(),valueType:e,typeName:S.ZodRecord,...H(r)})}},wn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return T(n,{code:k.invalid_type,expected:z.map,received:n.parsedType}),D;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new at(n,a,n.path,[u,"key"])),value:s._parse(new at(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return D;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return D;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};wn.create=(t,e,r)=>new wn({valueType:e,keyType:t,typeName:S.ZodMap,...H(r)});var $n=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return T(n,{code:k.invalid_type,expected:z.set,received:n.parsedType}),D;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return D;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new at(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:O.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};$n.create=(t,e)=>new $n({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...H(e)});var Is=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return T(r,{code:k.invalid_type,expected:z.function,received:r.parsedType}),D;function n(a,c){return po({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,yn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return po({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,yn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ur){let a=this;return Me(async function(...c){let u=new Ke([]),d=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,s).catch(m=>{throw u.addIssue(o(l,m)),u})})}else{let a=this;return Me(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ke([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,s);if(!l.success)throw new Ke([o(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:It.create(e).rest(Jt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||It.create([]).rest(Jt.create()),returns:r||Jt.create(),typeName:S.ZodFunction,...H(n)})}},qr=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};qr.create=(t,e)=>new qr({getter:t,typeName:S.ZodLazy,...H(e)});var Fr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fr.create=(t,e)=>new Fr({value:t,typeName:S.ZodLiteral,...H(e)});function Zp(t,e){return new Ur({values:t,typeName:S.ZodEnum,...H(e)})}var Ur=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:G.joinValues(n),received:r.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:k.invalid_enum_value,options:n}),D}return Me(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ur.create=Zp;var Hr=class extends V{_parse(e){let r=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=G.objectValues(r);return T(n,{expected:G.joinValues(o),received:n.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=G.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:o}),D}return Me(e.data)}get enum(){return this._def.values}};Hr.create=(t,e)=>new Hr({values:t,typeName:S.ZodNativeEnum,...H(e)});var ur=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:z.promise,received:r.parsedType}),D;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Me(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ur.create=(t,e)=>new ur({type:t,typeName:S.ZodPromise,...H(e)});var ct=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Cr(c.value):r.value==="dirty"?Cr(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?Cr(a.value):r.value==="dirty"?Cr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ir(i))return D;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ir(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):D);G.assertNever(o)}};ct.create=(t,e,r)=>new ct({schema:t,typeName:S.ZodEffects,effect:e,...H(r)});ct.createWithPreprocess=(t,e,r)=>new ct({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...H(r)});var We=class extends V{_parse(e){return this._getType(e)===z.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};We.create=(t,e)=>new We({innerType:t,typeName:S.ZodOptional,...H(e)});var Ct=class extends V{_parse(e){return this._getType(e)===z.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ct.create=(t,e)=>new Ct({innerType:t,typeName:S.ZodNullable,...H(e)});var Br=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Vr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _n(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vr.create=(t,e)=>new Vr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var kn=class extends V{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:z.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};kn.create=t=>new kn({typeName:S.ZodNaN,...H(t)});var kb=Symbol("zod_brand"),mo=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ho=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),Cr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},Jr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ir(o)&&(o.value=Object.freeze(o.value)),o);return _n(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Jr.create=(t,e)=>new Jr({innerType:t,typeName:S.ZodReadonly,...H(e)});function Ap(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Dp(t,e={},r){return t?cr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Ap(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Ap(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):cr.create()}var Sb={object:Ge.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var Tb=(t,e={message:`Input not instance of ${t.name}`})=>Dp(r=>r instanceof t,e),Lp=ar.create,qp=Or.create,Eb=kn.create,zb=Ar.create,Fp=Nr.create,Pb=Mr.create,Rb=xn.create,Ib=jr.create,Cb=Zr.create,Ob=cr.create,Ab=Jt.create,Nb=vt.create,Mb=bn.create,jb=Kt.create,tc=Ge.create,Zb=Ge.strictCreate,Db=Dr.create,Lb=Ps.create,qb=Lr.create,Fb=It.create,Ub=Rs.create,Hb=wn.create,Bb=$n.create,Vb=Is.create,Jb=qr.create,Kb=Fr.create,Wb=Ur.create,Gb=Hr.create,Xb=ur.create,Yb=ct.create,Qb=We.create,ew=Ct.create,tw=ct.createWithPreprocess,rw=ho.create,nw=()=>Lp().optional(),ow=()=>qp().optional(),sw=()=>Fp().optional(),iw={string:(t=>ar.create({...t,coerce:!0})),number:(t=>Or.create({...t,coerce:!0})),boolean:(t=>Nr.create({...t,coerce:!0})),bigint:(t=>Ar.create({...t,coerce:!0})),date:(t=>Mr.create({...t,coerce:!0}))};var aw=D;Fe();Fe();Fe();Fe();var g$=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(t,e),t.def=e,t.parse=(r,n)=>gc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gr(t,r,n),t.parseAsync=async(r,n)=>_c(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Xr(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var y$=w("ZodMiniObject",(t,e)=>{Us.init(t,e),g$.init(t,e),Y.defineLazy(t,"shape",()=>e.shape)});function ol(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new y$(r)}Fe();Bs();function Nt(t){return!!t._zod}function en(t){let e=Object.values(t);if(e.length===0)return ol({});let r=e.every(Nt),n=e.every(o=>!Nt(o));if(r)return ol(t);if(n)return tc(t);throw new Error("Mixed Zod versions detected in object shape.")}function fr(t,e){return Nt(t)?Gr(t,e):t.safeParse(e)}async function Qs(t,e){return Nt(t)?await Xr(t,e):await t.safeParseAsync(e)}function pr(t){if(!t)return;let e;if(Nt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Pn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return en(t)}}if(Nt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function v$(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ei(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${v$(e.path)}`:e.message).join(`
|
|
52
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function lh(t){return t.description}function dh(t){if(Nt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Rn(t){if(Nt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}hr();function gr(t){return t==="completed"||t==="failed"||t==="cancelled"}var rg=Symbol("Let zodToJsonSchema decide on which parser to use");var tg={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},ng=t=>typeof t=="string"?{...tg,name:t}:{...tg,...t};var og=t=>{let e=ng(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Al(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,Al(t,e,n,o)}var Si=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Si(e,t.currentPath):e.join("/")}}function sg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ig(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function ag(){return{type:"boolean"}}function Ti(t,e){return q(t.type._def,e)}var cg=(t,e)=>q(t.innerType._def,e);function Nl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Nl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return BS(t,e)}}var BS=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function ug(t,e){return{...q(t.innerType._def,e),default:t.defaultValue()}}function lg(t,e){return e.effectStrategy==="input"?q(t.schema._def,e):we(e)}function dg(t){return{type:"string",enum:Array.from(t.values)}}var VS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function fg(t,e){let r=[q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),q(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(VS(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function pg(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Ml,bt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ml===void 0&&(Ml=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ml),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ei(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":wt(r,"email",n.message,e);break;case"format:idn-email":wt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,bt.email,n.message,e);break}break;case"url":wt(r,"uri",n.message,e);break;case"uuid":wt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,bt.cuid,n.message,e);break;case"cuid2":He(r,bt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${jl(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${jl(n.value,e)}$`),n.message,e);break;case"datetime":wt(r,"date-time",n.message,e);break;case"date":wt(r,"date",n.message,e);break;case"time":wt(r,"time",n.message,e);break;case"duration":wt(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(jl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&wt(r,"ipv4",n.message,e),n.version!=="v4"&&wt(r,"ipv6",n.message,e);break}case"base64url":He(r,bt.base64url,n.message,e);break;case"jwt":He(r,bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,bt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,bt.ipv6Cidr,n.message,e);break}case"emoji":He(r,bt.emoji(),n.message,e);break;case"ulid":{He(r,bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{wt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,bt.base64,n.message,e);break}}break}case"nanoid":He(r,bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function jl(t,e){return e.patternStrategy==="escape"?KS(t):t}var JS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function KS(t){let e="";for(let r=0;r<t.length;r++)JS.has(t[r])||(e+="\\"),e+=t[r];return e}function wt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:mg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",mg(e,n),r,n)}function mg(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
53
53
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
54
54
|
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
55
55
|
`:`[${n[c]}\r
|
|
56
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function hi(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=mi(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=pi(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Oh(t,e){if(e.mapStrategy==="record")return hi(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ch(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Ah(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Nh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Po={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function jh(t,e){if(e.target==="openApi3")return Mh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Po&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Po[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Mh(t,e)}var Mh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Zh(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Po[t.innerType._def.typeName],nullable:!0}:{type:[Po[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Dh(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",cl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Q(r,"minimum",n.value,n.message,e):Q(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Q(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Q(r,"maximum",n.value,n.message,e):Q(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Q(r,"maximum",n.value,n.message,e));break;case"multipleOf":Q(r,"multipleOf",n.value,n.message,e);break}return r}function qh(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Mk(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Z(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Nk(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Nk(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mk(t){try{return t.isOptional()}catch{return!0}}var Lh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Uh=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Fh(t,e){return Z(t.type._def,e)}function Hh(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Q(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Q(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Vh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Bh(t){return{not:we(t)}}function Jh(t){return we(t)}var Wh=(t,e)=>Z(t.innerType._def,e);var Kh=(t,e,r)=>{switch(e){case S.ZodString:return mi(t,r);case S.ZodNumber:return Dh(t,r);case S.ZodObject:return qh(t,r);case S.ZodBigInt:return $h(t,r);case S.ZodBoolean:return kh();case S.ZodDate:return ul(t,r);case S.ZodUndefined:return Bh(r);case S.ZodNull:return Nh(r);case S.ZodArray:return wh(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return jh(t,r);case S.ZodIntersection:return Ph(t,r);case S.ZodTuple:return Vh(t,r);case S.ZodRecord:return hi(t,r);case S.ZodLiteral:return Rh(t,r);case S.ZodEnum:return zh(t);case S.ZodNativeEnum:return Ch(t);case S.ZodNullable:return Zh(t,r);case S.ZodOptional:return Lh(t,r);case S.ZodMap:return Oh(t,r);case S.ZodSet:return Hh(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Fh(t,r);case S.ZodNaN:case S.ZodNever:return Ah(r);case S.ZodEffects:return Th(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Jh(r);case S.ZodDefault:return Eh(t,r);case S.ZodBranded:return pi(t,r);case S.ZodReadonly:return Wh(t,r);case S.ZodCatch:return Sh(t,r);case S.ZodPipeline:return Uh(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==vh)return a}if(n&&!r){let a=jk(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Kh(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&Zk(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var jk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fi(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},Zk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fl=(t,e)=>{let r=bh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Z(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Dk(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function pl(t,e){return Pt(t)?Iu(t,{target:Dk(e?.target),io:e?.pipeStrategy??"input"}):fl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ml(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hl(t,e){let r=or(t,e);if(!r.success)throw r.error;return r.data}var qk=6e4,gi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ws,r=>{this._oncancel(r)}),this.setNotificationHandler(Xs,r=>{this._onprogress(r)}),this.setRequestHandler(Gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ys,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ei,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new O(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new O(N.InvalidParams,`Task not found: ${s}`);if(!ar(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(ar(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[ir]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ti,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new O(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ni,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new O(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(ar(o.status))throw new O(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof O?o:new O(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),O.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ht(s)||Sn(s)?this._onresponse(s):Ft(s)?this._onrequest(s,i):ch(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=O.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[ir]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=sh(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new O(N.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ht(e))n(e);else{let i=new O(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Ht(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Ht(e))o(e);else{let i=O.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,En,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},ar(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new O(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[ir]:c}});let f=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let g=v instanceof O?v:new O(N.RequestTimeout,String(v));l(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let g=or(r,v.result);g.success?u(g.data):l(g.error)}catch(g){l(g)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??qk,y=()=>f(O.fromError(N.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=g=>{let x=this._responseHandlers.get(p);x?x(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),l(g)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qs,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ri,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},lh,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ir]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ir]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ir]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ml(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=hl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ml(e);this._notificationHandlers.set(n,o=>{let s=hl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ft(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new O(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new O(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new O(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new O(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=So.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ar(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new O(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ar(a.status))throw new O(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=So.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ar(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Gh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Xh(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Gh(i)&&Gh(s)?r[o]={...i,...s}:r[o]=s}return r}Vr();var G_=Sa(cf(),1),X_=Sa(K_(),1);function XR(){let t=new G_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,X_.default)(t),t}var Qi=class{constructor(e){this._ajv=e??XR()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};Vr();var ea=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},zo,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Pn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Y_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Q_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ta=class extends gi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(To.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Qi,this.setRequestHandler(Ks,n=>this._oninitialize(n)),this.setNotificationHandler(Yu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(sl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=To.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ea(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Xh(this._capabilities,e)}setRequestHandler(e,r){let o=sr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=wn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=or(zn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new O(N.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let f=or(En,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new O(N.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=or(li,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new O(N.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Q_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Y_(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:kn.includes(r)?r:Ju,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Js)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},il,r):this.request({method:"sampling/createMessage",params:e},zo,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Pn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Pn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new O(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},al,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Vr();var tv=Symbol.for("mcp.completable");function gf(t){return!!t&&typeof t=="object"&&tv in t}function rv(t){return t[tv]?.complete}var ev;(function(t){t.Completable="McpCompletable"})(ev||(ev={}));var YR=/^[A-Za-z0-9._-]{1,128}$/;function QR(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!YR.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function e1(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function yf(t){let e=QR(t);return e1(t,e.warnings),e.isValid}var ra=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var na=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ta(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ra(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ui)),this.server.assertCanSetRequestHandler(gr(zn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ui,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=bn(r.inputSchema);return o?pl(o,{strictUnions:!0,pipeStrategy:"input"}):t1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=bn(r.outputSchema);o&&(n.outputSchema=pl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(zn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new O(N.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new O(N.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new O(N.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof O&&n.code===N.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=bn(e.inputSchema)??e.inputSchema,i=await qs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ls(a);throw new O(N.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new O(N.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=bn(e.outputSchema),s=await qs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ls(i);throw new O(N.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new O(N.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(gr(di)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(di,async e=>{switch(e.params.ref.type){case"ref/prompt":return gh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return yh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new O(N.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new O(N.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return is;let s=sr(n.argsSchema)?.[e.params.argument.name];if(!gf(s))return is;let i=rv(s);if(!i)return is;let a=await i(e.params.argument.value,e.params.context);return ov(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return is;throw new O(N.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return is;let s=await o(e.params.argument.value,e.params.context);return ov(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(oi)),this.server.assertCanSetRequestHandler(gr(si)),this.server.assertCanSetRequestHandler(gr(ii)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oi,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(si,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ii,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new O(N.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new O(N.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(gr(ai)),this.server.assertCanSetRequestHandler(gr(ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ai,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?r1(r.argsSchema):void 0}))})),this.server.setRequestHandler(ci,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new O(N.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new O(N.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=bn(n.argsSchema),s=await qs(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ls(c);throw new O(N.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Hr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Hr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Be?c._def?.innerType:c;return gf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){yf(e);let l={title:r,description:n,inputSchema:nv(o),outputSchema:nv(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&yf(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(_f(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!_f(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var t1={type:"object",properties:{}};function sv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function iv(t){return"_def"in t||"_zod"in t||sv(t)}function _f(t){return typeof t!="object"||t===null||iv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(sv)}function nv(t){if(t){if(_f(t))return Hr(t);if(!iv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function r1(t){let e=sr(t);return e?Object.entries(e).map(([r,n])=>{let o=Tm(n),s=zm(n);return{name:r,description:o,required:!s}}):[]}function gr(t){let r=sr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function ov(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var is={completion:{values:[],hasMore:!1}};import cv from"node:process";Vr();var n1=10*1024*1024,oa=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??n1}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
57
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
58
|
-
`}var
|
|
59
|
-
`);a+=
|
|
60
|
-
`:"")+p.text,i||=p.hasBinary,p.kind&&(a=p.kind),c??=p.toolName,p.call&&(u+=p.call)}let
|
|
61
|
-
`):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return
|
|
62
|
-
`),
|
|
56
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function zi(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ei(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ti(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function hg(t,e){if(e.mapStrategy==="record")return zi(t,e);let r=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function gg(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function yg(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function _g(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Lo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xg(t,e){if(e.target==="openApi3")return vg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Lo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Lo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return vg(t,e)}var vg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function bg(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Lo[t.innerType._def.typeName],nullable:!0}:{type:[Lo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function wg(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Al(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function $g(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=GS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=WS(t,e);return i!==void 0&&(n.additionalProperties=i),n}function WS(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function GS(t){try{return t.isOptional()}catch{return!0}}var kg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Sg=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let r=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Tg(t,e){return q(t.type._def,e)}function Eg(t,e){let n={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function zg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Pg(t){return{not:we(t)}}function Rg(t){return we(t)}var Ig=(t,e)=>q(t.innerType._def,e);var Cg=(t,e,r)=>{switch(e){case S.ZodString:return Ei(t,r);case S.ZodNumber:return wg(t,r);case S.ZodObject:return $g(t,r);case S.ZodBigInt:return ig(t,r);case S.ZodBoolean:return ag();case S.ZodDate:return Nl(t,r);case S.ZodUndefined:return Pg(r);case S.ZodNull:return _g(r);case S.ZodArray:return sg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return xg(t,r);case S.ZodIntersection:return fg(t,r);case S.ZodTuple:return zg(t,r);case S.ZodRecord:return zi(t,r);case S.ZodLiteral:return pg(t,r);case S.ZodEnum:return dg(t);case S.ZodNativeEnum:return gg(t);case S.ZodNullable:return bg(t,r);case S.ZodOptional:return kg(t,r);case S.ZodMap:return hg(t,r);case S.ZodSet:return Eg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Tg(t,r);case S.ZodNaN:case S.ZodNever:return yg(r);case S.ZodEffects:return lg(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Rg(r);case S.ZodDefault:return ug(t,r);case S.ZodBranded:return Ti(t,r);case S.ZodReadonly:return Ig(t,r);case S.ZodCatch:return cg(t,r);case S.ZodPipeline:return Sg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==rg)return a}if(n&&!r){let a=XS(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Cg(t,t.typeName,e),i=typeof s=="function"?q(s(),e):s;if(i&&YS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var XS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Si(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},YS=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Zl=(t,e)=>{let r=og(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:q(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function QS(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Dl(t,e){return Nt(t)?nl(t,{target:QS(e?.target),io:e?.pipeStrategy??"input"}):Zl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ll(t){let r=pr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Rn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ql(t,e){let r=fr(t,e);if(!r.success)throw r.error;return r.data}var eT=6e4,Pi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ai,r=>{this._oncancel(r)}),this.setNotificationHandler(li,r=>{this._onprogress(r)}),this.setRequestHandler(ui,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(di,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(M.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(pi,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new I(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(M.InvalidParams,`Task not found: ${s}`);if(!gr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(gr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[mr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(mi,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(gi,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(gr(o.status))throw new I(M.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(M.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Xt(s)||On(s)?this._onresponse(s):Gt(s)?this._onrequest(s,i):Bh(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[mr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Fh(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new I(M.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(d,l,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xt(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Xt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Xt(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(M.InternalError,String(i))}}return}let s;try{let i=await this.request(e,An,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},gr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[mr]:c}});let f=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof I?v:new I(M.RequestTimeout,String(v));d(y)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let y=fr(r,v.result);y.success?u(y.data):d(y.error)}catch(y){d(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??eT,g=()=>f(I.fromError(M.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(p);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(p),d(y)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},fi,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},hi,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Jh,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[mr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[mr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[mr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ll(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ql(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Ll(e);this._notificationHandlers.set(n,o=>{let s=ql(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Gt(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(M.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Mo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),gr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(M.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(gr(a.status))throw new I(M.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Mo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),gr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Og(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ag(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Og(i)&&Og(s)?r[o]={...i,...s}:r[o]=s}return r}hr();var O0=Xa(Af(),1),A0=Xa(C0(),1);function dI(){let t=new O0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,A0.default)(t),t}var fa=class{constructor(e){this._ajv=e??dI()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};hr();var pa=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(d=>d.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(s.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==l.size||![...d].every(p=>l.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Do,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},jn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function N0(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function M0(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ma=class extends Pi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zo.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fa,this.setRequestHandler(ci,n=>this._oninitialize(n)),this.setNotificationHandler(kl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Il,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Zo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ag(this._capabilities,e)}setRequestHandler(e,r){let o=pr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Rn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=fr(Mn,c);if(!d.success){let f=d.error instanceof Error?d.error.message:String(d.error);throw new I(M.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let f=fr(An,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new I(M.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=fr($i,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new I(M.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){M0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&N0(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Cn.includes(r)?r:vl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ii)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Cl,r):this.request({method:"sampling/createMessage",params:e},Do,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},jn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},jn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(M.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ol,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};hr();var Z0=Symbol.for("mcp.completable");function Ff(t){return!!t&&typeof t=="object"&&Z0 in t}function D0(t){return t[Z0]?.complete}var j0;(function(t){t.Completable="McpCompletable"})(j0||(j0={}));var ha=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",o=0,s=0;for(;o<e.length;)if(e[o]==="{"){n&&(r.push(n),n="");let i=e.indexOf("}",o);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(o+1,i),c=this.getOperator(a),u=a.includes("*"),d=this.getNames(a),l=d[0];for(let p of d)t.validateLength(p,1e6,"Variable name");r.push({name:l,operator:c,names:d,exploded:u}),o=i+1}else n+=e[o],o++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let u=r[c];if(u===void 0)return"";let d=Array.isArray(u)?u.map(l=>this.encodeValue(l,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${d}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[e.name];if(n===void 0)return"";let s=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let s=this.expandPart(o,e);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let s of e.names)t.validateLength(s,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){let i=e.names[s],a=s===0?"\\"+e.operator:"&";r.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n,o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let a of this.parts)if(typeof a=="string")r+=this.escapeRegExp(a);else{let c=this.partToRegExp(a);for(let{pattern:u,name:d}of c)r+=u,n.push({name:d,exploded:a.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let o=new RegExp(r),s=e.match(o);if(!s)return null;let i={};for(let a=0;a<n.length;a++){let{name:c,exploded:u}=n[a],d=s[a+1],l=c.replace("*","");u&&d.includes(",")?i[l]=d.split(","):i[l]=d}return i}};var fI=/^[A-Za-z0-9._-]{1,128}$/;function pI(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!fI.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function mI(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Uf(t){let e=pI(t);return mI(t,e.warnings),e.isValid}var ga=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var ya=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ma(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ga(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Sr(wi)),this.server.assertCanSetRequestHandler(Sr(Mn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(wi,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Pn(r.inputSchema);return o?Dl(o,{strictUnions:!0,pipeStrategy:"input"}):hI})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Pn(r.outputSchema);o&&(n.outputSchema=Dl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new I(M.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new I(M.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new I(M.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new I(M.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof I&&n.code===M.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Pn(e.inputSchema)??e.inputSchema,i=await Qs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ei(a);throw new I(M.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new I(M.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Pn(e.outputSchema),s=await Qs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ei(i);throw new I(M.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,d));let l=await n.taskStore.getTask(c);if(!l)throw new I(M.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Sr(ki)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ki,async e=>{switch(e.params.ref.type){case"ref/prompt":return Qh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return eg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new I(M.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new I(M.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new I(M.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ys;let s=pr(n.argsSchema)?.[e.params.argument.name];if(!Ff(s))return ys;let i=D0(s);if(!i)return ys;let a=await i(e.params.argument.value,e.params.context);return q0(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ys;throw new I(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ys;let s=await o(e.params.argument.value,e.params.context);return q0(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Sr(yi)),this.server.assertCanSetRequestHandler(Sr(_i)),this.server.assertCanSetRequestHandler(Sr(vi)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(yi,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(_i,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(vi,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new I(M.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new I(M.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Sr(xi)),this.server.assertCanSetRequestHandler(Sr(bi)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xi,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?gI(r.argsSchema):void 0}))})),this.server.setRequestHandler(bi,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new I(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new I(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Pn(n.argsSchema),s=await Qs(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=ei(c);throw new I(M.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:en(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=en(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof We?c._def?.innerType:c;return Ff(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Uf(e);let d={title:r,description:n,inputSchema:L0(o),outputSchema:L0(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Uf(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=en(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=en(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Hf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Hf(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},_a=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new ha(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},hI={type:"object",properties:{}};function F0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function U0(t){return"_def"in t||"_zod"in t||F0(t)}function Hf(t){return typeof t!="object"||t===null||U0(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(F0)}function L0(t){if(t){if(Hf(t))return en(t);if(!U0(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function gI(t){let e=pr(t);return e?Object.entries(e).map(([r,n])=>{let o=lh(n),s=dh(n);return{name:r,description:o,required:!s}}):[]}function Sr(t){let r=pr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Rn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function q0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ys={completion:{values:[],hasMore:!1}};import B0 from"node:process";hr();var yI=10*1024*1024,va=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??yI}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
57
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),_I(r)}clear(){this._buffer=void 0}};function _I(t){return Io.parse(JSON.parse(t))}function H0(t){return JSON.stringify(t)+`
|
|
58
|
+
`}var xa=class{constructor(e=B0.stdin,r=B0.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new va({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=H0(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};hr();function ba(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(t==null)return{text:"",hasBinary:!1};if(!Array.isArray(t))return{text:JSON.stringify(t??""),hasBinary:!1};let e="",r=!1,n,o,s="",i;for(let a of t){if(a==null||typeof a!="object"){e+=String(a??"");continue}let c=a;switch(c.type){case"text":case"input_text":case"output_text":e+=c.text??"";break;case"tool_use":{o="tool_call",n=c.name??n;let u=`[tool call: ${c.name}] ${JSON.stringify(c.input??{})}`;e+=u,s+=u;break}case"tool_result":{o="tool_result";let u=ba(c.content);r=r||u.hasBinary,e+=u.text,c.is_error===!0&&(i=!0);break}case"image":case"document":r=!0,e+=`[${c.type}]`;break;case"image_url":case"input_image":r=!0,e+="[image]";break;case"input_audio":r=!0,e+="[audio]";break;case"file":case"input_file":r=!0,e+="[file]";break;case"thinking":e+=c.thinking??"";break;case"redacted_thinking":e+="[redacted thinking]";break;default:e+=JSON.stringify(c)}}return{text:e,hasBinary:r,toolName:n,kind:o,toolCallText:s||void 0,isError:i}}function Jf(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ba(r.content),s=o.kind??(n==="developer"?"system":["system","user","assistant"].includes(n)?n:"other"),i=o.toolName,a=o.text,c=o.toolCallText;n==="tool"&&(s="tool_result");let u=r.tool_calls,d=Array.isArray(u)?u.filter(l=>l&&typeof l=="object"):void 0;if(d&&d.length>0){s="tool_call",i=d[0]?.function?.name??d[0]?.name;let l=d.map(p=>`[tool call: ${p.function?.name??p.name}] ${p.function?.arguments??JSON.stringify(p.input??{})}`).join(`
|
|
59
|
+
`);a+=l,c=(c??"")+l}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function Bf(t,e){let r=t.trimStart()[0];return{sourceFormat:"text",parseWarning:t.trim()===""?"Input is empty \u2014 nothing to profile.":e&&(r==="{"||r==="[")?`Input starts like JSON but does not parse (${e.message}), so it is not a conversation file.`:void 0,messages:t.trim()===""?[]:[{index:0,role:"user",kind:"user",text:t,hasBinary:!1}]}}function vI(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(!t||typeof t!="object")return{text:"",hasBinary:!1};let e=t;if(typeof e.text=="string")return{text:e.text,hasBinary:!1};if(e.inlineData||e.fileData)return{text:"[file]",hasBinary:!0};if(e.functionCall){let r=`[tool call: ${e.functionCall.name}] ${JSON.stringify(e.functionCall.args??{})}`;return{text:r,hasBinary:!1,kind:"tool_call",toolName:e.functionCall.name,call:r}}if(e.functionResponse){let r=e.functionResponse.response;return{text:typeof r?.output=="string"?r.output:typeof r?.content=="string"?r.content:JSON.stringify(r??{}),hasBinary:!1,kind:"tool_result",toolName:e.functionResponse.name}}return e.executableCode?{text:String(e.executableCode.code??""),hasBinary:!1}:e.codeExecutionResult?{text:String(e.codeExecutionResult.output??""),hasBinary:!1}:{text:JSON.stringify(e),hasBinary:!1}}function Vf(t,e){let r=t&&typeof t=="object"?t:{},n=r.role==="model"?"assistant":String(r.role??"user"),o=Array.isArray(r.parts)?r.parts:[],s="",i=!1,a,c,u="";for(let l of o){let p=vI(l);s+=(s&&p.text?`
|
|
60
|
+
`:"")+p.text,i||=p.hasBinary,p.kind&&(a=p.kind),c??=p.toolName,p.call&&(u+=p.call)}let d=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??d,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function xI(t,e){if(typeof t=="string")return{index:e,role:"user",kind:"user",text:t,hasBinary:!1};let r=t&&typeof t=="object"?t:{},n=r.type;if(n==="function_call"||n==="custom_tool_call"||n==="local_shell_call"){let o=r.name??(n==="local_shell_call"?"local_shell":void 0),s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.input??r.action??{}),i=`[tool call: ${o}] ${s}`;return{index:e,role:"assistant",kind:"tool_call",text:i,toolName:o,toolCallText:i,hasBinary:!1}}if(n==="function_call_output"||n==="custom_tool_call_output"||n==="local_shell_call_output"){let o=r.output,s=typeof o=="string"?{text:o,hasBinary:!1}:ba(o);return{index:e,role:"tool",kind:"tool_result",text:s.text,hasBinary:s.hasBinary}}if(n==="reasoning"){let o=Array.isArray(r.summary)?r.summary.map(s=>s?.text??"").join(`
|
|
61
|
+
`):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return Jf(r,e)}function V0(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return Bf("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(d){return Bf(t,d)}if(e===null||typeof e!="object")return Bf(t);if(Array.isArray(e)){let d=e.length===0||e.some(l=>l&&typeof l=="object"&&("role"in l||"parts"in l));return e.length>0&&e.every(l=>l&&typeof l=="object"&&Array.isArray(l.parts))?{sourceFormat:"gemini",messages:e.map((l,p)=>Vf(l,p))}:{sourceFormat:"array",parseWarning:d?void 0:"This is a JSON array, but no element has a `role` field \u2014 it does not look like a conversation.",messages:e.map((l,p)=>Jf(l,p))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let d=[],l=r.systemInstruction??r.system_instruction;if(l!=null){let p=typeof l=="string"?{text:l,hasBinary:!1}:Vf(l,-1);d.push({index:-1,role:"system",kind:"system",text:p.text,hasBinary:p.hasBinary})}return d.push(...r.contents.map((p,m)=>Vf(p,m))),{sourceFormat:"gemini",messages:d,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let d=[];typeof r.instructions=="string"&&r.instructions&&d.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let l=typeof r.input=="string"?[r.input]:r.input;return d.push(...l.map((p,m)=>xI(p,m))),{sourceFormat:"responses",messages:d,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let d=ba(r.system);a.push({index:-1,role:"system",kind:"system",text:d.text,hasBinary:d.hasBinary})}a.push(...s.map((d,l)=>Jf(d,l)));let c=r.system!=null||s.some(d=>Array.isArray(d?.content)&&d.content.some(l=>l?.type==="tool_use"||l?.type==="tool_result")),u=i?`\`messages\` is a ${typeof o}, not an array \u2014 this file is malformed.`:a.length===0?'This JSON has no `messages` array (and no `system`) \u2014 it does not look like a conversation. Expected {"messages":[{"role":\u2026,"content":\u2026}]}.':void 0;return{sourceFormat:c?"anthropic":"openai",parseWarning:u,messages:a,model:n}}import{createHash as WI}from"node:crypto";var J0=[[/claude.*haiku/i,2e5],[/claude.*(fable|mythos)|claude.*opus-?(5|4-[678])|claude.*sonnet-?(5|4-6)/i,1e6],[/claude.*sonnet|claude.*opus|claude-\d/i,2e5],[/gpt-5/i,4e5],[/gpt-4o|gpt-4-turbo|gpt-4\.1|o[134](-|$)/i,128e3],[/gpt-4(?!o|\.|-turbo)/i,8192],[/gpt-3\.5/i,16385],[/gemini.*(1\.5|2\.|2-5)/i,1e6],[/gemini-?3/i,1048576],[/llama.*3/i,128e3],[/mistral|mixtral/i,32e3]],G4=Math.max(...J0.map(([,t])=>t));function wa(t){if(t){for(let[e,r]of J0)if(e.test(t))return r}}function mn(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function bI(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var $a={anthropic:{prose:2.75,code:2.4},openai:{prose:4,code:3.2},google:{prose:4,code:3.2},generic:{prose:4,code:3.2}};function wI(t){return bI(t)>.08}function ka(t,e){let r=$a[mn(e)];return wI(t)?r.code:r.prose}function zt(t,e){return typeof t!="string"&&(t=String(t??"")),t?Math.ceil(t.length/ka(t,e)):0}var Kf=4;function A(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${A(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var ie=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Ne(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var Sa=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],$I=[[Ne("fable|mythos",5,1),ie(10,50,.25)],[Ne("fable|mythos",5),ie(10,50,1)],[Ne("opus",5,5),ie(4,20,.2)],[Ne("opus",5),ie(5,25,.5)],[Ne("opus",4,8),ie(5,25,.5)],[Ne("opus",4,7),ie(5,25,.5)],[Ne("opus",4,6),ie(5,25,.5)],[Ne("opus",4,5),ie(5,25,.5)],[Ne("opus",4,1),ie(15,75,1.5)],[Ne("opus",4),ie(15,75,1.5)],[/claude-3-opus/i,ie(15,75,1.5)],[Ne("sonnet",5,5),ie(2,10,.2)],[Ne("sonnet",5),ie(2,10,.2)],[Ne("haiku",5,5),ie(.1,.5,.01)],[Ne("haiku",4,5),ie(1,5,.1)],[/claude-3-5-haiku/i,ie(.8,4,.08)],[/claude-3-haiku/i,ie(.25,1.25,.03)],[Ne("sonnet",4,6),ie(3,15,.3)],[Ne("sonnet",4,5),ie(3,15,.3)],[Ne("sonnet",4),ie(3,15,.3)],[/claude-3-[57]-sonnet/i,ie(3,15,.3)],[Sa[0],ie(10,50,1)],[Sa[1],ie(5,25,.5)],[Sa[2],ie(3,15,.3)],[Sa[3],ie(1,5,.1)],[/gpt-5.*(mini|nano)/i,{inputPerM:.25,outputPerM:2,cacheReadPerM:.025}],[/gpt-5/i,{inputPerM:1.25,outputPerM:10,cacheReadPerM:.125}],[/gpt-4o-mini/i,{inputPerM:.15,outputPerM:.6,cacheReadPerM:.075}],[/gpt-4o|gpt-4\.1/i,{inputPerM:2.5,outputPerM:10,cacheReadPerM:1.25}],[/gpt-4-turbo/i,{inputPerM:10,outputPerM:30,cacheReadPerM:10}],[/o[13](-|$)/i,{inputPerM:2,outputPerM:8,cacheReadPerM:1}],[/gemini-3[.\d]*-flash-lite/i,ie(.3,2.5,.03)],[/gemini-3\.1-flash-lite/i,ie(.25,1.5,.025)],[/gemini-3-flash/i,ie(.5,3,.05)],[/gemini-3[.\d]*-flash/i,ie(.75,3.75,.075)],[/gemini-3[.\d]*-pro/i,ie(2,12,.2)],[/gemini.*flash/i,{inputPerM:.1,outputPerM:.4,cacheReadPerM:.025}],[/gemini.*pro/i,{inputPerM:1.25,outputPerM:5,cacheReadPerM:.31}]];function to(t){if(t){for(let[e,r]of $I)if(e.test(t))return r}}function Tr(t,e){return t/1e6*e.inputPerM}function Wf(t){return t/25e3}function qt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var K0=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,kI="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function W0(t){if(t.startsWith("data:"))return!0;let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);if(e.size<24)return!1;let r=0;for(let n of e.values())n>r&&(r=n);return r/t.length<.35}function ro(t){for(let e of t.matchAll(K0))if(W0(e[0]))return!0;return!1}function Gf(t){return t.replace(K0,e=>W0(e)?kI:e)}import{mkdirSync as sL,readFileSync as LI,writeFileSync as iL}from"node:fs";import{dirname as qI,join as FI}from"node:path";import{appendFileSync as SI,existsSync as TI,mkdirSync as EI,readFileSync as zI,statSync as PI,writeFileSync as RI}from"node:fs";import{homedir as II}from"node:os";import{dirname as X0,join as Y0}from"node:path";var CI={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function OI(t){let e={...CI},r=new Map;for(let n of t){if(n.ev==="rollup"&&n.carried){e.optimizeSaved+=n.carried.optimizeSaved,e.optimizeUsd+=n.carried.optimizeUsd,e.proxySaved+=n.carried.proxySaved,e.proxyUsd+=n.carried.proxyUsd,e.proxyRequests+=n.carried.proxyRequests,e.checks+=n.carried.checks,e.warnings+=n.carried.warnings,e.shrinkage+=n.carried.shrinkage,n.carried.since&&(e.since=Math.min(e.since??n.carried.since,n.carried.since));continue}e.since=Math.min(e.since??n.ts,n.ts),n.ev==="optimize"?(e.optimizeSaved+=n.saved??0,e.optimizeUsd+=n.usd??0):n.ev==="proxy"?(e.proxySaved+=n.saved??0,e.proxyUsd+=n.usd??0,e.proxyRequests+=n.requests??0):(n.ev==="check"||n.ev===void 0)&&n.sid!=="doctor-probe"&&(e.checks++,n.warn&&e.warnings++,n.sid&&n.sid!=="mcp-sketch"&&typeof n.tok=="number"&&r.set(n.sid,[...r.get(n.sid)??[],n.tok]))}for(let n of r.values())for(let o=1;o<n.length;o++)n[o]<n[o-1]&&(e.shrinkage+=n[o-1]-n[o]);return e}function Xf(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??Y0(II(),".claude",".context-doctor-hook-state.json")}function AI(){return Y0(X0(Xf()),".context-doctor-ledger.jsonl")}var G0=100,NI=256*1024,MI=128*1024,jI=500,ZI=4*1024;function DI(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>G0?e.slice(0,G0):e}function Ta(t){let e=AI();try{if(EI(X0(e),{recursive:!0}),TI(e)&&PI(e).size>NI){let n=zI(e,"utf8").trimEnd().split(`
|
|
62
|
+
`),o=l=>{try{return[JSON.parse(l)]}catch{return[]}},s=new Set,i=0;for(let l=n.length-1;l>=0&&s.size<jI;l--){let p=Buffer.byteLength(n[l])+1;if(!(p>ZI)){if(i+p>MI)break;s.add(l),i+=p}}let a=n.filter((l,p)=>s.has(p)),c=n.filter((l,p)=>!s.has(p)).flatMap(o),u=OI(c),d={ts:Date.now(),ev:"rollup",carried:u};RI(e,[JSON.stringify(d),...a].join(`
|
|
63
63
|
`)+`
|
|
64
|
-
`)}
|
|
65
|
-
`)}catch{}}var k1=2,S1=.5,E1=2;function T1(){return $1(w1(Sf()),".context-doctor-calibration.json")}function z1(t){let e=(t??"").toLowerCase();return e.includes("claude")?"claude":/gpt|^o\d/.test(e)?"gpt":e.includes("gemini")?"gemini":e?e.split(/[-_/]/)[0]:"unknown"}function P1(){try{return JSON.parse(b1(T1(),"utf8"))}catch{return{}}}function hv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=P1()[z1(t)];if(!e||e.v!==k1||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<S1||r>E1?{factor:1,samples:0}:{factor:r,samples:e.samples}}function I1(t){switch(t.kind){case"system":return"system";case"user":return"user";case"assistant":return"assistant";case"tool_call":return"tool_calls";case"tool_result":return"tool_results";default:return"other"}}function O1(t,e){let r=new Map,n=0;for(let a of t){if(a.estSavings<=0)continue;if(a.messages.length===0){n+=a.estSavings;continue}let c=a.id==="near_duplicate"&&a.messages.length>2?a.messages.slice(1):[a.messages[a.messages.length-1]],u=a.estSavings/c.length;for(let l of c)r.set(l,Math.max(r.get(l)??0,u))}let o=Math.round([...r.values()].reduce((a,c)=>a+c,0)),s=Math.max(0,e-o),i=o+Math.min(n,s);return Math.min(i,Math.round(e*.9))}function C1(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function gv(t){return R1("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function A1(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function N1(t){let e=t.toLowerCase().replace(/\s+/g," ").trim().split(" "),r=e.length>1500,n=new Set;for(let o=0;o+8<=e.length;o++){let s=A1(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var yv=.6;function M1(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var _v=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function j1(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Z1(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;_v.lastIndex=0;for(let n of e.matchAll(_v)){let o=n[2].replace(/\\+$/,"");j1(o)&&r.add(o)}return[...r]}function vv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=hv(r),o=t.messages.map(g=>({msg:g,tokens:Math.round(sn(g.text,r)*n.factor)+wf})),s=o.reduce((g,x)=>g+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let g of o)i[I1(g.msg)]+=g.tokens;let a=[];for(let g of o)g.msg.kind==="tool_result"&&g.tokens>2e3&&a.push({id:"large_tool_result",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool result at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} is ~${g.tokens} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[g.msg.index]});for(let g of o)g.msg.kind==="tool_call"&&g.tokens>2e3&&a.push({id:"large_tool_call",severity:g.tokens>8e3?"high":"warn",estSavings:Math.round(g.tokens*.8),message:`Tool call at message #${g.msg.index}${g.msg.toolName?` (${g.msg.toolName})`:""} carries ~${g.tokens} tokens of arguments.`,suggestion:'Usually a whole file being written inline. Once it has run, replace the arguments with a reference ("wrote <path>") \u2014 or write files in smaller pieces so no single call carries the entire content.',messages:[g.msg.index]});let c=new Map;for(let g of o){if(g.msg.text.length<300)continue;let x=gv(g.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:g.tokens-wf,message:`Message #${g.msg.index} duplicates the content of message #${$} (~${g.tokens} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,g.msg.index]}):c.set(x,g.msg.index)}{let g=o.filter(L=>L.msg.text.length>=300).sort((L,_e)=>_e.tokens-L.tokens).slice(0,150),x=g.map(L=>N1(L.msg.text)),$=x.map(L=>L.size),D=new Set(a.filter(L=>L.id==="duplicate_content").flatMap(L=>L.messages)),R=g.map((L,_e)=>_e),ie=L=>{for(;R[L]!==L;)L=R[L]=R[R[L]];return L},ae=g.map(()=>({sim:0,partnerTokens:0}));for(let L=0;L<g.length;L++)for(let _e=L+1;_e<g.length;_e++){let $t=g[L],xr=g[_e];if(D.has($t.msg.index)&&D.has(xr.msg.index))continue;let ps=Math.min($[L],$[_e]),cn=Math.max($[L],$[_e]);if(cn===0||ps/cn<yv)continue;let ft=M1(x[L],x[_e]);ft<yv||(R[ie(L)]=ie(_e),ft>ae[L].sim&&(ae[L]={sim:ft,partnerTokens:xr.tokens}),ft>ae[_e].sim&&(ae[_e]={sim:ft,partnerTokens:$t.tokens}))}let Te=new Map;g.forEach((L,_e)=>{if(ae[_e].sim===0)return;let $t=ie(_e);Te.set($t,[...Te.get($t)??[],_e])});for(let L of Te.values()){if(L.length<2)continue;L.sort((pt,br)=>g[pt].msg.index-g[br].msg.index);let _e=L.slice(1),$t=_e.reduce((pt,br)=>pt+Math.round(Math.min(g[br].tokens,ae[br].partnerTokens)*ae[br].sim*.9),0),xr=L.map(pt=>ae[pt].sim),ps=Math.round(Math.min(...xr)*100),cn=Math.round(Math.max(...xr)*100),ft=L.map(pt=>g[pt].msg.index),Wf=ps===cn?`~${cn}%`:`${ps}-${cn}%`,O0=_e.reduce((pt,br)=>pt+g[br].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:$t,message:L.length===2?`Messages #${ft[0]} and #${ft[1]} are ${Wf} similar (~${Math.min(g[L[0]].tokens,g[L[1]].tokens)} tokens repeated with different framing).`:`${L.length} messages are ${Wf} similar to each other (${ft.slice(0,6).map(pt=>`#${pt}`).join(", ")}${ft.length>6?", \u2026":""}): ~${H(O0)} tokens in the ${_e.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:ft})}}let u=new Map;for(let g of o){if(g.msg.kind!=="tool_call"||!g.msg.toolCallText)continue;let x=gv(g.msg.toolCallText),$=u.get(x)??[];$.push(g.msg.index),u.set(x,$)}let l=g=>o.find(x=>x.msg.index>g&&x.msg.kind==="tool_result")?.msg;for(let[,g]of u){if(g.length<2)continue;let x=g.slice(1).filter((D,R)=>l(g[R])?.isError===!0).length,$=g.length-1-x;x>0&&a.push({id:"retried_tool_call",severity:x>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${x} time(s) after it failed (messages #${g.join(", #")}).`,suggestion:x>=3?"Three or more identical retries of a failing command is a loop. Each attempt keeps its error output in context; the answer is in the first error, not in the fourth attempt.":"A retry after a failure is normal once. The failed attempt's output stays in context though, so once the fix is understood the earlier error can go.",messages:g}),$>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${$} time(s) after it had already succeeded (messages #${g.join(", #")}).`,suggestion:"Repeating a call that already succeeded means the earlier result scrolled out of the model's attention \u2014 keep results in a compact recap instead of re-calling.",messages:g})}{let g=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of Z1(x.msg.toolName,x.msg.toolCallText))g.set($,[...g.get($)??[],x.msg.index]);for(let[x,$]of g){if($.length<3)continue;let D=o.filter(ie=>ie.msg.kind==="tool_result"&&$.some(ae=>ie.msg.index===ae+1)).reduce((ie,ae)=>ie+ae.tokens,0),R=Math.round(D*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:R>4e3?"high":"warn",estSavings:R,message:`${x.split("/").pop()} was read ${$.length} times (messages #${$.join(", #")}), keeping ${$.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:$})}}for(let g of o)g.msg.kind!=="tool_result"||g.tokens<500||!/Traceback \(most recent call last\)|command not found|npm error|ERR!|\bexit code [1-9]|Exception in thread|FAILED|error TS\d+/i.test(g.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(g.tokens*.85),message:`Message #${g.msg.index} holds ~${g.tokens} tokens of failed tool output (errors, stack trace or non-zero exit).`,suggestion:"Keep the one line that identifies the failure and drop the rest \u2014 a full trace has no value once the fix is understood.",messages:[g.msg.index]});for(let g of o)Jn(g.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(g.tokens*.9),message:`Message #${g.msg.index} contains a base64/binary blob (~${g.tokens} tokens of mostly meaningless characters).`,suggestion:"Never put base64 in text content \u2014 use the provider's file/image APIs or replace with a file reference.",messages:[g.msg.index]});let d=t.messages.filter(g=>g.kind==="user"||g.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,D)=>$+D.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${x} tokens.`,suggestion:"Summarize the older half of the conversation into a compact recap and drop the raw turns (context-doctor optimize --strategy prune-history).",messages:[]})}s>0&&i.system/s>.25&&i.system>2e3&&a.push({id:"large_system_prompt",severity:"info",estSavings:0,message:`System prompt is ~${i.system} tokens (${Math.round(i.system/s*100)}% of the context).`,suggestion:"A big system prompt is fine IF it is stable \u2014 put it first and use prompt caching (Anthropic: cache_control; OpenAI: automatic prefix caching) so you stop paying full price for it every call.",messages:[]}),(on(e)==="anthropic"||on(e)==="openai")&&a.push({id:"cache_ordering",severity:"info",estSavings:0,message:"Prompt caching only matches a byte-identical prefix.",suggestion:"Keep stable content (system prompt, tool definitions, reference docs) at the start and never interleave it with per-request content \u2014 a single changed byte early in the prompt invalidates the cache for everything after it.",messages:[]});let p=aa(e),m=p?s/p*100:void 0;m!==void 0&&m>70&&a.push({id:"near_window_limit",severity:m>90?"high":"warn",estSavings:0,message:`Context is at ~${m.toFixed(0)}% of ${e}'s window.`,suggestion:"Models degrade well before the hard limit (lost-in-the-middle). Compact now rather than when the request fails.",messages:[]});let f=o.map(g=>({index:g.msg.index,role:g.msg.role,kind:g.msg.kind,tokens:g.tokens,preview:C1(g.msg.text),toolName:g.msg.toolName})).sort((g,x)=>x.tokens-g.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((g,x)=>h[g.severity]-h[x.severity]||x.estSavings-g.estSavings);let y=O1(a,s),_=la(e),v;if(_){let g=as(s,_),x=as(y,_);v={perCallUsd:g,per1kCallsUsd:g*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:$f(s),ttftSavedSeconds:$f(y)}}return{totalTokens:s,model:e,contextWindow:p,usagePct:m,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:y,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as D1}from"node:crypto";var wv=10,fa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:wv};function q1(t){if(t?.name==="Write"&&typeof t.input?.file_path=="string")return t.input.file_path;let e=t?.name==="Bash"?String(t.input?.command??""):"",r=/(?:cat|tee)\s*>+\s*([^\s<]+)\s*<</.exec(e);return r?r[1]:null}function L1(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function xv(t,e,r){let n=Math.round(e*ua("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
|
|
66
|
-
[context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function
|
|
67
|
-
`):JSON.stringify(t)}function
|
|
68
|
-
`),u=e(c,i);if(u===c)return s;let
|
|
69
|
-
\u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function
|
|
70
|
-
`);let
|
|
71
|
-
`)}var
|
|
72
|
-
`)):(e.push(""),e.push(`Findings (recoverable ~${
|
|
73
|
-
`))}function
|
|
64
|
+
`)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=DI(r[n]);o===void 0?delete r[n]:r[n]=o}SI(e,JSON.stringify({ts:Date.now(),...r})+`
|
|
65
|
+
`)}catch{}}var UI=2,HI=.5,BI=2;function VI(){return FI(qI(Xf()),".context-doctor-calibration.json")}function JI(t){let e=(t??"").toLowerCase();return e.includes("claude")?"claude":/gpt|^o\d/.test(e)?"gpt":e.includes("gemini")?"gemini":e?e.split(/[-_/]/)[0]:"unknown"}function KI(){try{return JSON.parse(LI(VI(),"utf8"))}catch{return{}}}function Q0(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=KI()[JI(t)];if(!e||e.v!==UI||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<HI||r>BI?{factor:1,samples:0}:{factor:r,samples:e.samples}}function GI(t){switch(t.kind){case"system":return"system";case"user":return"user";case"assistant":return"assistant";case"tool_call":return"tool_calls";case"tool_result":return"tool_results";default:return"other"}}function XI(t,e){let r=new Map,n=0;for(let a of t){if(a.estSavings<=0)continue;if(a.messages.length===0){n+=a.estSavings;continue}let c=a.id==="near_duplicate"&&a.messages.length>2?a.messages.slice(1):[a.messages[a.messages.length-1]],u=a.estSavings/c.length;for(let d of c)r.set(d,Math.max(r.get(d)??0,u))}let o=Math.round([...r.values()].reduce((a,c)=>a+c,0)),s=Math.max(0,e-o),i=o+Math.min(n,s);return Math.min(i,Math.round(e*.9))}function YI(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function ev(t){return WI("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function QI(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function eC(t){let e=t.toLowerCase().replace(/\s+/g," ").trim().split(" "),r=e.length>1500,n=new Set;for(let o=0;o+8<=e.length;o++){let s=QI(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var tv=.6;function tC(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var rv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function rC(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function nC(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;rv.lastIndex=0;for(let n of e.matchAll(rv)){let o=n[2].replace(/\\+$/,"");rC(o)&&r.add(o)}return[...r]}function nv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=Q0(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(zt(y.text,r)*n.factor)+Kf})),s=o.reduce((y,x)=>y+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let y of o)i[GI(y.msg)]+=y.tokens;let a=[];for(let y of o)y.msg.kind==="tool_result"&&y.tokens>2e3&&a.push({id:"large_tool_result",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool result at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} is ~${y.tokens} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[y.msg.index]});for(let y of o)y.msg.kind==="tool_call"&&y.tokens>2e3&&a.push({id:"large_tool_call",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool call at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} carries ~${y.tokens} tokens of arguments.`,suggestion:'Usually a whole file being written inline. Once it has run, replace the arguments with a reference ("wrote <path>") \u2014 or write files in smaller pieces so no single call carries the entire content.',messages:[y.msg.index]});let c=new Map;for(let y of o){if(y.msg.text.length<300)continue;let x=ev(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-Kf,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${y.tokens} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,y.msg.index]}):c.set(x,y.msg.index)}{let y=o.filter(U=>U.msg.text.length>=300).sort((U,_e)=>_e.tokens-U.tokens).slice(0,150),x=y.map(U=>eC(U.msg.text)),$=x.map(U=>U.size),C=new Set(a.filter(U=>U.id==="duplicate_content").flatMap(U=>U.messages)),R=y.map((U,_e)=>_e),ae=U=>{for(;R[U]!==U;)U=R[U]=R[R[U]];return U},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let U=0;U<y.length;U++)for(let _e=U+1;_e<y.length;_e++){let Pt=y[U],Rr=y[_e];if(C.has(Pt.msg.index)&&C.has(Rr.msg.index))continue;let Ts=Math.min($[U],$[_e]),gn=Math.max($[U],$[_e]);if(gn===0||Ts/gn<tv)continue;let yt=tC(x[U],x[_e]);yt<tv||(R[ae(U)]=ae(_e),yt>ce[U].sim&&(ce[U]={sim:yt,partnerTokens:Rr.tokens}),yt>ce[_e].sim&&(ce[_e]={sim:yt,partnerTokens:Pt.tokens}))}let Ee=new Map;y.forEach((U,_e)=>{if(ce[_e].sim===0)return;let Pt=ae(_e);Ee.set(Pt,[...Ee.get(Pt)??[],_e])});for(let U of Ee.values()){if(U.length<2)continue;U.sort((_t,Ir)=>y[_t].msg.index-y[Ir].msg.index);let _e=U.slice(1),Pt=_e.reduce((_t,Ir)=>_t+Math.round(Math.min(y[Ir].tokens,ce[Ir].partnerTokens)*ce[Ir].sim*.9),0),Rr=U.map(_t=>ce[_t].sim),Ts=Math.round(Math.min(...Rr)*100),gn=Math.round(Math.max(...Rr)*100),yt=U.map(_t=>y[_t].msg.index),Ip=Ts===gn?`~${gn}%`:`${Ts}-${gn}%`,Vx=_e.reduce((_t,Ir)=>_t+y[Ir].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Pt,message:U.length===2?`Messages #${yt[0]} and #${yt[1]} are ${Ip} similar (~${Math.min(y[U[0]].tokens,y[U[1]].tokens)} tokens repeated with different framing).`:`${U.length} messages are ${Ip} similar to each other (${yt.slice(0,6).map(_t=>`#${_t}`).join(", ")}${yt.length>6?", \u2026":""}): ~${A(Vx)} tokens in the ${_e.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:yt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=ev(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let d=y=>o.find(x=>x.msg.index>y&&x.msg.kind==="tool_result")?.msg;for(let[,y]of u){if(y.length<2)continue;let x=y.slice(1).filter((C,R)=>d(y[R])?.isError===!0).length,$=y.length-1-x;x>0&&a.push({id:"retried_tool_call",severity:x>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${x} time(s) after it failed (messages #${y.join(", #")}).`,suggestion:x>=3?"Three or more identical retries of a failing command is a loop. Each attempt keeps its error output in context; the answer is in the first error, not in the fourth attempt.":"A retry after a failure is normal once. The failed attempt's output stays in context though, so once the fix is understood the earlier error can go.",messages:y}),$>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${$} time(s) after it had already succeeded (messages #${y.join(", #")}).`,suggestion:"Repeating a call that already succeeded means the earlier result scrolled out of the model's attention \u2014 keep results in a compact recap instead of re-calling.",messages:y})}{let y=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of nC(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let C=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),R=Math.round(C*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:R>4e3?"high":"warn",estSavings:R,message:`${x.split("/").pop()} was read ${$.length} times (messages #${$.join(", #")}), keeping ${$.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:$})}}for(let y of o)y.msg.kind!=="tool_result"||y.tokens<500||!/Traceback \(most recent call last\)|command not found|npm error|ERR!|\bexit code [1-9]|Exception in thread|FAILED|error TS\d+/i.test(y.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(y.tokens*.85),message:`Message #${y.msg.index} holds ~${y.tokens} tokens of failed tool output (errors, stack trace or non-zero exit).`,suggestion:"Keep the one line that identifies the failure and drop the rest \u2014 a full trace has no value once the fix is understood.",messages:[y.msg.index]});for(let y of o)ro(y.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(y.tokens*.9),message:`Message #${y.msg.index} contains a base64/binary blob (~${y.tokens} tokens of mostly meaningless characters).`,suggestion:"Never put base64 in text content \u2014 use the provider's file/image APIs or replace with a file reference.",messages:[y.msg.index]});let l=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(l>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,C)=>$+C.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${l} turns; the older half holds ~${x} tokens.`,suggestion:"Summarize the older half of the conversation into a compact recap and drop the raw turns (context-doctor optimize --strategy prune-history).",messages:[]})}s>0&&i.system/s>.25&&i.system>2e3&&a.push({id:"large_system_prompt",severity:"info",estSavings:0,message:`System prompt is ~${i.system} tokens (${Math.round(i.system/s*100)}% of the context).`,suggestion:"A big system prompt is fine IF it is stable \u2014 put it first and use prompt caching (Anthropic: cache_control; OpenAI: automatic prefix caching) so you stop paying full price for it every call.",messages:[]}),(mn(e)==="anthropic"||mn(e)==="openai")&&a.push({id:"cache_ordering",severity:"info",estSavings:0,message:"Prompt caching only matches a byte-identical prefix.",suggestion:"Keep stable content (system prompt, tool definitions, reference docs) at the start and never interleave it with per-request content \u2014 a single changed byte early in the prompt invalidates the cache for everything after it.",messages:[]});let p=wa(e),m=p?s/p*100:void 0;m!==void 0&&m>70&&a.push({id:"near_window_limit",severity:m>90?"high":"warn",estSavings:0,message:`Context is at ~${m.toFixed(0)}% of ${e}'s window.`,suggestion:"Models degrade well before the hard limit (lost-in-the-middle). Compact now rather than when the request fails.",messages:[]});let f=o.map(y=>({index:y.msg.index,role:y.msg.role,kind:y.msg.kind,tokens:y.tokens,preview:YI(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),h={high:0,warn:1,info:2};a.sort((y,x)=>h[y.severity]-h[x.severity]||x.estSavings-y.estSavings);let g=XI(a,s),_=to(e),v;if(_){let y=Tr(s,_),x=Tr(g,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:Wf(s),ttftSavedSeconds:Wf(g)}}return{totalTokens:s,model:e,contextWindow:p,usagePct:m,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:g,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as oC}from"node:crypto";var iv=10,Ea={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:iv};function sC(t){if(t?.name==="Write"&&typeof t.input?.file_path=="string")return t.input.file_path;let e=t?.name==="Bash"?String(t.input?.command??""):"",r=/(?:cat|tee)\s*>+\s*([^\s<]+)\s*<</.exec(e);return r?r[1]:null}function iC(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function ov(t,e,r){let n=Math.round(e*ka("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
|
|
66
|
+
[context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function Yf(t,e,r=iv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function aC(t){return oC("sha1").update(t.trim()).digest("hex")}function no(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?e.text??"":e?.type==="tool_result"?no(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
|
|
67
|
+
`):JSON.stringify(t)}function Qf(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(l=>l?.type==="text"&&typeof l.text=="string");if(a.length===0)return s;let c=a.map(l=>l.text).join(`
|
|
68
|
+
`),u=e(c,i);if(u===c)return s;let d=!1;return s.map(l=>l?.type==="text"&&typeof l.text=="string"?d?null:(d=!0,{...l,text:u}):l).filter(l=>l!==null)};return typeof r=="string"?e(r,n):Array.isArray(r)?n==="tool_result"?o(r,n):r.map(s=>{if(s?.type==="text"&&typeof s.text=="string"){let i=e(s.text,"text");return i===s.text?s:{...s,text:i}}if(s?.type==="tool_result"){if(typeof s.content=="string"){let i=e(s.content,"tool_result");return i===s.content?s:{...s,content:i}}if(Array.isArray(s.content)){let i=o(s.content,"tool_result");return i===s.content?s:{...s,content:i}}}return s}):r}function ep(t){return typeof t=="string"?ro(t)?Gf(t):t:Array.isArray(t)?t.map(ep):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,ep(r)])):t}function cC(t,e,r){let n=Math.round(e*ka(t,r));if(t.length<=n)return t;let o=t.slice(0,n),s=t.length-n;return`${o}
|
|
69
|
+
\u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function uC(t){let e=new Set;for(let r of t)if(Array.isArray(r?.content))for(let n of r.content)n?.type==="tool_use"&&n.id&&e.add(n.id);for(let r of t){if(!Array.isArray(r?.content))continue;let n=r.content.filter(o=>o?.type!=="tool_result"||o.tool_use_id&&e.has(o.tool_use_id));n.length!==r.content.length&&(r.content=n.length>0?n:[{type:"text",text:"[context-doctor: earlier tool result dropped with the pruned history]"}])}}function sv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function av(t,e={}){let r={strategies:e.strategies??Ea.strategies,keepRecent:e.keepRecent??Ea.keepRecent,maxToolResultTokens:e.maxToolResultTokens??Ea.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):Ea.trimBoundaryStep},n;try{n=JSON.parse(t)}catch{throw new Error("optimize requires a JSON conversation (message array, or object with a `messages` field)")}let o=Array.isArray(n)?n:n?.messages;if(!Array.isArray(o))throw Array.isArray(n?.contents)||typeof n?.input=="string"||Array.isArray(n?.input)?new Error(`optimize rewrites a \`messages\` array (Anthropic or OpenAI chat); this is ${Array.isArray(n?.contents)?"a Gemini `contents`":"an OpenAI Responses `input`"} request. Profile it with analyze (or profile_context); the autopilot proxy slims these requests live.`):new Error("No `messages` array found in input");for(let g=o.length-1;g>=0;g--)(!o[g]||typeof o[g]!="object")&&o.splice(g,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(g=>Array.isArray(g?.content)&&g.content.some(_=>_?.type==="tool_use"||_?.type==="tool_result")),i=e.model??(!Array.isArray(n)&&typeof n?.model=="string"?n.model:void 0)??(s?"claude":void 0),a=g=>zt(g,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:no(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=g=>{let _=a(no(g.content));for(let v of Array.isArray(g.tool_calls)?g.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return g.function_call&&(_+=a(`${g.function_call.name??""} ${g.function_call.arguments??""}`)),_},d=c+o.reduce((g,_)=>g+u(_),0),l=[];if(r.strategies.includes("strip-base64")&&o.forEach((g,_)=>{let v=no(g.content);if(!ro(v))return;let y=a(v),x=Qf(g,C=>ro(C)?Gf(C):C);Array.isArray(x)&&(x=x.map(C=>C?.type==="tool_use"&&C.input!=null?{...C,input:ep(C.input)}:C));let $=y-a(no(x));$>50&&(g.content=x,l.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let g=Yf(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,C=Qf(v,R=>{if(R.length<300)return R;let ae=aC(R),ce=_.get(ae);if(ce===void 0)return _.set(ae,y),R;if(y>=g)return R;let Ee=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(R)-a(Ee),$??=ce,Ee});x<=0||(v.content=C,l.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let g=Yf(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=g||!sv(_))return;let y=0,x=Qf(_,($,C)=>{if(C!=="tool_result")return $;let R=a($);if(R<=r.maxToolResultTokens)return $;let ae=cC($,r.maxToolResultTokens,i),ce=a(ae);return ce>=R?$:(y+=R-ce,ae)});y<=0||(_.content=x,l.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:y,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let g=Yf(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=g)return;let y=0;if(Array.isArray(_.content))for(let x of _.content){if(x?.type!=="tool_use"||x.input==null||typeof x.input!="object"||iC(o,v,sC(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let C=ov(x.input,r.maxToolResultTokens,i),R=a(JSON.stringify(C));R>=$||(x.input=C,y+=$-R)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let C=a($);if(C<=r.maxToolResultTokens)continue;let R;try{R=JSON.parse($)}catch{continue}if(!R||typeof R!="object"||Array.isArray(R))continue;let ae=JSON.stringify(ov(R,r.maxToolResultTokens,i)),ce=a(ae);ce>=C||(x.function.arguments=ae,y+=C-ce)}y>0&&l.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:y,note:"Arguments of a completed tool call truncated"})})}let p,m=0;for(;m<o.length&&(o[m]?.role==="system"||o[m]?.role==="developer");)m++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-m>f*2){let g=o.length-f;for(;g<o.length&&sv(o[g]);)g++;if(o.length-g>=2){uC(o.slice(g));let _=o.slice(m,g),v=_.reduce((x,$)=>x+u($),0);p=_.map((x,$)=>`[${m+$}:${x.role}] ${no(x.content).replace(/\s+/g," ").slice(0,200)}`).join(`
|
|
70
|
+
`);let y={role:"user",content:`[context-doctor: ${_.length} earlier messages (~${v} tokens) pruned. Replace this stub with an LLM-written summary of those turns for best results.]`};o.splice(m,g-m,y),l.push({strategy:"prune-history",messageIndex:m,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let h=c+o.reduce((g,_)=>g+u(_),0);return{conversation:n,tokensBefore:d,tokensAfter:h,applied:l,prunedDigest:p}}var cv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},lC={high:"\u2716",warn:"\u25B2",info:"\u2139"};function dC(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function fC(t){return t.replace(/(?:[A-Za-z]:)?(?:~|\.{1,2})?(?:[\\/][\w.@+-]+)+|[\w.@~+-]+(?:[\\/][\w.@+-]+)+/g,"[path]").replace(/(?<![\w.@+-])[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]{0,9}(?![\w@+-]|\.\w)/g,"[file]")}function uv(t,e={}){let r=[],n=t;if(r.push("CONTEXT DOCTOR \u2014 profile"),r.push("\u2550".repeat(56)),n.parseWarning&&(r.push(`\u26A0 ${n.parseWarning}${n.sourceFormat==="text"&&n.messageCount>0?" Profiled as raw text below, which is almost certainly not what you want.":""}`),r.push("")),r.push(`Total: ~${A(n.totalTokens)} tokens across ${n.messageCount} messages (${n.sourceFormat} format)`),n.calibration){let i=Math.round((n.calibration.factor-1)*100);r.push(` estimates calibrated ${i>=0?"+":""}${i}% from ${n.calibration.samples} exact count(s) you ran on this machine (analyze --exact)`)}if(n.model){let i=n.contextWindow?` of ${A(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${qt(n.cost.perCallUsd)} input per call \xB7 ~${qt(n.cost.per1kCallsUsd)} per 1k calls \xB7 ~${n.cost.ttftSeconds.toFixed(1)}s of latency per call (estimates)`),r.push(""),r.push("Where the tokens go"),r.push("\u2500".repeat(56));let o=Object.entries(n.categories).filter(([,i])=>i>0).sort((i,a)=>a[1]-i[1]),s=Math.max(...o.map(([i])=>cv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${cv[i].padEnd(s)} ${dC(c)} ${String(Math.round(c*100)).padStart(3)}% ~${A(a)}`)}r.push(""),r.push("Largest messages"),r.push("\u2500".repeat(56));for(let i of n.largestMessages){let a=i.toolName?`${i.kind}:${i.toolName}`:i.kind,c=e.redact?"[redacted]":i.preview;r.push(` #${i.index} [${a}] ~${A(i.tokens)} ${c}`)}if(r.push(""),n.findings.length>0){r.push(`Findings (${n.findings.length})`),r.push("\u2500".repeat(56));let i=3,a=new Map,c=new Map;for(let u of n.findings){let d=a.get(u.id)??0;if(d>=i){let m=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:m.count+1,savings:m.savings+u.estSavings});continue}a.set(u.id,d+1);let l=u.estSavings>0?` [save ~${A(u.estSavings)}]`:"";r.push(`${lC[u.severity]} ${e.redact?fC(u.message):u.message}${l}`),r.push(` \u2192 ${u.suggestion}`);let p=c.get(u.id);d+1===i&&p===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,d]of c){if(d.count===0)continue;let l=Math.min(d.savings,n.totalEstSavings),p=l>0?`, up to ~${A(l)} more recoverable`:"";r.push(` \u2026 and ${d.count} more of the same kind (${u})${p}. Use --json for the full list.`)}if(r.push(""),n.totalEstSavings>0){let u=n.totalTokens>0?Math.round(n.totalEstSavings/n.totalTokens*100):0,d=`Potential recovery: ~${A(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(d+=` \u2248 ${qt(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(d),r.push("Run `context-doctor optimize <file>` to apply the safe fixes automatically.")}}else r.push("No issues found \u2014 this context is in good shape.");return r.join(`
|
|
71
|
+
`)}var pC=2060,mC={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},hC=6.3,gC={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},yC=1500,lv=2e3,_C=30,tp=400,vC=1e4,xC=6;function bC(t,e){let r=$a[mn(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function wC(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):yC;if(t.approx_tokens&&t.approx_tokens>0)return Math.round(t.approx_tokens);let r=t.approx_chars&&t.approx_chars>0?t.approx_chars:t.approx_lines&&t.approx_lines>0?t.approx_lines*mC[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*hC:gC[t.kind];return Math.round(r/bC(t.kind,e))}function rp(t){return Math.round(pC/$a[mn(t)].prose)}var dv=60;function $C(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>dv?e.slice(0,dv-1)+"\u2026":e}function kC(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:$C(_?.label)})),n=rp(t.model),o=e*n,s=r.map(_=>({block:_,tokens:wC(_,t.model),copies:Math.max(1,Math.floor(_.repeated??1))})),i=s.reduce((_,v)=>_+v.tokens*v.copies,0),a=o+i,c=[];for(let{block:_,tokens:v,copies:y}of s){if(y>1&&c.push({id:"duplicate_block",severity:"warn",estSavings:v*(y-1),message:`"${_.label}" appears ${y} times (~${A(v)} each).`,action:`Refer to "${_.label}" by name from now on; never re-quote it.`}),_.kind==="base64"){c.push({id:"base64_blob",severity:"high",estSavings:Math.max(0,v-50),message:`"${_.label}" is inline base64 (~${A(v)}), which the model cannot read anyway.`,action:`Drop it: describe "${_.label}" in one line and ask the user to attach it as a file if needed.`});continue}if(_.kind!=="image"&&v>=lv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*lv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${A(v)}${_.stale?" and already acted on":""}.`,action:_.stale?`Replace "${_.label}" with a one-line note of what it was and what came of it.`:`Summarize "${_.label}" into the points still needed (facts, identifiers, decisions) and work from the summary.`})}}let u=s.filter(_=>_.block.kind==="image");if(u.length>=3){let _=u.reduce((v,y)=>v+y.tokens*y.copies,0);c.push({id:"many_images",severity:"info",estSavings:0,message:`${u.length} images (~${A(_)}) ride along on every turn.`,action:"Once an image has been read, describe what it showed in a sentence so it need not be looked at again; new chats should get only the images still needed."})}if(e>=_C){let _=xC*n+tp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${A(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${tp}-token brief (goal, decisions, current state, open items, key identifiers) and call save_handoff, or the user picks the \`handoff\` prompt. A new chat re-reads ~${A(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let d=wa(t.model),l=d?Math.round(a/d*100):void 0;l!==void 0&&l>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${l}% of the ${A(d)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let p={high:0,warn:1,info:2};c.sort((_,v)=>p[_.severity]-p[v.severity]||v.estSavings-_.estSavings);let m=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),h=Math.min(a,Math.max(m,f)),g=to(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:d,usagePct:l,findings:c,totalEstSavings:h,perTurnUsd:g?Tr(a,g):void 0,perTurnCachedUsd:g?a/1e6*g.cacheReadPerM:void 0}}function fv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${A(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${A(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${A(t.baselineTokens)} plain conversation + ${A(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${qt(t.perTurnUsd)} at list price, ${qt(t.perTurnCachedUsd)} when cached. On a subscription this is what spends the usage limit.`):e.push(" Re-read on every turn. On a subscription this is what spends the usage limit."),t.findings.length===0?(e.push("No findings: nothing large, repeated, or stale in the sketch. Keep going."),e.join(`
|
|
72
|
+
`)):(e.push(""),e.push(`Findings (recoverable ~${A(t.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`),t.findings.forEach((o,s)=>{let i=o.estSavings>0?` [~${A(o.estSavings)}]`:"";e.push(`${s+1}. ${o.severity.toUpperCase()}${i} ${o.message}`),e.push(` \u2192 ${o.action}`)}),e.push(""),e.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat."),!t.findings.some(o=>o.id==="long_history")&&t.totalEstSavings>=vC&&e.push(`To recover the ~${A(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${tp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
|
|
73
|
+
`))}function pv(t,{record:e=!0}={}){let r=kC(t);return e&&Ta({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as Ov}from"node:child_process";import{existsSync as Av,lstatSync as LC,readdirSync as qC,readFileSync as FC,realpathSync as up,statSync as UC}from"node:fs";import{homedir as HC}from"node:os";import{basename as lp,extname as Aa,isAbsolute as BC,join as oo,relative as Nv,resolve as VC,sep as JC}from"node:path";import{execFile as SC,spawnSync as mv}from"node:child_process";import{existsSync as hv,mkdtempSync as gv,readFileSync as op,rmSync as yv}from"node:fs";import{tmpdir as _v}from"node:os";import{dirname as vv,extname as xv,join as za}from"node:path";var Pa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),bv={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function _s(t,e){try{let r=mv(t,e,bv);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var wv=["-convert","txt","-noload","-nostore","-stdout"],$v='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function TC(t){let e=_s("pdftotext",["-enc","UTF-8",t,"-"])??_s("pdftotext",[t,"-"]);if(e)return e;let r=za(gv(za(_v(),"cd-pdf-")),"out.txt");try{mv("pdftotext",[t,r],bv);let n=hv(r)?op(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{yv(vv(r),{recursive:!0,force:!0})}}function EC(t,e){let r=_s("unzip",["-p",t,...e]);return r?kv(r):void 0}function kv(t){return t.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
|
|
74
74
|
|
|
75
75
|
`).replace(/<(w:tab|w:br)\/>/g," ").replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&").replace(/\n{3,}/g,`
|
|
76
76
|
|
|
77
|
-
`).trim()}function
|
|
77
|
+
`).trim()}function Sv(t){let e=xv(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=TC(t)?.replace(/\f/g,`
|
|
78
78
|
|
|
79
|
-
`),!n&&r&&(n=
|
|
79
|
+
`),!n&&r&&(n=_s("osascript",["-l","JavaScript","-e",$v,t])),!n)return{error:r?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(r&&e!==".pptx"&&(n=_s("textutil",[...wv,t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=EC(t,o))}if(!n)return{error:r?"unreadable document":`needs unzip${e===".doc"||e===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:n}}var vs=2e4;function np(t,e,r){let n=r-Date.now();return n<=0?Promise.resolve({timedOut:!0}):new Promise(o=>{let s=!1,i=u=>{s||(s=!0,clearTimeout(c),o(u))},a,c=setTimeout(()=>{a?.kill("SIGKILL"),i({timedOut:!0})},n);try{a=SC(t,e,{encoding:"utf8",timeout:n,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(u,d)=>{if(u)return i({timedOut:!!u.killed||Date.now()>=r});i({out:typeof d=="string"&&d.trim()?d:void 0,timedOut:!1})}),a.on("error",()=>i({timedOut:!1}))}catch{i({timedOut:!1})}})}async function Ra(t,e=Date.now()+vs){let r=xv(t).toLowerCase(),n=process.platform==="darwin",o,s=!1,i=async(c,u)=>{if(o||s)return;let d=await np(c,u,e);d.timedOut?s=!0:o=d.out},a=()=>({error:"not read: the time allowed for reading documents in this call ran out"});if(r===".pdf"){if(await i("pdftotext",["-enc","UTF-8",t,"-"]),await i("pdftotext",[t,"-"]),!o&&!s){let c=za(gv(za(_v(),"cd-pdf-")),"out.txt");try{(await np("pdftotext",[t,c],e)).timedOut?s=!0:hv(c)&&(o=op(c,"utf8").trim()?op(c,"utf8"):void 0)}finally{yv(vv(c),{recursive:!0,force:!0})}}return o=o?.replace(/\f/g,`
|
|
80
|
+
|
|
81
|
+
`),!o&&n&&await i("osascript",["-l","JavaScript","-e",$v,t]),o?{text:o}:s?a():{error:n?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}if(n&&r!==".pptx"&&await i("textutil",[...wv,t]),!o&&!s){let c=r===".docx"?["word/document.xml"]:r===".pptx"?["ppt/slides/*.xml"]:r===".odt"?["content.xml"]:[];if(c.length){let u=await np("unzip",["-p",t,...c],e);u.timedOut?s=!0:u.out&&(o=kv(u.out))}}return o?{text:o}:s?a():{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}var KC=4e3,WC=400,GC="claude",XC=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".h",".cc",".cpp",".hpp",".cs",".php",".scala",".sh",".bash",".zsh",".sql",".lua",".dart",".vue",".svelte"]),YC=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function QC(t,e){let r=Aa(t).toLowerCase();return YC.has(r)?"markdown":XC.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var eO=/^(?![\s})\]]|$)/,Cv=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function tO(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,d)=>{u>s&&t.slice(s,u).some(l=>l.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=d};for(let u=0;u<t.length;u++){let d=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(d)&&(a=!a);let l=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(d);if(l){c(u,!0);let p=l[1].length;n.length=p-1,n[p-1]=l[2],o=n.filter(Boolean).join(" > ");continue}!a&&!d.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&d.trim()&&eO.test(d)&&c(u,!1):!d.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}if(c(t.length,!1),e!=="markdown")for(let u of r){let d=t.slice(u.start,u.end).map(m=>m.trim()).filter(Boolean),l=d.map(m=>m.replace(Cv,"").trim()).find(Boolean),p=e==="code"&&(d.find(m=>!Cv.test(m))||l)||d[0]||"";u.heading=p.slice(0,80)}return r}var rO=t=>t>=55296&&t<=56319,nO=t=>t>=56320&&t<=57343;function oO(t,e={}){let r=Math.max(50,e.maxChunkTokens??WC),n=e.model??GC,o=QC(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
|
|
80
82
|
`).split(`
|
|
81
|
-
`).forEach((p,m)=>{for(;p.length>a;){let f=p.lastIndexOf(" ",a),h=f>a/2?f+1:a;
|
|
82
|
-
`,n));let u=(p,m)=>c[m]-c[p],
|
|
83
|
-
`);return{id:`${t.name}#${m+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[h-1]??h,heading:p.heading,text:
|
|
84
|
-
`);r.push(`PACKED ~${
|
|
85
|
-
`)}if(t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...
|
|
86
|
-
`);for(let a of t.selected)r.push("",`\u2500\u2500 ${a.id} \xB7 L${a.startLine}-${a.endLine}${a.heading?` \xB7 ${a.heading}`:""} \xB7 ~${
|
|
87
|
-
`)}var
|
|
88
|
-
1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering;
|
|
89
|
-
2.
|
|
90
|
-
3.
|
|
91
|
-
4.
|
|
92
|
-
5.
|
|
93
|
-
|
|
94
|
-
`),
|
|
83
|
+
`).forEach((p,m)=>{for(;p.length>a;){let f=p.lastIndexOf(" ",a),h=f>a/2?f+1:a;rO(p.charCodeAt(h-1))&&nO(p.charCodeAt(h))&&h--,s.push(p.slice(0,h)),i.push(m+1),p=p.slice(h)}s.push(p),i.push(m+1)});let c=[0];for(let p of s)c.push(c[c.length-1]+zt(p+`
|
|
84
|
+
`,n));let u=(p,m)=>c[m]-c[p],d=[];for(let p of tO(s,o)){if(u(p.start,p.end)<=r){d.push(p);continue}let m=p.start;for(let f=p.start+1;f<=p.end;f++)if(f===p.end||u(m,f+1)>r){let h=m===p.start;d.push({start:m,end:f,heading:h?p.heading:`${p.heading} (cont.)`,hard:h&&p.hard}),m=f}}let l=[];for(let p of d){let m=l[l.length-1];m&&!p.hard&&m.heading===p.heading&&u(m.start,p.end)<=r||m&&!p.hard&&o!=="markdown"&&u(m.start,p.end)<=r?m.end=p.end:l.push({...p})}return l.map((p,m)=>{let f=p.start,h=p.end;for(;f<h&&!s[f].trim();)f++;for(;h>f&&!s[h-1].trim();)h--;let g=s.slice(f,h).join(`
|
|
85
|
+
`);return{id:`${t.name}#${m+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[h-1]??h,heading:p.heading,text:g,tokens:zt(g,n),score:0}})}var sO=new Set("a an and are as at be but by can do does for from has have how i if in into is it its of on or our so that the their them then there these they this to was we were what when where which who why will with you your about should would could not no yes all any my me get set use using used".split(" "));function Ca(t){let e=[],r=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u);for(let n of r)n.length<2||sO.has(n)||(n.length>4&&n.endsWith("ies")?n=n.slice(0,-3)+"y":n.length>3&&n.endsWith("s")&&!n.endsWith("ss")&&(n=n.slice(0,-1)),e.push(n));return e}function iO(t,e){let r=[...new Set(Ca(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...Ca(i.text),...Ca(i.heading),...Ca(i.heading)],c=new Map;for(let u of a)c.set(u,(c.get(u)??0)+1);return{len:a.length,tf:c}}),o=n.reduce((i,a)=>i+a.len,0)/n.length||1,s=n.length;for(let i of r){let a=n.filter(u=>u.tf.has(i)).length;if(a===0)continue;let c=Math.log(1+(s-a+.5)/(a+.5));n.forEach((u,d)=>{let l=u.tf.get(i)??0;l&&(t[d].score+=c*(l*2.2/(l+1.2*(1-.75+.75*u.len/o))))})}}async function Mv(t,e={}){let r=t.map(s=>oO(s,e)),n=e.query?.trim()||void 0,o;if(n&&(iO(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(Iv(),Rv));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...aO(t,r,n,e),semanticNote:o}}function aO(t,e,r,n){let o=Math.max(1,n.budget??KC),s=e.flat(),i=[],a=[],c=[],u=0,d=(m,f)=>{if(!i.includes(m)){if(u+m.tokens>o){c.some(h=>h.id===m.id)||c.push({id:m.id,tokens:m.tokens,requested:f});return}i.push(m),u+=m.tokens}},l="outline";if(n.ids?.length){l="ids";let m=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let h=m.get(f);h?d(h,!0):a.push(f)}}if(r){l==="outline"&&(l="query");for(let m of[...s].filter(f=>f.score>0).sort((f,h)=>h.score-f.score))d(m,!1)}let p=new Map(s.map((m,f)=>[m,f]));return i.sort((m,f)=>p.get(m)-p.get(f)),{mode:l,query:r,budget:o,totalTokens:s.reduce((m,f)=>m+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((m,f)=>({name:m.name,tokens:e[f].reduce((h,g)=>h+g.tokens,0),chunks:e[f].length,selected:e[f].filter(h=>i.includes(h)).length}))}}function ap(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${A(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function jv(t,{outlineLimit:e=60}={}){let r=[],n=t.totalTokens>0?Math.round(t.packedTokens/t.totalTokens*100):0,o=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`;if(t.mode==="outline")return r.push(`OUTLINE of ${o}: ~${A(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...ap(t.chunks,e)),r.join(`
|
|
86
|
+
`);r.push(`PACKED ~${A(t.packedTokens)} of ~${A(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${A(t.budget)}.`),t.missingIds.length&&r.push(`Unknown ids: ${t.missingIds.join(", ")}.`),t.semanticNote&&r.push(`(${t.semanticNote})`);let s=(t.unfit??[]).filter(a=>a.requested);if(t.selected.length>0&&s.length>0&&r.push(`Did not fit the budget of ${A(t.budget)}: ${s.map(a=>`${a.id} (~${A(a.tokens)})`).join(", ")}. Ask for it alone or with a larger budget (--max-tokens; MCP max_tokens).`),t.selected.length===0&&(t.unfit??[]).length>0){let a=t.unfit[0],c=t.chunks.find(u=>u.id===a.id);return r.push(`Nothing fit the budget of ${A(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${A(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...ap(t.chunks,e)),r.join(`
|
|
87
|
+
`)}if(t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...ap(t.chunks,e)),r.join(`
|
|
88
|
+
`);for(let a of t.selected)r.push("",`\u2500\u2500 ${a.id} \xB7 L${a.startLine}-${a.endLine}${a.heading?` \xB7 ${a.heading}`:""} \xB7 ~${A(a.tokens)}`,a.text);let i=t.chunks.length-t.selected.length;if(i>0){let a=t.chunks.filter(c=>c.score>0&&!t.selected.includes(c)).sort((c,u)=>u.score-c.score).slice(0,5);r.push("",`Not included: ${i} chunk(s). `+(a.length?`Next best: ${a.map(c=>`${c.id} (${c.heading||`L${c.startLine}`})`).join("; ")}.`:"Ask for the outline to see them."))}return r.join(`
|
|
89
|
+
`)}var cO=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Oa={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function uO(t){try{let e=Ov("git",["-C",t,"ls-files","-z","--cached","--others","--exclude-standard"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status!==0||typeof e.stdout!="string"?void 0:e.stdout.split("\0").filter(r=>r&&Av(oo(t,r))).sort()}catch{return}}function lO(t){let e=Ov("git",["-C",t,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status===0&&typeof e.stdout=="string"&&e.stdout.length>0}function Zv(t,e){let r=Nv(t,e);return r===""||r!==".."&&!r.startsWith(".."+JC)&&!BC(r)}var dO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd"]),fO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function pO(t){let e=lp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(dO.has(r))return`a credentials file (${e})`;if(/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(r)||/^id_(rsa|dsa|ecdsa|ed25519)/.test(r)&&!r.endsWith(".pub"))return"a private SSH key";if(fO.has(Aa(r)))return`a key or certificate store (${Aa(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials"}function mO(){let t=HC(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",oo(".config","gcloud"),oo("Library","Keychains"),".password-store"].map(n=>oo(t,n)),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"],r=e.map(n=>{try{return up(n)}catch{return n}});return[...new Set([...e,...r])]}function hO(t,e){return e.find(r=>Zv(r,t))}function cp(t){let e=t?.code;return e==="ENOENT"?"not found":e==="EACCES"||e==="EPERM"?"permission denied":e==="ENOTDIR"?"not a directory":e==="EISDIR"?"is a directory":e==="ELOOP"?"too many symlinks":e?`unreadable (${e})`:`unreadable (${t?.message??t})`}function gO(t,e=process.cwd()){let r=typeof e=="string"?{cwd:e}:e,n=r.cwd??process.cwd(),o=r.includeSecrets===!0,s=r.secretsHint??"",i=o?[]:mO(),a=[],c=[],u=0,d=new Set,l="",p=0,m=!1,f=g=>{try{return up(g)}catch{return VC(g)}},h=(g,_)=>{if(a.length>=Oa.files){(_||c.length<20)&&c.push(`${g}: over ${Oa.files} files`);return}let v;try{v=_?UC(g):LC(g)}catch(R){c.push(`${g}: ${cp(R)}`);return}if(v.isSymbolicLink()){let R;try{R=up(g)}catch{return}Zv(l,R)||c.push(`${g}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let R=hO(f(g),i);if(R){_&&c.push(`${g}: refused, ${R} holds credentials${s}`);return}}if(v.isDirectory()){let R=lp(g);if(!_&&cO.has(R))return;if(!_&&R.startsWith(".")){p++;return}let ae=_?uO(g):void 0;if(_&&(m=ae!==void 0),ae){ae.length===0&&lO(g)&&c.push(`${g}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Ee of ae)h(oo(g,Ee),!1);return}let ce;try{ce=qC(g).sort()}catch(Ee){c.push(`${g}: ${cp(Ee)}`);return}for(let Ee of ce)h(oo(g,Ee),!1);return}if(!v.isFile()){_&&c.push(`${g}: not a regular file`);return}if(!o){let R=pO(g);if(R){c.push(`${g}: ${R}, likely holding secrets; not packed${s}`);return}}if(!_&&lp(g).startsWith(".")&&!m){p++;return}let y=f(g);if(d.has(y))return;if(v.size>Oa.fileBytes||u+v.size>Oa.totalBytes){c.push(`${g}: too large (${Math.round(v.size/1024)} KB)`);return}let x=Nv(n,g),$=x&&!x.startsWith("..")?x:g;if(Pa.has(Aa(g).toLowerCase())){if(r.defer){u+=v.size,d.add(y),a.push({name:$,text:""}),r.defer.push({slot:a.length-1,path:g});return}let R=Sv(g);"error"in R?c.push(`${g}: ${R.error}`):(u+=v.size,d.add(y),a.push({name:$,text:R.text}));return}let C;try{C=FC(g)}catch(R){c.push(`${g}: ${cp(R)}`);return}if(C.subarray(0,8e3).includes(0)){_&&c.push(`${g}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}u+=v.size,d.add(y),a.push({name:$,text:C.toString("utf8")})};for(let g of t){if(!Av(g)){c.push(`${g}: not found`);continue}l=f(g),p=0,m=!1,h(g,!0),p>0&&c.push(`${g}: ${p} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:a,skipped:c}}async function Dv(t,e={}){let r=[],{sources:n,skipped:o}=gO(t,{...e,defer:r}),s=Date.now()+(e.budgetMs??vs),i=new Set;for(let a of r){let c=await Ra(a.path,s);"error"in c?(o.push(`${a.path}: ${c.error}`),i.add(a.slot)):n[a.slot].text=c.text}return{sources:n.filter((a,c)=>!i.has(c)),skipped:o}}var Lv=`Context hygiene rules (always on):
|
|
90
|
+
1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a \`sketch\`. Act on its top finding. Do not estimate token counts yourself.
|
|
91
|
+
2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
|
|
92
|
+
3. Summarize any paste or tool result over ~2k tokens into the points you need.
|
|
93
|
+
4. Refer to earlier content by name; never re-quote it or inline base64.
|
|
94
|
+
5. For a big file you won't edit, call pack_context with the question; don't read it whole.
|
|
95
|
+
6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var yO=["openai/session","openai/subject"];function qv(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&yO.some(n=>typeof t[n]=="string")?"compact":"full"}var so=t=>Math.round(t);function Fv(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${A(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${A(t.totalEstSavings)} recoverable (${n}%).`];t.parseWarning&&o.unshift(`\u26A0 ${t.parseWarning}`),o.push(r?"Act on #1 (first in structuredContent.findings).":"No findings.");let s=Object.fromEntries(Object.entries(t.categories).filter(([,a])=>a>0).sort((a,c)=>c[1]-a[1]).map(([a,c])=>[a,so(c)])),i={total_tokens:so(t.totalTokens),messages:t.messageCount,recoverable_tokens:so(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${A(a.estSavings)}`:""}: ${a.message} \u2192 ${a.suggestion}`)};return t.findings.length>6&&(i.more_findings=t.findings.length-6),t.model&&(i.model=t.model),t.usagePct!==void 0&&(i.window_pct=Number(t.usagePct.toFixed(1))),t.cost&&(i.usd_per_call=Number(t.cost.perCallUsd.toFixed(4))),{text:o.join(`
|
|
96
|
+
`),structured:i,meta:{"context-doctor/report":e,"context-doctor/largest":t.largestMessages.map(a=>({index:a.index,kind:a.kind,tokens:so(a.tokens),preview:a.preview}))}}}function Uv(t,e){let[r,...n]=t.findings,o=[`~${A(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${A(t.totalEstSavings)} recoverable, only in a new chat.`];r?(o.push(`Act on #1 now: ${r.message} \u2192 ${r.action}`),o.push("This chat's history cannot be edited: what is already here comes back only in a new chat (save_handoff).")):o.push("No findings. Keep going.");let s={total_tokens:t.totalTokens,recoverable_tokens:t.totalEstSavings,recoverable_by:"a new chat (handoff)"};return n.length&&(s.other_findings=n.map(i=>`${i.severity}${i.estSavings>0?` ~${A(i.estSavings)}`:""}: ${i.message}`)),t.usagePct!==void 0&&(s.window_pct=t.usagePct),t.perTurnUsd!==void 0&&(s.usd_per_turn=Number(t.perTurnUsd.toFixed(4))),{text:o.join(`
|
|
97
|
+
`),structured:s,meta:{"context-doctor/report":e}}}function _O(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function vO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function Hv(t,e,r=120){let n=new Map;for(let l of t.chunks){let p=n.get(l.source)??[],m=vO(l.heading),f=p[p.length-1];f&&f.heading===m?(f.last=l.id,f.tokens+=l.tokens):p.push({first:l.id,last:l.id,heading:m,tokens:l.tokens}),n.set(l.source,p)}let o=r,s=0,i=[...n.entries()].map(([l,p])=>{let m=p.slice(0,Math.max(0,o));o-=m.length,s+=p.length-m.length;let f=p.reduce((h,g)=>h+g.tokens,0);return{name:l,tokens:so(f),sections:m.map(h=>`${_O(h.first,h.last)} ${h.heading} ~${A(h.tokens)}`)}}),a=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`,c=t.chunks[0]?.id??"name#1",u=`OUTLINE of ${a}: ~${A(t.totalTokens)} tokens in ${t.chunks.length} chunks, as sections in structuredContent. Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${c}).`,d={total_tokens:so(t.totalTokens),chunks:t.chunks.length,sources:i};return s>0&&(d.sections_not_shown=s),{text:u,structured:d,meta:{"context-doctor/outline":e}}}import{existsSync as xO,lstatSync as rr,mkdirSync as Jv,readdirSync as bO,readFileSync as dp,realpathSync as Na,rmSync as wO,writeFileSync as Bv}from"node:fs";import{homedir as io}from"node:os";import{isAbsolute as $O,join as nt,relative as kO,sep as SO}from"node:path";var gt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function pp(t=io()){return nt(t,".context-doctor","handoffs")}var TO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function Kv(t){return typeof t=="string"&&t.length<=80&&TO.test(t)}function EO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function zO(t){let e=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}-${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function mp(t){let e=[],r=gt;typeof t?.brief!="string"||!t.brief.trim()?e.push("`brief` is empty: write the handoff brief first."):t.brief.length>r.briefChars&&e.push(`\`brief\` is ${t.brief.length} characters; the limit is ${r.briefChars} (aim for \u2264${r.briefTargetTokens} tokens).`),t.title!==void 0&&(typeof t.title!="string"||t.title.length>r.titleChars)&&e.push(`\`title\` must be a string of at most ${r.titleChars} characters.`);let n=t.verbatim??[];if(!Array.isArray(n))e.push("`verbatim` must be a list of {label, text}.");else{n.length>r.blocks&&e.push(`${n.length} verbatim blocks; the limit is ${r.blocks}. Keep only what must stay exact.`);let o=typeof t.brief=="string"?t.brief.length:0;n.forEach((s,i)=>{(typeof s?.label!="string"||!s.label.trim()||s.label.length>r.labelChars)&&e.push(`verbatim[${i}].label must be 1-${r.labelChars} characters.`),typeof s?.text!="string"||!s.text.trim()?e.push(`verbatim[${i}].text is empty.`):s.text.length>r.blockChars?e.push(`verbatim[${i}] ("${String(s.label).slice(0,40)}") is ${s.text.length} characters; the limit is ${r.blockChars}. Summarize it, or keep only the exact lines needed.`):o+=s.text.length}),o>r.totalChars&&e.push(`The handoff is ${o} characters; the limit is ${r.totalChars}. A handoff that big is not a cut.`)}t.model!==void 0&&typeof t.model!="string"&&e.push("`model` must be a string.");for(let o of["chatTokens","turns"]){let s=t[o];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<0||s>1e8)&&e.push(`\`${o}\` must be a non-negative number.`)}return e}var bs="masked by context-doctor",qe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${bs}]`:void 0}),PO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),RO=[qe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),qe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),qe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,PO),qe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),qe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),qe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),qe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),qe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),qe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),qe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),qe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),qe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),qe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),qe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),qe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),qe("a JWT",/(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g),{kind:"a password in a URL",re:/\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]*):([^\s@/]+)@/gi,replace:t=>`${t[1]}${t[2]}:[${bs}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${bs}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${bs}]`}],IO="(?:password|passwd|passphrase|pwd|secret|secret[_-]?key|secret[_-]?access[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|authtoken|refresh[_-]?token|bearer[_-]?token|token|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|credentials?)",CO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${IO}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),OO=/^(?:string|str|number|int|integer|bool|boolean|any|null|nil|none|undefined|true|false|required|optional|empty|redacted|hidden|secret|password|\*+|x{3,}|\.{3,})$/i,AO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function NO(t){return!(OO.test(t)||AO.test(t)||/^(?:\/|~\/|\.{1,2}\/|[A-Za-z]:\\)/.test(t)||/^(?:process\.env|os\.environ|env\.|ENV\[|getenv)/i.test(t)||/^[A-Za-z_$][\w$]*(?:\.[\w$]+)+$/.test(t)&&!/[0-9]/.test(t)||/^\d{1,7}$/.test(t))}function ja(t){let e=0,r=new Set,n=String(t??"");for(let o of RO)n=n.replace(o.re,(...s)=>{let i=s.slice(0,-2).filter(c=>typeof c=="string"||c===void 0),a=o.replace(i);return a===void 0?i[0]:(e++,r.add(o.kind),a)});return n=n.replace(CO,(o,s,i)=>NO(i)?(e++,r.add("a password or secret assignment"),`${s}[${bs}]`):o),{text:n,count:e,kinds:[...r]}}function MO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function fp(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function jO(t,e,r,n){let o=[`# Handoff: ${t}`,"",`Continue from this handoff (written ${e.slice(0,16).replace("T"," ")} UTC, saved by context-doctor). It replaces the earlier chat; ask for anything it does not cover.`,"",r.trim()];if(n.length){o.push("","## Verbatim (keep exact)");for(let s of n){let i=MO(s.text);o.push("",`### ${fp(s.label,gt.labelChars)}`,"",i,s.text.replace(/\s+$/,""),i)}}return o.join(`
|
|
98
|
+
`)+`
|
|
99
|
+
`}function ZO(t,e){let r={after:t};e.chatTokens!==void 0&&e.chatTokens>0?(r.now=Math.round(e.chatTokens),r.nowSource="given"):e.turns!==void 0&&e.turns>0&&(r.now=Math.round(e.turns)*rp(e.model),r.nowSource="turns");let n=to(e.model);return n&&(r.afterUsd=Tr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=Tr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function Wv(t){let e=(o,s)=>o!==void 0?` (${qt(o)} at list price, ${qt(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${A(t.after)} tokens${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt. Pass chat_tokens (from profile_context) to see the per-turn saving.`;let r=t.nowSource==="turns"?" (estimated from the turn count)":"",n=Math.max(0,t.now-t.after);return[`Now: ~${A(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${A(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${A(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
|
|
100
|
+
`)}function Ma(t,e){let r=kO(t,e);return r===""||r!==".."&&!r.startsWith(".."+SO)&&!$O(r)}var hn=class extends Error{};function Za(t,e){let r=i=>{if(e)throw new hn(i)},n;try{n=Na(t)}catch{return r("the home directory cannot be read")}let o=nt(t,".context-doctor"),s=pp(t);for(let i of[o,s]){let a;try{a=rr(i)}catch{if(!e)return;try{Jv(i,{mode:448}),a=rr(i)}catch(u){return r(`cannot create ${ht(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${ht(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${ht(i,t)} is not a folder`);let c;try{c=Na(i)}catch{return r(`${ht(i,t)} cannot be read`)}if(!Ma(n,c))return r(`${ht(i,t)} resolves outside the home directory`)}return s}function Vv(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function DO(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>Vv(n,t)-Vv(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var LO=0;function Da(t=io()){let e=Za(t,!1);if(!e)return[];let r;try{r=bO(e)}catch{return[]}let n=[];for(let o of r){if(!Kv(o))continue;let s=nt(e,o);try{if(!rr(s).isDirectory())continue;let i=nt(s,"meta.json");if(!rr(i).isFile())continue;let a=JSON.parse(dp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(DO(Date.now()))}function hp(t,e=io()){let r=t==="latest"?Da(e)[0]?.id:t;if(!Kv(r))return;let n=Za(e,!1);if(!n)return;let o=nt(n,r),s=nt(o,"handoff.md");if(Ma(n,s))try{let i=rr(s);if(!i.isFile()||i.size>gt.readBytes||!rr(o).isDirectory()||!rr(nt(o,"meta.json")).isFile())return;let a=JSON.parse(dp(nt(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:dp(s,"utf8")}}catch{return}}function qO(t,e,r){let n=Za(t,!1);if(!n)return 0;let o=Da(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=nt(n,i.id);try{if(!Ma(n,a)||!rr(a).isDirectory()||!rr(nt(a,"meta.json")).isFile()||!Ma(Na(n),Na(a)))continue;wO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function xs(t,{keepNewlines:e=!0}={}){let r=String(t??"").replace(/\r\n?/g,`
|
|
101
|
+
`);return e?r.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,""):r.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}function Gv(t,{home:e=io(),now:r=new Date,store:n=!0}={}){let o=mp(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=ja(x);return i+=$.count,$.kinds.forEach(C=>s.add(C)),$.text},c=a(xs(t.brief)),u=fp(t.title?.trim()?a(xs(t.title,{keepNewlines:!1})):c.split(`
|
|
102
|
+
`).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",gt.titleChars),d=(t.verbatim??[]).map(x=>({label:fp(a(xs(x.label,{keepNewlines:!1})),gt.labelChars),text:a(xs(x.text))})),l=t.model===void 0?void 0:a(xs(String(t.model),{keepNewlines:!1})).slice(0,gt.modelChars)||void 0,p=r.toISOString(),m=jO(u,p,c,d),f=`${zO(r)}-${EO(u)}`,h={id:f,title:u,created:p,model:l,tokens:zt(m,l),briefTokens:zt(c,l),blocks:d.map(x=>({label:x.label,tokens:zt(x.text,l)})),masked:i,order:Date.now()*1e3+LO++%1e3},g=ZO(h.tokens,{...t,model:l});if(!n)return{meta:h,markdown:m,maskedKinds:[...s],math:g,rotated:0};let _=Za(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,C=nt(_,$);try{Jv(C,{mode:448}),h.id=$,v=C;break}catch(R){if(R.code!=="EEXIST")throw new hn(`cannot create a handoff folder in ${ht(_,e)} (${R.code??"error"})`)}}if(!v)throw new hn(`too many handoffs saved in the same second in ${ht(_,e)}`);try{Bv(nt(v,"handoff.md"),m,{mode:384,flag:"wx"}),Bv(nt(v,"meta.json"),JSON.stringify(h,null,2)+`
|
|
103
|
+
`,{mode:384,flag:"wx"})}catch(x){throw new hn(`cannot write the handoff in ${ht(v,e)} (${x.code??"error"})`)}let y=qO(e,gt.kept,h.id);if(!xO(nt(v,"handoff.md")))throw new hn(`the handoff in ${ht(v,e)} is gone`);return{meta:h,markdown:m,dir:v,maskedKinds:[...s],math:g,rotated:y}}function ht(t,e=io()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Xv(t,e=io()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as FO}from"node:dns";import{request as UO}from"node:http";import{request as HO}from"node:https";import{isIP as Qv}from"node:net";import{mkdtempSync as BO,rmSync as VO,writeFileSync as JO}from"node:fs";import{tmpdir as KO}from"node:os";import{extname as WO,join as Yv}from"node:path";var Je={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},GO={"application/pdf":".pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/msword":".doc","application/rtf":".rtf","text/rtf":".rtf","application/vnd.oasis.opendocument.text":".odt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx"};function ex(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function gp(t){let[e,r]=t.split(".").map(Number),n=Number(t.split(".")[2]);return e===0||e===10||e===127||e>=224||e===169&&r===254||e===172&&r>=16&&r<=31||e===192&&r===168||e===100&&r>=64&&r<=127||e===192&&r===0||e===198&&(r===18||r===19)||e===198&&r===51&&n===100||e===203&&r===0&&n===113||e===192&&r===88&&n===99}function XO(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"").replace(/%.*$/,""),r=e.match(/(\d+\.\d+\.\d+\.\d+)$/);if(r){let[u,d,l,p]=r[1].split(".").map(Number);e=e.slice(0,-r[1].length)+`${(u<<8|d).toString(16)}:${(l<<8|p).toString(16)}`}let[n,o]=e.split("::"),s=n?n.split(":"):[],i=o!==void 0&&o?o.split(":"):[],a=e.includes("::")?8-s.length-i.length:0,c=[...s,...Array(Math.max(0,a)).fill("0"),...i].map(u=>parseInt(u||"0",16));return c.length===8&&c.every(u=>Number.isInteger(u)&&u>=0&&u<=65535)?c:void 0}function tx(t){let e=t.replace(/^\[|\]$/g,""),r=Qv(e);if(r===4)return gp(e);if(r===6){let n=XO(e);return n?n.slice(0,5).every(o=>o===0)&&(n[5]===65535||n[5]===0)?n[5]===0&&n[6]===0&&n[7]<=1?!0:gp(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n.slice(0,4).every(o=>o===0)&&n[4]===65535&&n[5]===0?gp(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n[0]===100&&n[1]===65435||n[0]===8194||n[0]===8193&&n[1]===0||(n[0]&65024)===64512||(n[0]&65472)===65152||(n[0]&65280)===65280||n[0]===8193&&n[1]===3512||n[0]===256&&n[1]===0&&n[2]===0&&n[3]===0:!0}return!0}function yp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function YO(t,e=process.env){let r;try{r=new URL(t)}catch{return{error:"not a URL"}}if(r.username||r.password)return{error:"credentials in the URL"};let n=r.hostname.replace(/^\[|\]$/g,""),o=ex(e)&&yp(n);return r.protocol!=="https:"&&!(r.protocol==="http:"&&o)?{error:`only https downloads are allowed (got ${r.protocol.replace(":","")})`}:o?{url:r}:/^localhost$|\.localhost$|\.local$|\.internal$/i.test(n.replace(/\.$/,""))?{error:"a local host name"}:Qv(n)&&tx(n)?{error:"a private or loopback address"}:{url:r}}function QO(t){return(e,r,n)=>{FO(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>tx(u.address)&&!(t&&yp(u.address))))return n(Object.assign(new Error(`${e} resolves to a private address`),{code:"EPRIVATE"}));Array.isArray(s)?n(null,s):n(null,s,i)})}}function eA(t,e,r,n){return new Promise(o=>{let s=ex(e)&&yp(t.hostname),i=t.protocol==="https:"?HO:UO,a=!1,c=p=>{a||(a=!0,clearTimeout(d),o(p))},u=Math.max(1,r-Date.now()),d=setTimeout(()=>{l.destroy(),c({status:0,error:"timed out"})},u),l=i(t,{method:"GET",lookup:QO(s),timeout:u,headers:{accept:"*/*","user-agent":"context-doctor"}},p=>{let m=p.statusCode??0;if(m>=300&&m<400)return p.resume(),c({status:m,location:typeof p.headers.location=="string"?p.headers.location:void 0});if(m!==200)return p.resume(),c({status:m,error:`HTTP ${m}`});let f=n<Je.bytes?`over the ${Je.totalBytes/1024/1024} MB total for one call`:`too large (over ${Je.bytes/1024/1024} MB)`,h=Number(p.headers["content-length"]);if(Number.isFinite(h)&&h>n)return l.destroy(),c({status:m,error:f});let g=[],_=0;p.on("data",v=>{if(_+=v.length,_>n){l.destroy(),c({status:m,error:f});return}g.push(v)}),p.on("end",()=>c({status:m,body:Buffer.concat(g)})),p.on("error",v=>c({status:m,error:v.message}))});l.on("timeout",()=>{l.destroy(),c({status:0,error:"timed out"})}),l.on("error",p=>c({status:0,error:p.code==="EPRIVATE"?"refused: the host resolves to a private address":p.message})),l.end()})}async function tA(t,e=process.env,{deadline:r,maxBytes:n=Je.bytes}={}){let o=Math.min(Date.now()+Je.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Je.bytes)),i=t;for(let a=0;a<=Je.redirects;a++){let c=YO(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(Date.now()>=o)return{error:"timed out"};let u=await eA(c.url,e,o,s);if(u.error)return{error:u.error};if(u.location!==void 0){if(!u.location)return{error:`HTTP ${u.status} without a location`};try{i=new URL(u.location,c.url).toString()}catch{return{error:"refused a redirect: not a URL"}}continue}return{body:u.body??Buffer.alloc(0)}}return{error:`more than ${Je.redirects} redirects`}}function rA(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function rx(t,e=process.env){let r=[],n=[],o=0,s=Date.now()+Je.callMs;for(let i of t.slice(0,Je.files)){let a=rA(i);if(Date.now()>=s){n.push(`${a}: not read, the ${Je.callMs/1e3} s allowed for one call ran out`);continue}let c=await tA(String(i.download_url??""),e,{deadline:s,maxBytes:Je.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=WO(a).toLowerCase(),d=Pa.has(u)?u:GO[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(d){let l=BO(Yv(KO(),"cd-file-"));try{let p=Yv(l,`upload${d}`);JO(p,c.body,{mode:384});let m=await Ra(p,Math.min(Date.now()+vs,s));"error"in m?n.push(`${a}: ${m.error}`):r.push({name:a,text:m.text})}finally{VO(l,{recursive:!0,force:!0})}continue}if(c.body.subarray(0,8e3).includes(0)){n.push(`${a}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);continue}r.push({name:a,text:c.body.toString("utf8")})}return t.length>Je.files&&n.push(`${t.length-Je.files} more file(s): at most ${Je.files} per call`),{sources:r,skipped:n}}var nx={bodyBytes:10485760,bodyMs:3e4},nA=["https://chatgpt.com","https://chat.openai.com"],ox=["localhost","127.0.0.1","::1"];function La(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function qa(t){let e=t.trim().toLowerCase();return e.startsWith("[")?e=e.slice(1,e.indexOf("]")>0?e.indexOf("]"):void 0):e.split(":").length===2&&(e=e.split(":")[0]),e.replace(/\.$/,"")}function sx(t,e,r,n=process.env){let o=[...La(e),...La(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],s=new Set([...nA,...La(r),...La(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(c=>c.toLowerCase().replace(/\/+$/,"")));if(o.includes("*"))return{hosts:"*",origins:s};let i=qa(t),a=new Set([...ox,...o.map(qa)]);return i&&i!=="0.0.0.0"&&i!=="::"&&a.add(i),{hosts:a,origins:s}}function ix(t,e){if(t.hosts!=="*"){let n=qa(String(e.host??""));if(!n)return"the request has no Host header";if(!t.hosts.has(n))return`Host "${n}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${n}`}let r=e.origin;if(r!==void 0){let n=String(r).toLowerCase().replace(/\/+$/,"");if(t.origins.has(n))return;let o;try{o=new URL(n)}catch{return`Origin "${n}" is not allowed`}let s=qa(o.host);if(!(ox.includes(s)||t.hosts!=="*"&&t.hosts.has(s)))return`Origin "${n}" is not allowed. To let a web page call this server, start it with --allowed-origins ${n}`}}function ax(t,e=nx.bodyBytes,r=nx.bodyMs){return new Promise(n=>{let o=!1,s=setTimeout(()=>{o||(o=!0,n({status:408,code:-32600,message:`the request body did not arrive within ${Math.round(r/1e3)} s`}))},r),i=l=>{clearTimeout(s),n(l)},a={status:413,code:-32600,message:`request body over ${Math.round(e/1024/1024)} MB`},c=Number(t.headers["content-length"]);if(Number.isFinite(c)&&c>e)return t.resume(),i(a);let u=[],d=0;t.on("data",l=>{if(!o){if(d+=l.length,d>e)return o=!0,u.length=0,t.resume(),i(a);u.push(l)}}),t.on("end",()=>{if(!o){o=!0;try{i({value:JSON.parse(Buffer.concat(u).toString("utf8"))})}catch{i({status:400,code:-32700,message:"Parse error: the body is not JSON"})}}}),t.on("error",()=>{o||(o=!0,i({status:400,code:-32700,message:"the request body could not be read"}))})})}var WA=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],GA={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Rp(t,e,r){if(qv(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function Ux(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===M.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function Hx({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new ya({name:"context-doctor",version:"0.37.0"},{instructions:Lv});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, findings (duplicates, oversized pastes or tool results, base64, long history). Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Z.string().optional().describe("Conversation JSON or text. In a chat app pass `sketch` instead."),sketch:Z.object({turns:Z.number().int().nonnegative().max(1e5).describe("Exchanges so far"),model:Z.string().optional().describe("Model this chat runs as"),blocks:Z.array(Z.object({turn:Z.number().int().positive().max(1e5),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name, e.g. 'the nginx config'"),approx_tokens:Z.number().positive().optional(),approx_lines:Z.number().positive().optional(),approx_words:Z.number().positive().optional(),approx_chars:Z.number().positive().optional(),repeated:Z.number().int().positive().max(1e3).optional().describe("Times it appears (2+ = duplicate)"),stale:Z.boolean().optional().describe("Acted on, no longer needed")})).max(500).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars or tokens for logs and tool output."),model:Z.string().optional().describe("Model for window math, e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){for(let[h,g]of a.blocks.entries())for(let[_,v]of Object.entries(GA)){let y=g[_];if(typeof y=="number"&&y>v)return{isError:!0,content:[{type:"text",text:`sketch.blocks[${h}].${_} is ${y}; the most that makes sense is ${v}. Give a rough size of the block itself.`}]}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",m=pv({...a,model:a.model??c},{record:!t}),f=p+fv(m);return Rp(u?._meta,f,()=>{let h=Uv(m,f);return{...h,text:p+h.text}})}if(!i)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let d=nv(V0(i),c),l=uv(d);return Rp(u?._meta,l,()=>Fv(d,l))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens with deterministic strategies (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns the slimmed JSON and a savings summary. Use after profile_context finds waste the user wants fixed. Add prune-history only with the user's consent, then write the summary the result asks for.",{conversation:Z.string().describe("Conversation JSON (OpenAI, Anthropic, or a message array)"),strategies:Z.array(Z.enum(WA)).optional().describe("Default: dedupe, trim-tool-results, strip-base64. trim-tool-calls: big inline file writes; prune-history: old turns, lossy."),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages left untouched (default 6; prune-history keeps \u22652)"),max_tool_result_tokens:Z.number().int().positive().optional().describe("Budget per trimmed tool result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let d="";if(a?.includes("prune-history")){let _=await Ux(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),d=`
|
|
104
|
+
prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let l=av(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),p=l.tokensBefore-l.tokensAfter;p>0&&!t&&Ta({ev:"optimize",src:"mcp",saved:p,model:l.conversation?.model});let m=`Saved ~${A(p)} tokens (${A(l.tokensBefore)} \u2192 ${A(l.tokensAfter)}) via ${l.applied.length} change(s):
|
|
105
|
+
`+l.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${A(_.tokensSaved)})`).join(`
|
|
106
|
+
`)+d,f=1e5,h=JSON.stringify(l.conversation),g=[{type:"text",text:m},h.length<=f?{type:"text",text:h}:{type:"text",text:`[optimized conversation is ${h.length} chars \u2014 too large to echo into this context. Tell the user the savings above and that \`npx context-doctor optimize <file> --out slim.json\` produces the file directly.]`}];return l.prunedDigest&&g.push({type:"text",text:`ACTION REQUIRED (you, the assistant calling this tool): the pruned turns are digested below. Write a dense factual summary of them (\u2264150 tokens: decisions, current state, open items, key identifiers) and replace the '[context-doctor: ... pruned]' stub message in the conversation above with your summary before presenting the result.
|
|
95
107
|
|
|
96
108
|
PRUNED TURNS DIGEST:
|
|
97
|
-
`+
|
|
98
|
-
Skipped: ${
|
|
99
|
-
|
|
109
|
+
`+l.prunedDigest}),{content:g}});let o=Z.object({download_url:Z.string(),file_id:Z.string(),mime_type:Z.string().optional(),file_name:Z.string().optional()}).strict(),s={...t?{}:{paths:Z.array(Z.string()).max(50).optional().describe("Files or folders, absolute paths")},text:Z.string().optional().describe("Raw text to pack instead of files"),query:Z.string().optional().describe("The question; omit for an outline"),max_tokens:Z.number().int().positive().max(2e5).optional().describe("Budget, default 4000"),ids:Z.array(Z.string()).max(200).optional().describe("Chunk ids from an outline or result, e.g. docs/guide.md#4"),model:Z.string().optional().describe("Model the budget is counted for (default Claude)"),...t?{files:Z.array(o).optional().describe("Files the user uploaded")}:{semantic:Z.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")}};if(n.registerTool("pack_context",{description:"Read only the parts of large files a question needs: chunks files or folders along their structure, ranks chunks against `query` and returns the best that fit `max_tokens`, with ids and line ranges. No query: an outline; pick with `ids`. Use instead of reading a big doc, log or folder whole when not editing it. Text, code, PDF, Word, PowerPoint, ODT.",inputSchema:s,annotations:{title:"Pack context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},...t?{_meta:{"openai/fileParams":["files"]}}:{}},async(i,a)=>{let{paths:c,text:u,query:d,max_tokens:l,ids:p,model:m,semantic:f,files:h}=i,g=C=>({content:[{type:"text",text:C}],isError:!0});if(c?.length&&!r)return g("This server runs over HTTP and does not read files. Pass the document as `text`, or attach it (`files`).");let{sources:_,skipped:v}=c?.length?await Dv(c):{sources:[],skipped:[]};if(t&&h?.length){let C=await rx(h);_.push(...C.sources),v.push(...C.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return g(v.length?`Nothing readable: ${v.join("; ")}`:r?"Pass `paths` (files or folders) or `text`.":"This server runs over HTTP and reads no files from its own disk: pass the user's upload as `files`, or the document as `text`.");let y=await Mv(_,{query:d,budget:l,ids:p,model:m,semantic:t?void 0:f}),x=v.length?`
|
|
110
|
+
Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=jv(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:Rp(a?._meta,$,()=>{let C=Hv(y,$);return{...C,text:C.text+x}})}),n.prompt("context_checkup","Profile this conversation's context and apply the top fix. One click, no typing.",async()=>({messages:[{role:"user",content:{type:"text",text:"Run profile_context on our conversation so far: pass a `sketch` (turn count, the model you are running as, and every block over ~500 tokens, repeated, or an image; one size hint each). Report the total, the top three findings, and the estimated recoverable tokens in under 120 words. Then, if the top finding is recoverable, apply it: summarize the offending content into the points still needed and tell me what you dropped. Do not re-quote the content you are summarizing."}}]})),n.registerPrompt("handoff",{title:"Hand off to a new chat",description:"Write a short brief of this chat, save it, and continue in a new chat: the only way to cut a long chat's cost.",argsSchema:{focus:Z.string().max(200).optional().describe("What the next chat should work on (optional)")}},async({focus:i})=>({messages:[{role:"user",content:{type:"text",text:`Hand this chat off to a new one. Write a dense brief of at most ${gt.briefTargetTokens} tokens: the goal, decisions made (with the reason in a few words), the current state, open items and the next step, and key identifiers (names, paths, IDs, versions, numbers). Leave out what is finished or no longer needed. Separately, list only the blocks that must stay exact (code, config, commands, figures), each with a short label. Then call save_handoff with the brief, those blocks as \`verbatim\`, a short title, the model you run as, and \`chat_tokens\` if you have a profile_context figure (else \`turns\`). Do not write the brief into this reply before the call. After it, tell me in two lines how to continue, as its result says.`+(i?.trim()?` The next chat will work on: ${i.trim()}`:"")}}]})),n.registerPrompt("ask_file",{title:"Ask a big file",description:"Answer from a big file or folder without reading it whole: pack_context returns only the parts the question needs.",argsSchema:{path:Z.string().max(1e3).describe("Absolute path to the file or folder"),question:Z.string().max(2e3).describe("What you want to know from it")}},async({path:i,question:a})=>({messages:[{role:"user",content:{type:"text",text:`Answer from ${JSON.stringify(i)} without pasting or reading it whole: ${a}
|
|
111
|
+
|
|
112
|
+
Call pack_context with paths [${JSON.stringify(i)}] and the question as \`query\`. Answer from the chunks it returns and cite their ids. If they do not hold the answer, call it again with the ids it names as next best, or with no query for an outline to pick from; do not read the file whole. If pack_context cannot read paths here, ask me to attach or paste the file, and pass it as \`files\` or \`text\`.`}}]})),n.registerTool("save_handoff",{description:`Save a handoff for continuing in a new chat (a chat's history cannot be cut; a new chat can). Write \`brief\` yourself (\u2264${gt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:Z.string(),verbatim:Z.array(Z.object({label:Z.string(),text:Z.string()})).optional().describe("Code, config, figures"),title:Z.string().optional(),chat_tokens:Z.number().optional().describe("Chat size, from profile_context"),turns:Z.number().optional(),model:Z.string().optional()},annotations:{title:"Save handoff",readOnlyHint:!e,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async({brief:i,verbatim:a,title:c,chat_tokens:u,turns:d,model:l})=>{let p={brief:i,verbatim:a,title:c,model:l,chatTokens:u,turns:d},m=mp(p);if(m.length)return{isError:!0,content:[{type:"text",text:`Not saved: ${m.join(" ")}`}]};let f=a;if(e){let y=a?.length??0,x=await Ux(n,`Save a handoff of this chat on this computer (${ht(pp())}) to start a new chat from? "${ja(c??i.split(`
|
|
113
|
+
`)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${ja(a.map($=>$.label).join(", ")).text.slice(0,200)}`:""}.`,y?{include_verbatim:{type:"boolean",title:"Include the verbatim blocks",default:!0}}:{});if(x.asked&&!x.ok)return{content:[{type:"text",text:`Not saved: ${x.why}. Do not retry; ask the user in the chat if they still want a handoff.`}]};x.asked&&x.content.include_verbatim===!1&&(f=void 0)}let h;try{h=Gv({...p,verbatim:f},{store:e})}catch(y){let x=Xv(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let g=h.meta,_=`brief ~${A(g.briefTokens)}${g.blocks.length?`, ${g.blocks.length} verbatim block(s) ~${A(g.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[h.dir?`Handoff saved: ${g.id} (~${A(g.tokens)} tokens: ${_}) in ${ht(h.dir)}.`:`Handoff ready (~${A(g.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return g.masked>0&&v.push(`Masked ${g.masked} secret-looking string(s) (${h.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),g.briefTokens>gt.briefTargetTokens&&v.push(`The brief is ~${g.briefTokens} tokens; the target is \u2264${gt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(Wv(h.math)),h.dir?(v.push(t?"Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message (or, on the machine running this server, `context-doctor handoff latest --copy`). Then stop working in this chat.":"Now tell the user, in two lines: open a new chat and attach the resource handoff://latest (Claude Desktop: + menu, context-doctor), or paste the handoff; `context-doctor handoff latest --copy` copies it. Where attaching is not possible (ChatGPT, the web, phones), print the brief and the verbatim blocks in one fenced block to paste. Then stop working in this chat."),t||n.server.sendResourceListChanged().catch(()=>{})):v.push("Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message. Then stop working in this chat."),{content:[{type:"text",text:v.join(`
|
|
114
|
+
`)}]}}),e&&!t){let i="No handoff saved yet. In a long chat, pick the `handoff` prompt (+ menu) or ask for a handoff; the assistant saves it with save_handoff.";n.registerResource("handoff-latest","handoff://latest",{title:"Latest handoff",description:"The newest saved handoff: attach it to a new chat to continue there.",mimeType:"text/markdown"},async a=>({contents:[{uri:a.href,mimeType:"text/markdown",text:hp("latest")?.markdown??i}]})),n.registerResource("handoff",new _a("handoff://{id}",{list:async()=>({resources:Da().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${A(a.tokens)} tokens, saved ${a.created.slice(0,16).replace("T"," ")} UTC`,mimeType:"text/markdown"}))})}),{title:"Saved handoff",description:"A saved handoff, by id.",mimeType:"text/markdown"},async(a,{id:c})=>{let u=hp(String(Array.isArray(c)?c[0]:c));if(!u)throw new I(M.InvalidParams,`No saved handoff at ${a.href}. List them with resources/list, or run \`context-doctor handoff list\`.`);return{contents:[{uri:a.href,mimeType:"text/markdown",text:u.markdown}]}})}return n.tool("context_best_practices","Curated context-management checklist, optionally for one provider. Call it when the user asks how to keep context lean or structure prompts for caching.",{provider:Z.enum(["general","anthropic","openai"]).optional().describe("Default: general")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:i})=>({content:[{type:"text",text:[...Bx.general,...i&&i!=="general"?Bx[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
|
|
115
|
+
`)}]})),n}var Bx={general:["Put stable content first (system prompt, tool definitions, reference docs) and volatile content last \u2014 prompt caches match byte-identical prefixes only.","Truncate or summarize tool results before they enter history; keep only what the model actually needs downstream.","Never inline base64/binary data in text content \u2014 use file/image APIs.","Summarize and drop conversation history past ~30-40 turns; models lose the middle of long contexts well before the hard limit.","Deduplicate: if the same document/result appears twice, replace later copies with a reference.","Measure before optimizing \u2014 profile the conversation to find the actual heavy hitters."],anthropic:["Use prompt caching with cache_control breakpoints after your stable prefix: cached reads cost 2.5-10% of input depending on the model, and cache writes 1.25x input (5-minute cache) or 2x (1-hour cache).","Current Claude generations have a 1M-token window (Haiku 200k), but quality degrades under heavy fill; aim to stay under ~70%.","For agents: prefer compact tool-result summaries in history and re-fetch details on demand."],openai:["Prefix caching is automatic for prompts >1024 tokens \u2014 but only on byte-identical prefixes, so keep the front of your prompt stable.","Use max_completion_tokens headroom math: input + output must fit the window together."]};function XA(t,e,r){t.headers[e]=r;let n=t.rawHeaders;for(let o=0;o<n.length;o+=2)if(n[o].toLowerCase()===e){n[o+1]=r;return}n.push(e,r)}var Wa=process.argv.slice(2);if(Wa.includes("--http")){let t=a=>{let c=Wa.indexOf(a);return c>=0?Wa[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=Wa.includes("--store-handoffs"),o=sx(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(Fx(),qx));s(async(a,c)=>{try{if(a.url==="/health"){c.setHeader("content-type","application/json"),c.end(JSON.stringify({ok:!0,service:"context-doctor-mcp"}));return}let u=(a.url??"").split("?")[0];if(u!=="/mcp"&&u!=="/mcp/"){c.statusCode=404,c.end(JSON.stringify({error:"MCP endpoint is /mcp"}));return}let d=(_,v,y)=>{c.statusCode=_,c.setHeader("content-type","application/json"),(_===413||_===408)&&c.setHeader("connection","close"),c.end(JSON.stringify({jsonrpc:"2.0",error:{code:v,message:y},id:null})),(_===413||_===408)&&setTimeout(()=>a.destroy(),1e3).unref()},l=ix(o,a.headers);if(l)return d(403,-32e3,`Forbidden: ${l}.`);if(a.method!=="POST"){c.statusCode=405,c.setHeader("allow","POST"),c.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let p=await ax(a);if(!("value"in p))return d(p.status,p.code,p.message);let m=String(a.headers.accept??""),f=m.includes("text/event-stream");(!f||!m.includes("application/json"))&&XA(a,"accept","application/json, text/event-stream");let h=Hx({http:!0,storeHandoffs:n}),g=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{g.close(),h.close()}),await h.connect(g),await g.handleRequest(a,c,p.value)}catch(u){c.headersSent||(c.statusCode=500),c.end(JSON.stringify({error:u.message}))}}).listen(e,r,()=>{console.error(`context-doctor MCP (streamable HTTP) on http://${r}:${e}/mcp`),console.error("ChatGPT developer-mode connectors need a URL their servers can reach \u2014 expose this via your host or a tunnel."),console.error(o.hosts==="*"?"Host check off (--allowed-hosts '*').":`Answering Host: ${[...o.hosts].join(", ")}. Behind a tunnel, add its host name: --allowed-hosts <name>.`)})}else{let t=new xa;await Hx().connect(t)}
|