context-doctor 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cdRequire } from 'module'; const require = __cdRequire(import.meta.url);
3
- var Wb=Object.create;var uc=Object.defineProperty;var Kb=Object.getOwnPropertyDescriptor;var Gb=Object.getOwnPropertyNames;var Xb=Object.getPrototypeOf,Yb=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$o=(t,e)=>{for(var r in e)uc(t,r,{get:e[r],enumerable:!0})},Qb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gb(e))!Yb.call(t,o)&&o!==r&&uc(t,o,{get:()=>e[o],enumerable:!(n=Kb(e,o))||n.enumerable});return t};var lc=(t,e,r)=>(r=t!=null?Wb(Xb(t)):{},Qb(e||!t||!t.__esModule?uc(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 it(t){return t&&Object.assign(Us,t),Us}var u$,l$,er,Us,Nn=X(()=>{u$=Object.freeze({status:"aborted"});l$=Symbol("zod_brand"),er=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Us={}});var ee={};$o(ee,{BIGINT_FORMAT_RANGES:()=>pm,Class:()=>gc,NUMBER_FORMAT_RANGES:()=>$c,aborted:()=>on,allowsEval:()=>xc,assert:()=>h$,assertEqual:()=>d$,assertIs:()=>p$,assertNever:()=>m$,assertNotEqual:()=>f$,assignProp:()=>vc,cached:()=>Ro,captureStackTrace:()=>Bs,cleanEnum:()=>z$,cleanRegex:()=>Io,clone:()=>at,createTransparentProxy:()=>b$,defineLazy:()=>pe,esc:()=>nn,escapeRegex:()=>yr,extend:()=>k$,finalizeIssue:()=>$t,floatSafeRemainder:()=>_c,getElementAtPath:()=>g$,getEnumValues:()=>zo,getLengthableOrigin:()=>Co,getParsedType:()=>x$,getSizableOrigin:()=>mm,isObject:()=>Mn,isPlainObject:()=>jn,issue:()=>kc,joinValues:()=>Hs,jsonStringifyReplacer:()=>yc,merge:()=>S$,normalizeParams:()=>q,nullish:()=>Po,numKeys:()=>v$,omit:()=>$$,optionalKeys:()=>wc,partial:()=>T$,pick:()=>w$,prefixIssues:()=>jt,primitiveTypes:()=>fm,promiseAllObject:()=>y$,propertyKeyTypes:()=>bc,randomString:()=>_$,required:()=>E$,stringifyPrimitive:()=>Vs,unwrapMessage:()=>Eo});function d$(t){return t}function f$(t){return t}function p$(t){}function m$(t){throw new Error}function h$(t){}function zo(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 Hs(t,e="|"){return t.map(r=>Vs(r)).join(e)}function yc(t,e){return typeof e=="bigint"?e.toString():e}function Ro(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Po(t){return t==null}function Io(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function _c(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 pe(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 vc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function g$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function y$(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 _$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function nn(t){return JSON.stringify(t)}function Mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jn(t){if(Mn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Mn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function v$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function q(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 b$(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 Vs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function w$(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 at(t,{...t._zod.def,shape:r,checks:[]})}function $$(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 at(t,{...t._zod.def,shape:r,checks:[]})}function k$(t,e){if(!jn(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 vc(this,"shape",n),n},checks:[]};return at(t,r)}function S$(t,e){return at(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return vc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function T$(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 at(e,{...e._zod.def,shape:o,checks:[]})}function E$(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 at(e,{...e._zod.def,shape:o,checks:[]})}function on(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Eo(t){return typeof t=="string"?t:t?.message}function $t(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Eo(t.inst?._zod.def?.error?.(t))??Eo(e?.error?.(t))??Eo(r.customError?.(t))??Eo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function mm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Co(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function kc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function z$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Bs,xc,x$,bc,fm,$c,pm,gc,Zt=X(()=>{Bs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};xc=Ro(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});x$=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}`)}},bc=new Set(["string","number","symbol"]),fm=new Set(["string","number","bigint","boolean","symbol","undefined"]);$c={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]},pm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};gc=class{constructor(...e){}}});function Sc(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 Tc(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 hm,Js,Ao,Ec=X(()=>{Nn();Zt();hm=(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,yc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Js=w("$ZodError",hm),Ao=w("$ZodError",hm,{Parent:Error})});var zc,Rc,Pc,Ic,Cc,sn,Ac,an,Oc=X(()=>{Nn();Ec();Zt();zc=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 er;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>$t(c,s,it())));throw Bs(a,o?.callee),a}return i.value},Rc=zc(Ao),Pc=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=>$t(c,s,it())));throw Bs(a,o?.callee),a}return i.value},Ic=Pc(Ao),Cc=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 er;return s.issues.length?{success:!1,error:new(t??Js)(s.issues.map(i=>$t(i,o,it())))}:{success:!0,data:s.value}},sn=Cc(Ao),Ac=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=>$t(i,o,it())))}:{success:!0,data:s.value}},an=Ac(Ao)});function Sm(){return new RegExp(P$,"u")}function Nm(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 Mm(t){return new RegExp(`^${Nm(t)}$`)}function jm(t){let e=Nm({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(`^${Am}T(?:${n})$`)}var gm,ym,_m,vm,xm,bm,wm,$m,Nc,km,P$,Tm,Em,zm,Rm,Pm,Mc,Im,Cm,Am,Om,Zm,Dm,Lm,qm,Fm,Um,Hm,Ks=X(()=>{gm=/^[cC][^\s-]{8,}$/,ym=/^[0-9a-z]+$/,_m=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vm=/^[0-9a-vA-V]{20}$/,xm=/^[A-Za-z0-9]{27}$/,bm=/^[a-zA-Z0-9_-]{21}$/,wm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$m=/^([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})$/,Nc=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)$/,km=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,P$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Tm=/^(?:(?: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])$/,Em=/^(([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})$/,zm=/^((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])$/,Rm=/^(([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])$/,Pm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mc=/^[A-Za-z0-9_-]*$/,Im=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Cm=/^\+(?:[0-9]){6,14}[0-9]$/,Am="(?:(?:\\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])))",Om=new RegExp(`^${Am}$`);Zm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Dm=/^\d+$/,Lm=/^-?\d+(?:\.\d+)?/i,qm=/true|false/i,Fm=/null/i,Um=/^[^A-Z]*$/,Hm=/^[^a-z]*$/});var Ie,Bm,jc,Zc,Vm,Jm,Wm,Km,Gm,Oo,Xm,Ym,Qm,eh,th,rh,nh,Gs=X(()=>{Nn();Ks();Zt();Ie=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Bm={number:"number",bigint:"bigint",object:"date"},jc=w("$ZodCheckLessThan",(t,e)=>{Ie.init(t,e);let r=Bm[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})}}),Zc=w("$ZodCheckGreaterThan",(t,e)=>{Ie.init(t,e);let r=Bm[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})}}),Vm=w("$ZodCheckMultipleOf",(t,e)=>{Ie.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):_c(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})}}),Jm=w("$ZodCheckNumberFormat",(t,e)=>{Ie.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=$c[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=Dm)}),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})}}),Wm=w("$ZodCheckMaxLength",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Km=w("$ZodCheckMinLength",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Gm=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ie.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Po(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=Co(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})}}),Oo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ie.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=()=>{})}),Xm=w("$ZodCheckRegex",(t,e)=>{Oo.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})}}),Ym=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Um),Oo.init(t,e)}),Qm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Hm),Oo.init(t,e)}),eh=w("$ZodCheckIncludes",(t,e)=>{Ie.init(t,e);let r=yr(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})}}),th=w("$ZodCheckStartsWith",(t,e)=>{Ie.init(t,e);let r=new RegExp(`^${yr(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})}}),rh=w("$ZodCheckEndsWith",(t,e)=>{Ie.init(t,e);let r=new RegExp(`.*${yr(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})}}),nh=w("$ZodCheckOverwrite",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Xs,Dc=X(()=>{Xs=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 sw=Object.create;var fc=Object.defineProperty;var iw=Object.getOwnPropertyDescriptor;var aw=Object.getOwnPropertyNames;var cw=Object.getPrototypeOf,uw=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),To=(t,e)=>{for(var r in e)fc(t,r,{get:e[r],enumerable:!0})},lw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aw(e))!uw.call(t,o)&&o!==r&&fc(t,o,{get:()=>e[o],enumerable:!(n=iw(e,o))||n.enumerable});return t};var pc=(t,e,r)=>(r=t!=null?sw(cw(t)):{},lw(e||!t||!t.__esModule?fc(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 at(t){return t&&Object.assign(Vs,t),Vs}var x$,b$,rr,Vs,Dn=X(()=>{x$=Object.freeze({status:"aborted"});b$=Symbol("zod_brand"),rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vs={}});var ee={};To(ee,{BIGINT_FORMAT_RANGES:()=>_m,Class:()=>vc,NUMBER_FORMAT_RANGES:()=>Tc,aborted:()=>an,allowsEval:()=>$c,assert:()=>T$,assertEqual:()=>w$,assertIs:()=>k$,assertNever:()=>S$,assertNotEqual:()=>$$,assignProp:()=>wc,cached:()=>Co,captureStackTrace:()=>Ws,cleanEnum:()=>D$,cleanRegex:()=>Oo,clone:()=>ct,createTransparentProxy:()=>C$,defineLazy:()=>me,esc:()=>sn,escapeRegex:()=>xr,extend:()=>N$,finalizeIssue:()=>St,floatSafeRemainder:()=>bc,getElementAtPath:()=>E$,getEnumValues:()=>Io,getLengthableOrigin:()=>No,getParsedType:()=>I$,getSizableOrigin:()=>vm,isObject:()=>Ln,isPlainObject:()=>qn,issue:()=>Ec,joinValues:()=>Js,jsonStringifyReplacer:()=>xc,merge:()=>M$,normalizeParams:()=>q,nullish:()=>Ao,numKeys:()=>P$,omit:()=>O$,optionalKeys:()=>Sc,partial:()=>j$,pick:()=>A$,prefixIssues:()=>Lt,primitiveTypes:()=>ym,promiseAllObject:()=>z$,propertyKeyTypes:()=>kc,randomString:()=>R$,required:()=>Z$,stringifyPrimitive:()=>Ks,unwrapMessage:()=>Po});function w$(t){return t}function $$(t){return t}function k$(t){}function S$(t){throw new Error}function T$(t){}function Io(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 Js(t,e="|"){return t.map(r=>Ks(r)).join(e)}function xc(t,e){return typeof e=="bigint"?e.toString():e}function Co(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 Oo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function bc(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 me(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 wc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function E$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function z$(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 R$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function sn(t){return JSON.stringify(t)}function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function P$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function xr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ct(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function q(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 C$(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 Ks(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Sc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function A$(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 ct(t,{...t._zod.def,shape:r,checks:[]})}function O$(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 ct(t,{...t._zod.def,shape:r,checks:[]})}function N$(t,e){if(!qn(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 wc(this,"shape",n),n},checks:[]};return ct(t,r)}function M$(t,e){return ct(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return wc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function j$(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 ct(e,{...e._zod.def,shape:o,checks:[]})}function Z$(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 ct(e,{...e._zod.def,shape:o,checks:[]})}function an(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Lt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Po(t){return typeof t=="string"?t:t?.message}function St(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Po(t.inst?._zod.def?.error?.(t))??Po(e?.error?.(t))??Po(r.customError?.(t))??Po(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function vm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function No(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ec(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function D$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ws,$c,I$,kc,ym,Tc,_m,vc,qt=X(()=>{Ws=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};$c=Co(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});I$=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}`)}},kc=new Set(["string","number","symbol"]),ym=new Set(["string","number","bigint","boolean","symbol","undefined"]);Tc={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]},_m={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};vc=class{constructor(...e){}}});function zc(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 Rc(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 xm,Gs,Mo,Pc=X(()=>{Dn();qt();xm=(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,xc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gs=w("$ZodError",xm),Mo=w("$ZodError",xm,{Parent:Error})});var Ic,Cc,Ac,Oc,Nc,cn,Mc,un,jc=X(()=>{Dn();Pc();qt();Ic=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 rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Cc=Ic(Mo),Ac=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=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Oc=Ac(Mo),Nc=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 rr;return s.issues.length?{success:!1,error:new(t??Gs)(s.issues.map(i=>St(i,o,at())))}:{success:!0,data:s.value}},cn=Nc(Mo),Mc=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=>St(i,o,at())))}:{success:!0,data:s.value}},un=Mc(Mo)});function Pm(){return new RegExp(q$,"u")}function Lm(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 qm(t){return new RegExp(`^${Lm(t)}$`)}function Um(t){let e=Lm({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(`^${Zm}T(?:${n})$`)}var bm,wm,$m,km,Sm,Tm,Em,zm,Zc,Rm,q$,Im,Cm,Am,Om,Nm,Dc,Mm,jm,Zm,Dm,Fm,Hm,Bm,Vm,Jm,Wm,Km,Ys=X(()=>{bm=/^[cC][^\s-]{8,}$/,wm=/^[0-9a-z]+$/,$m=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,km=/^[0-9a-vA-V]{20}$/,Sm=/^[A-Za-z0-9]{27}$/,Tm=/^[a-zA-Z0-9_-]{21}$/,Em=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zm=/^([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})$/,Zc=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)$/,Rm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,q$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Im=/^(?:(?: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])$/,Cm=/^(([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})$/,Am=/^((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])$/,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})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Dc=/^[A-Za-z0-9_-]*$/,Mm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,jm=/^\+(?:[0-9]){6,14}[0-9]$/,Zm="(?:(?:\\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(`^${Zm}$`);Fm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Hm=/^\d+$/,Bm=/^-?\d+(?:\.\d+)?/i,Vm=/true|false/i,Jm=/null/i,Wm=/^[^A-Z]*$/,Km=/^[^a-z]*$/});var Ce,Gm,Lc,qc,Xm,Ym,Qm,eh,th,jo,rh,nh,oh,sh,ih,ah,ch,Qs=X(()=>{Dn();Ys();qt();Ce=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Gm={number:"number",bigint:"bigint",object:"date"},Lc=w("$ZodCheckLessThan",(t,e)=>{Ce.init(t,e);let r=Gm[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})}}),qc=w("$ZodCheckGreaterThan",(t,e)=>{Ce.init(t,e);let r=Gm[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})}}),Xm=w("$ZodCheckMultipleOf",(t,e)=>{Ce.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):bc(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})}}),Ym=w("$ZodCheckNumberFormat",(t,e)=>{Ce.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Tc[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=Hm)}),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})}}),Qm=w("$ZodCheckMaxLength",(t,e)=>{var r;Ce.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=No(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),eh=w("$ZodCheckMinLength",(t,e)=>{var r;Ce.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=No(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),th=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ce.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=No(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})}}),jo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ce.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=()=>{})}),rh=w("$ZodCheckRegex",(t,e)=>{jo.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})}}),nh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Wm),jo.init(t,e)}),oh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Km),jo.init(t,e)}),sh=w("$ZodCheckIncludes",(t,e)=>{Ce.init(t,e);let r=xr(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})}}),ih=w("$ZodCheckStartsWith",(t,e)=>{Ce.init(t,e);let r=new RegExp(`^${xr(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})}}),ah=w("$ZodCheckEndsWith",(t,e)=>{Ce.init(t,e);let r=new RegExp(`.*${xr(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})}}),ch=w("$ZodCheckOverwrite",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ei,Uc=X(()=>{ei=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 sh,Lc=X(()=>{sh={major:4,minor:0,patch:0}});function vh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function I$(t){if(!Mc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return vh(r)}function C$(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 ih(t,e,r){t.issues.length&&e.issues.push(...jt(r,t.issues)),e.value[r]=t.value}function Ys(t,e,r){t.issues.length&&e.issues.push(...jt(r,t.issues)),e.value[r]=t.value}function ah(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(...jt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ch(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=>$t(s,n,it())))}),e}function qc(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(jn(t)&&jn(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=qc(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=qc(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 uh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),on(t))return t;let n=qc(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 lh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function dh(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 fh(t,e,r){return on(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function ph(t){return t.value=Object.freeze(t.value),t}function mh(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(kc(o))}}var le,No,me,Fc,Uc,Hc,Bc,Vc,Jc,Wc,Kc,Gc,Xc,Yc,hh,gh,yh,_h,Qc,eu,tu,ru,nu,ou,su,iu,Qs,au,cu,uu,lu,du,fu,ei,ti,pu,mu,hu,gu,yu,_u,vu,xu,bu,wu,$u,ku,Su,Tu,Eu,xh=X(()=>{Gs();Nn();Dc();Oc();Ks();Zt();Lc();Zt();le=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=sh;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=on(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,m=l._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new er;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=on(s,d)))});else{if(s.issues.length===d)continue;c||(c=on(s,d))}}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 er;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=sn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return an(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),No=w("$ZodString",(t,e)=>{le.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Zm(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}}),me=w("$ZodStringFormat",(t,e)=>{Oo.init(t,e),No.init(t,e)}),Fc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=$m),me.init(t,e)}),Uc=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=Nc(n))}else e.pattern??(e.pattern=Nc());me.init(t,e)}),Hc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=km),me.init(t,e)}),Bc=w("$ZodURL",(t,e)=>{me.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:Im.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})}}}),Vc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Sm()),me.init(t,e)}),Jc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=bm),me.init(t,e)}),Wc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=gm),me.init(t,e)}),Kc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ym),me.init(t,e)}),Gc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=_m),me.init(t,e)}),Xc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=vm),me.init(t,e)}),Yc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xm),me.init(t,e)}),hh=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=jm(e)),me.init(t,e)}),gh=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Om),me.init(t,e)}),yh=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Mm(e)),me.init(t,e)}),_h=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=wm),me.init(t,e)}),Qc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Tm),me.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),eu=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Em),me.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})}}}),tu=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=zm),me.init(t,e)}),ru=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Rm),me.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})}}});nu=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Pm),me.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{vh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});ou=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Mc),me.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{I$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),su=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Cm),me.init(t,e)});iu=w("$ZodJWT",(t,e)=>{me.init(t,e),t._zod.check=r=>{C$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Qs=w("$ZodNumber",(t,e)=>{le.init(t,e),t._zod.pattern=t._zod.bag.pattern??Lm,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}}),au=w("$ZodNumber",(t,e)=>{Jm.init(t,e),Qs.init(t,e)}),cu=w("$ZodBoolean",(t,e)=>{le.init(t,e),t._zod.pattern=qm,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}}),uu=w("$ZodNull",(t,e)=>{le.init(t,e),t._zod.pattern=Fm,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}}),lu=w("$ZodUnknown",(t,e)=>{le.init(t,e),t._zod.parse=r=>r}),du=w("$ZodNever",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});fu=w("$ZodArray",(t,e)=>{le.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=>ih(u,r,i))):ih(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});ei=w("$ZodObject",(t,e)=>{le.init(t,e);let r=Ro(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof le))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=wc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});pe(t._zod,"propValues",()=>{let d=e.shape,m={};for(let p in d){let f=d[p]._zod;if(f.values){m[p]??(m[p]=new Set);for(let g of f.values)m[p].add(g)}}return m});let n=d=>{let m=new Xs(["shape","payload","ctx"]),p=r.value,f=v=>{let y=nn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),h=0;for(let v of p.keys)g[v]=`key_${h++}`;m.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let y=g[v];m.write(`const ${y} = ${f(v)};`);let x=nn(v);m.write(`
5
+ `))}}});var lh,Fc=X(()=>{lh={major:4,minor:0,patch:0}});function kh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function U$(t){if(!Dc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return kh(r)}function F$(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 dh(t,e,r){t.issues.length&&e.issues.push(...Lt(r,t.issues)),e.value[r]=t.value}function ti(t,e,r){t.issues.length&&e.issues.push(...Lt(r,t.issues)),e.value[r]=t.value}function fh(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(...Lt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ph(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=>St(s,n,at())))}),e}function Hc(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(qn(t)&&qn(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=Hc(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=Hc(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 mh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),an(t))return t;let n=Hc(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 hh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function gh(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 yh(t,e,r){return an(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function _h(t){return t.value=Object.freeze(t.value),t}function vh(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(Ec(o))}}var le,Zo,he,Bc,Vc,Jc,Wc,Kc,Gc,Xc,Yc,Qc,eu,tu,xh,bh,wh,$h,ru,nu,ou,su,iu,au,cu,uu,ri,lu,du,fu,pu,mu,hu,ni,oi,gu,yu,_u,vu,xu,bu,wu,$u,ku,Su,Tu,Eu,zu,Ru,Pu,Sh=X(()=>{Qs();Dn();Uc();jc();Ys();qt();Fc();qt();le=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=lh;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=an(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,m=l._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new rr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=an(s,d)))});else{if(s.issues.length===d)continue;c||(c=an(s,d))}}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 rr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=cn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return un(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Zo=w("$ZodString",(t,e)=>{le.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Fm(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}}),he=w("$ZodStringFormat",(t,e)=>{jo.init(t,e),Zo.init(t,e)}),Bc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zm),he.init(t,e)}),Vc=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=Zc(n))}else e.pattern??(e.pattern=Zc());he.init(t,e)}),Jc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Rm),he.init(t,e)}),Wc=w("$ZodURL",(t,e)=>{he.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:Mm.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})}}}),Kc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Pm()),he.init(t,e)}),Gc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Tm),he.init(t,e)}),Xc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=bm),he.init(t,e)}),Yc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=wm),he.init(t,e)}),Qc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=$m),he.init(t,e)}),eu=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=km),he.init(t,e)}),tu=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Sm),he.init(t,e)}),xh=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Um(e)),he.init(t,e)}),bh=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Dm),he.init(t,e)}),wh=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=qm(e)),he.init(t,e)}),$h=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Em),he.init(t,e)}),ru=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Im),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),nu=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Cm),he.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})}}}),ou=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Am),he.init(t,e)}),su=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Om),he.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})}}});iu=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Nm),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{kh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});au=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Dc),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{U$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),cu=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jm),he.init(t,e)});uu=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{F$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ri=w("$ZodNumber",(t,e)=>{le.init(t,e),t._zod.pattern=t._zod.bag.pattern??Bm,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}}),lu=w("$ZodNumber",(t,e)=>{Ym.init(t,e),ri.init(t,e)}),du=w("$ZodBoolean",(t,e)=>{le.init(t,e),t._zod.pattern=Vm,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}}),fu=w("$ZodNull",(t,e)=>{le.init(t,e),t._zod.pattern=Jm,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}}),pu=w("$ZodUnknown",(t,e)=>{le.init(t,e),t._zod.parse=r=>r}),mu=w("$ZodNever",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});hu=w("$ZodArray",(t,e)=>{le.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=>dh(u,r,i))):dh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});ni=w("$ZodObject",(t,e)=>{le.init(t,e);let r=Co(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof le))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=Sc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});me(t._zod,"propValues",()=>{let d=e.shape,m={};for(let p in d){let f=d[p]._zod;if(f.values){m[p]??(m[p]=new Set);for(let g of f.values)m[p].add(g)}}return m});let n=d=>{let m=new ei(["shape","payload","ctx"]),p=r.value,f=v=>{let y=sn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),h=0;for(let v of p.keys)g[v]=`key_${h++}`;m.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let y=g[v];m.write(`const ${y} = ${f(v)};`);let x=sn(v);m.write(`
6
6
  if (${y}.issues.length) {
7
7
  if (input[${x}] === undefined) {
8
8
  if (${x} in input) {
@@ -24,18 +24,18 @@ var Wb=Object.create;var uc=Object.defineProperty;var Kb=Object.getOwnPropertyDe
24
24
  `)}else{let y=g[v];m.write(`const ${y} = ${f(v)};`),m.write(`
25
25
  if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
26
26
  ...iss,
27
- path: iss.path ? [${nn(v)}, ...iss.path] : [${nn(v)}]
28
- })));`),m.write(`newResult[${nn(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Mn,i=!Us.jitless,c=i&&xc.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let f=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let y=l.shape;for(let x of l.keys){let $=y[x],N=$._zod.run({value:p[x],issues:[]},m),A=$._zod.optin==="optional"&&$._zod.optout==="optional";N instanceof Promise?f.push(N.then(ce=>A?ah(ce,d,x,p):Ys(ce,d,x))):A?ah(N,d,x,p):Ys(N,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let g=[],h=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(h.has(y))continue;if(v==="never"){g.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>Ys($,d,y))):Ys(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});ti=w("$ZodUnion",(t,e)=>{le.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(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=>Io(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=>ch(i,r,t,n)):ch(s,r,t,n)}}),pu=w("$ZodDiscriminatedUnion",(t,e)=>{ti.init(t,e);let r=t._zod.parse;pe(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=Ro(()=>{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(!Mn(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)}}),mu=w("$ZodIntersection",(t,e)=>{le.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])=>uh(r,c,u)):uh(r,s,i)}});hu=w("$ZodRecord",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!jn(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(...jt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jt(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=>$t(u,n,it())),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(...jt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),gu=w("$ZodEnum",(t,e)=>{le.init(t,e);let r=zo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>bc.has(typeof n)).map(n=>typeof n=="string"?yr(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}}),yu=w("$ZodLiteral",(t,e)=>{le.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?yr(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}}),_u=w("$ZodTransform",(t,e)=>{le.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 er;return r.value=o,r}}),vu=w("$ZodOptional",(t,e)=>{le.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(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)}),xu=w("$ZodNullable",(t,e)=>{le.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(r.source)}|null)$`):void 0}),pe(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)}),bu=w("$ZodDefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(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=>lh(s,e)):lh(o,e)}});wu=w("$ZodPrefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(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))}),$u=w("$ZodNonOptional",(t,e)=>{le.init(t,e),pe(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=>dh(s,t)):dh(o,t)}});ku=w("$ZodCatch",(t,e)=>{le.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(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=>$t(i,n,it()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>$t(s,n,it()))},input:r.value}),r.issues=[]),r)}}),Su=w("$ZodPipe",(t,e)=>{le.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(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=>fh(s,e,n)):fh(o,e,n)}});Tu=w("$ZodReadonly",(t,e)=>{le.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(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(ph):ph(o)}});Eu=w("$ZodCustom",(t,e)=>{Ie.init(t,e),le.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=>mh(s,r,n,t));mh(o,r,n,t)}})});function bh(){return{localeError:O$()}}var A$,O$,wh=X(()=>{Zt();A$=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},O$=()=>{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 ${A$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Vs(n.values[0])}`:`Invalid option: expected one of ${Hs(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":""}: ${Hs(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 ri=X(()=>{});function $h(){return new Mo}var N$,M$,Mo,_r,Ru=X(()=>{N$=Symbol("ZodOutput"),M$=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)}};_r=$h()});function Pu(t,e){return new t({type:"string",...q(e)})}function Iu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ni(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Cu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Au(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function Ou(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Nu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Mu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function ju(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Zu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function Du(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Lu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function qu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Fu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Uu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Hu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Bu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Vu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Ju(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Wu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Ku(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Gu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Xu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function kh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function Sh(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function Th(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function Eh(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Yu(t,e){return new t({type:"number",checks:[],...q(e)})}function Qu(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function el(t,e){return new t({type:"boolean",...q(e)})}function tl(t,e){return new t({type:"null",...q(e)})}function rl(t){return new t({type:"unknown"})}function nl(t,e){return new t({type:"never",...q(e)})}function oi(t,e){return new jc({check:"less_than",...q(e),value:t,inclusive:!1})}function jo(t,e){return new jc({check:"less_than",...q(e),value:t,inclusive:!0})}function si(t,e){return new Zc({check:"greater_than",...q(e),value:t,inclusive:!1})}function Zo(t,e){return new Zc({check:"greater_than",...q(e),value:t,inclusive:!0})}function ii(t,e){return new Vm({check:"multiple_of",...q(e),value:t})}function ai(t,e){return new Wm({check:"max_length",...q(e),maximum:t})}function Zn(t,e){return new Km({check:"min_length",...q(e),minimum:t})}function ci(t,e){return new Gm({check:"length_equals",...q(e),length:t})}function ol(t,e){return new Xm({check:"string_format",format:"regex",...q(e),pattern:t})}function sl(t){return new Ym({check:"string_format",format:"lowercase",...q(t)})}function il(t){return new Qm({check:"string_format",format:"uppercase",...q(t)})}function al(t,e){return new eh({check:"string_format",format:"includes",...q(e),includes:t})}function cl(t,e){return new th({check:"string_format",format:"starts_with",...q(e),prefix:t})}function ul(t,e){return new rh({check:"string_format",format:"ends_with",...q(e),suffix:t})}function cn(t){return new nh({check:"overwrite",tx:t})}function ll(t){return cn(e=>e.normalize(t))}function dl(){return cn(t=>t.trim())}function fl(){return cn(t=>t.toLowerCase())}function pl(){return cn(t=>t.toUpperCase())}function zh(t,e,r){return new t({type:"array",element:e,...q(r)})}function ml(t,e,r){let n=q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function hl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...q(r)})}var Rh=X(()=>{Gs();Zt()});var Ph=X(()=>{});function gl(t,e){if(t instanceof Mo){let n=new ui(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 ui(e);return r.process(t),r.emit(t,e)}function Te(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 Te(o.element,r);case"object":{for(let s in o.shape)if(Te(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Te(s,r))return!0;return!1}case"intersection":return Te(o.left,r)||Te(o.right,r);case"tuple":{for(let s of o.items)if(Te(s,r))return!0;return!!(o.rest&&Te(o.rest,r))}case"record":return Te(o.keyType,r)||Te(o.valueType,r);case"map":return Te(o.keyType,r)||Te(o.valueType,r);case"set":return Te(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Te(o.innerType,r);case"lazy":return Te(o.getter(),r);case"default":return Te(o.innerType,r);case"prefault":return Te(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Te(o.in,r)||Te(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var ui,Ih=X(()=>{Ru();Zt();ui=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??_r,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},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let f=p;f.type="string";let{minimum:g,maximum:h,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof h=="number"&&(f.maxLength=h),_&&(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=p,{minimum:g,maximum:h,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 g=="number"&&(f.minimum=g,typeof x=="number"&&(x>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof h=="number"&&(f.maximum=h,typeof y=="number"&&(y<=h?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=p;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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=p,{minimum:g,maximum:h}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof h=="number"&&(f.maxItems=h),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=p;f.type="object",f.properties={};let g=o.shape;for(let v in g)f.properties[v]=this.process(g[v],{...d,path:[...d.path,"properties",v]});let h=new Set(Object.keys(g)),_=new Set([...h].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,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=p;f.anyOf=o.options.map((g,h)=>this.process(g,{...d,path:[...d.path,"anyOf",h]}));break}case"intersection":{let f=p,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),h=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(g)?g.allOf:[g],..._(h)?h.allOf:[h]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let g=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,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:h,maximum:_}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=p;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=p,g=zo(o.entries);g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=p,g=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(h))}else g.push(h);if(g.length!==0)if(g.length===1){let h=g[0];f.type=h===null?"null":typeof h,f.const=h}else g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),g.every(h=>typeof h=="boolean")&&(f.type="string"),g.every(h=>h===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=p,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:_,mime:v}=e._zod.bag;h!==void 0&&(g.minLength=h),_!==void 0&&(g.maxLength=_),v?v.length===1?(g.contentMediaType=v[0],Object.assign(f,g)):f.anyOf=v.map(y=>({...g,contentMediaType:y})):Object.assign(f,g);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);p.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=p;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._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")}p.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=p,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.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,p.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"&&Te(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 g=n.external.registry.get(l[0])?.id,h=n.external.uri??(v=>v);if(g)return{ref:h(g)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${h("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let p=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:p+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let f=d.schema;for(let g in f)delete f[g];f.$ref=m};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 ? [${sn(v)}, ...iss.path] : [${sn(v)}]
28
+ })));`),m.write(`newResult[${sn(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Ln,i=!Vs.jitless,c=i&&$c.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let f=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let y=l.shape;for(let x of l.keys){let $=y[x],N=$._zod.run({value:p[x],issues:[]},m),A=$._zod.optin==="optional"&&$._zod.optout==="optional";N instanceof Promise?f.push(N.then(ae=>A?fh(ae,d,x,p):ti(ae,d,x))):A?fh(N,d,x,p):ti(N,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let g=[],h=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(h.has(y))continue;if(v==="never"){g.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>ti($,d,y))):ti(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});oi=w("$ZodUnion",(t,e)=>{le.init(t,e),me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),me(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=>Oo(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=>ph(i,r,t,n)):ph(s,r,t,n)}}),gu=w("$ZodDiscriminatedUnion",(t,e)=>{oi.init(t,e);let r=t._zod.parse;me(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=Co(()=>{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(!Ln(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)}}),yu=w("$ZodIntersection",(t,e)=>{le.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])=>mh(r,c,u)):mh(r,s,i)}});_u=w("$ZodRecord",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!qn(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(...Lt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Lt(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=>St(u,n,at())),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(...Lt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Lt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),vu=w("$ZodEnum",(t,e)=>{le.init(t,e);let r=Io(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>kc.has(typeof n)).map(n=>typeof n=="string"?xr(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}}),xu=w("$ZodLiteral",(t,e)=>{le.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?xr(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}}),bu=w("$ZodTransform",(t,e)=>{le.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 rr;return r.value=o,r}}),wu=w("$ZodOptional",(t,e)=>{le.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oo(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)}),$u=w("$ZodNullable",(t,e)=>{le.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oo(r.source)}|null)$`):void 0}),me(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)}),ku=w("$ZodDefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(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=>hh(s,e)):hh(o,e)}});Su=w("$ZodPrefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(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))}),Tu=w("$ZodNonOptional",(t,e)=>{le.init(t,e),me(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=>gh(s,t)):gh(o,t)}});Eu=w("$ZodCatch",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(t._zod,"optout",()=>e.innerType._zod.optout),me(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=>St(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>St(s,n,at()))},input:r.value}),r.issues=[]),r)}}),zu=w("$ZodPipe",(t,e)=>{le.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(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=>yh(s,e,n)):yh(o,e,n)}});Ru=w("$ZodReadonly",(t,e)=>{le.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>e.innerType._zod.optin),me(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(_h):_h(o)}});Pu=w("$ZodCustom",(t,e)=>{Ce.init(t,e),le.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=>vh(s,r,n,t));vh(o,r,n,t)}})});function Th(){return{localeError:B$()}}var H$,B$,Eh=X(()=>{qt();H$=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},B$=()=>{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 ${H$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ks(n.values[0])}`:`Invalid option: expected one of ${Js(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":""}: ${Js(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 si=X(()=>{});function zh(){return new Do}var V$,J$,Do,br,Cu=X(()=>{V$=Symbol("ZodOutput"),J$=Symbol("ZodInput"),Do=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)}};br=zh()});function Au(t,e){return new t({type:"string",...q(e)})}function Ou(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ii(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Nu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Mu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function ju(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Du(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function Lu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function qu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function Uu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Fu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Hu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Bu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Vu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Ju(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Wu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Ku(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Gu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Xu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Yu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Qu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function el(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function Rh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function Ph(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function Ih(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function Ch(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function tl(t,e){return new t({type:"number",checks:[],...q(e)})}function rl(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function nl(t,e){return new t({type:"boolean",...q(e)})}function ol(t,e){return new t({type:"null",...q(e)})}function sl(t){return new t({type:"unknown"})}function il(t,e){return new t({type:"never",...q(e)})}function ai(t,e){return new Lc({check:"less_than",...q(e),value:t,inclusive:!1})}function Lo(t,e){return new Lc({check:"less_than",...q(e),value:t,inclusive:!0})}function ci(t,e){return new qc({check:"greater_than",...q(e),value:t,inclusive:!1})}function qo(t,e){return new qc({check:"greater_than",...q(e),value:t,inclusive:!0})}function ui(t,e){return new Xm({check:"multiple_of",...q(e),value:t})}function li(t,e){return new Qm({check:"max_length",...q(e),maximum:t})}function Un(t,e){return new eh({check:"min_length",...q(e),minimum:t})}function di(t,e){return new th({check:"length_equals",...q(e),length:t})}function al(t,e){return new rh({check:"string_format",format:"regex",...q(e),pattern:t})}function cl(t){return new nh({check:"string_format",format:"lowercase",...q(t)})}function ul(t){return new oh({check:"string_format",format:"uppercase",...q(t)})}function ll(t,e){return new sh({check:"string_format",format:"includes",...q(e),includes:t})}function dl(t,e){return new ih({check:"string_format",format:"starts_with",...q(e),prefix:t})}function fl(t,e){return new ah({check:"string_format",format:"ends_with",...q(e),suffix:t})}function ln(t){return new ch({check:"overwrite",tx:t})}function pl(t){return ln(e=>e.normalize(t))}function ml(){return ln(t=>t.trim())}function hl(){return ln(t=>t.toLowerCase())}function gl(){return ln(t=>t.toUpperCase())}function Ah(t,e,r){return new t({type:"array",element:e,...q(r)})}function yl(t,e,r){let n=q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function _l(t,e,r){return new t({type:"custom",check:"custom",fn:e,...q(r)})}var Oh=X(()=>{Qs();qt()});var Nh=X(()=>{});function vl(t,e){if(t instanceof Do){let n=new fi(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 fi(e);return r.process(t),r.emit(t,e)}function Ee(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 Ee(o.element,r);case"object":{for(let s in o.shape)if(Ee(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ee(s,r))return!0;return!1}case"intersection":return Ee(o.left,r)||Ee(o.right,r);case"tuple":{for(let s of o.items)if(Ee(s,r))return!0;return!!(o.rest&&Ee(o.rest,r))}case"record":return Ee(o.keyType,r)||Ee(o.valueType,r);case"map":return Ee(o.keyType,r)||Ee(o.valueType,r);case"set":return Ee(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ee(o.innerType,r);case"lazy":return Ee(o.getter(),r);case"default":return Ee(o.innerType,r);case"prefault":return Ee(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ee(o.in,r)||Ee(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var fi,Mh=X(()=>{Cu();qt();fi=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??br,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},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let f=p;f.type="string";let{minimum:g,maximum:h,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof h=="number"&&(f.maxLength=h),_&&(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=p,{minimum:g,maximum:h,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 g=="number"&&(f.minimum=g,typeof x=="number"&&(x>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof h=="number"&&(f.maximum=h,typeof y=="number"&&(y<=h?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=p;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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=p,{minimum:g,maximum:h}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof h=="number"&&(f.maxItems=h),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=p;f.type="object",f.properties={};let g=o.shape;for(let v in g)f.properties[v]=this.process(g[v],{...d,path:[...d.path,"properties",v]});let h=new Set(Object.keys(g)),_=new Set([...h].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,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=p;f.anyOf=o.options.map((g,h)=>this.process(g,{...d,path:[...d.path,"anyOf",h]}));break}case"intersection":{let f=p,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),h=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(g)?g.allOf:[g],..._(h)?h.allOf:[h]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let g=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,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:h,maximum:_}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=p;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=p,g=Io(o.entries);g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=p,g=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(h))}else g.push(h);if(g.length!==0)if(g.length===1){let h=g[0];f.type=h===null?"null":typeof h,f.const=h}else g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),g.every(h=>typeof h=="boolean")&&(f.type="string"),g.every(h=>h===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=p,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:_,mime:v}=e._zod.bag;h!==void 0&&(g.minLength=h),_!==void 0&&(g.maxLength=_),v?v.length===1?(g.contentMediaType=v[0],Object.assign(f,g)):f.anyOf=v.map(y=>({...g,contentMediaType:y})):Object.assign(f,g);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);p.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=p;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._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")}p.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=p,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.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,p.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"&&Ee(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 g=n.external.registry.get(l[0])?.id,h=n.external.uri??(v=>v);if(g)return{ref:h(g)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${h("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let p=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:p+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let f=d.schema;for(let g in f)delete f[g];f.$ref=m};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>
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 p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){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 m=this.seen.get(l),p=m.def??m.schema,f={...p};if(m.ref===null)return;let g=m.ref;if(m.ref=null,g){a(g,d);let h=this.seen.get(g).schema;h.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(h)):(Object.assign(p,h),Object.assign(p,f))}m.isParent||this.override({zodSchema:l,jsonSchema:p,path:m.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 Ch=X(()=>{});var Ue=X(()=>{Nn();Oc();Ec();xh();Gs();Lc();Zt();Ks();ri();Ru();Dc();Ph();Rh();Ih();Ch()});var _l=X(()=>{Ue()});var Do={};$o(Do,{ZodISODate:()=>Mh,ZodISODateTime:()=>Nh,ZodISODuration:()=>Zh,ZodISOTime:()=>jh,date:()=>xl,datetime:()=>vl,duration:()=>wl,time:()=>bl});function vl(t){return kh(Nh,t)}function xl(t){return Sh(Mh,t)}function bl(t){return Th(jh,t)}function wl(t){return Eh(Zh,t)}var Nh,Mh,jh,Zh,$l=X(()=>{Ue();kl();Nh=w("ZodISODateTime",(t,e)=>{hh.init(t,e),xe.init(t,e)});Mh=w("ZodISODate",(t,e)=>{gh.init(t,e),xe.init(t,e)});jh=w("ZodISOTime",(t,e)=>{yh.init(t,e),xe.init(t,e)});Zh=w("ZodISODuration",(t,e)=>{_h.init(t,e),xe.init(t,e)})});var Dh,oZ,Lo,Sl=X(()=>{Ue();Ue();Dh=(t,e)=>{Js.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Tc(t,r)},flatten:{value:r=>Sc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},oZ=w("ZodError",Dh),Lo=w("ZodError",Dh,{Parent:Error})});var Lh,qh,Fh,Uh,Tl=X(()=>{Ue();Sl();Lh=zc(Lo),qh=Pc(Lo),Fh=Cc(Lo),Uh=Ac(Lo)});function b(t){return Pu(zk,t)}function ae(t){return Yu(Wh,t)}function Bh(t){return Qu(Vk,t)}function Re(t){return el(Jk,t)}function Kh(t){return tl(Wk,t)}function be(){return rl(Kk)}function Xk(t){return nl(Gk,t)}function te(t,e){return zh(Yk,t,e)}function I(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new Gh(r)}function He(t,e){return new Gh({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:be(),...ee.normalizeParams(e)})}function ge(t,e){return new Xh({type:"union",options:t,...ee.normalizeParams(e)})}function Rl(t,e,r){return new Qk({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}function pi(t,e){return new eS({type:"intersection",left:t,right:e})}function he(t,e,r){return new tS({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new El({type:"enum",entries:r,...ee.normalizeParams(e)})}function j(t,e){return new rS({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}function Yh(t){return new nS({type:"transform",transform:t})}function we(t){return new Qh({type:"optional",innerType:t})}function Vh(t){return new oS({type:"nullable",innerType:t})}function iS(t,e){return new sS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cS(t,e){return new aS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function uS(t,e){return new eg({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}function dS(t,e){return new lS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function zl(t,e){return new fS({type:"pipe",in:t,out:e})}function mS(t){return new pS({type:"readonly",innerType:t})}function hS(t){let e=new Ie({check:"custom"});return e._zod.check=t,e}function rg(t,e){return ml(tg,t??(()=>!0),e)}function gS(t,e={}){return hl(tg,t,e)}function yS(t){let e=hS(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ee.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(ee.issue(o))}},t(r.value,r)));return e}function Pl(t,e){return zl(Yh(t),e)}var ke,Jh,zk,xe,Rk,Hh,fi,Pk,Ik,Ck,Ak,Ok,Nk,Mk,jk,Zk,Dk,Lk,qk,Fk,Uk,Hk,Bk,Wh,Vk,Jk,Wk,Kk,Gk,Yk,Gh,Xh,Qk,eS,tS,El,rS,nS,Qh,oS,sS,aS,eg,lS,fS,pS,tg,kl=X(()=>{Ue();Ue();_l();$l();Tl();ke=w("ZodType",(t,e)=>(le.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)=>at(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Lh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Fh(t,r,n),t.parseAsync=async(r,n)=>qh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Uh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(gS(r,n)),t.superRefine=r=>t.check(yS(r)),t.overwrite=r=>t.check(cn(r)),t.optional=()=>we(t),t.nullable=()=>Vh(t),t.nullish=()=>we(Vh(t)),t.nonoptional=r=>uS(t,r),t.array=()=>te(t),t.or=r=>ge([t,r]),t.and=r=>pi(t,r),t.transform=r=>zl(t,Yh(r)),t.default=r=>iS(t,r),t.prefault=r=>cS(t,r),t.catch=r=>dS(t,r),t.pipe=r=>zl(t,r),t.readonly=()=>mS(t),t.describe=r=>{let n=t.clone();return _r.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return _r.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return _r.get(t);let n=t.clone();return _r.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Jh=w("_ZodString",(t,e)=>{No.init(t,e),ke.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(ol(...n)),t.includes=(...n)=>t.check(al(...n)),t.startsWith=(...n)=>t.check(cl(...n)),t.endsWith=(...n)=>t.check(ul(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(ai(...n)),t.length=(...n)=>t.check(ci(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(sl(n)),t.uppercase=n=>t.check(il(n)),t.trim=()=>t.check(dl()),t.normalize=(...n)=>t.check(ll(...n)),t.toLowerCase=()=>t.check(fl()),t.toUpperCase=()=>t.check(pl())}),zk=w("ZodString",(t,e)=>{No.init(t,e),Jh.init(t,e),t.email=r=>t.check(Iu(Rk,r)),t.url=r=>t.check(Mu(Pk,r)),t.jwt=r=>t.check(Xu(Bk,r)),t.emoji=r=>t.check(ju(Ik,r)),t.guid=r=>t.check(ni(Hh,r)),t.uuid=r=>t.check(Cu(fi,r)),t.uuidv4=r=>t.check(Au(fi,r)),t.uuidv6=r=>t.check(Ou(fi,r)),t.uuidv7=r=>t.check(Nu(fi,r)),t.nanoid=r=>t.check(Zu(Ck,r)),t.guid=r=>t.check(ni(Hh,r)),t.cuid=r=>t.check(Du(Ak,r)),t.cuid2=r=>t.check(Lu(Ok,r)),t.ulid=r=>t.check(qu(Nk,r)),t.base64=r=>t.check(Wu(Fk,r)),t.base64url=r=>t.check(Ku(Uk,r)),t.xid=r=>t.check(Fu(Mk,r)),t.ksuid=r=>t.check(Uu(jk,r)),t.ipv4=r=>t.check(Hu(Zk,r)),t.ipv6=r=>t.check(Bu(Dk,r)),t.cidrv4=r=>t.check(Vu(Lk,r)),t.cidrv6=r=>t.check(Ju(qk,r)),t.e164=r=>t.check(Gu(Hk,r)),t.datetime=r=>t.check(vl(r)),t.date=r=>t.check(xl(r)),t.time=r=>t.check(bl(r)),t.duration=r=>t.check(wl(r))});xe=w("ZodStringFormat",(t,e)=>{me.init(t,e),Jh.init(t,e)}),Rk=w("ZodEmail",(t,e)=>{Hc.init(t,e),xe.init(t,e)}),Hh=w("ZodGUID",(t,e)=>{Fc.init(t,e),xe.init(t,e)}),fi=w("ZodUUID",(t,e)=>{Uc.init(t,e),xe.init(t,e)}),Pk=w("ZodURL",(t,e)=>{Bc.init(t,e),xe.init(t,e)}),Ik=w("ZodEmoji",(t,e)=>{Vc.init(t,e),xe.init(t,e)}),Ck=w("ZodNanoID",(t,e)=>{Jc.init(t,e),xe.init(t,e)}),Ak=w("ZodCUID",(t,e)=>{Wc.init(t,e),xe.init(t,e)}),Ok=w("ZodCUID2",(t,e)=>{Kc.init(t,e),xe.init(t,e)}),Nk=w("ZodULID",(t,e)=>{Gc.init(t,e),xe.init(t,e)}),Mk=w("ZodXID",(t,e)=>{Xc.init(t,e),xe.init(t,e)}),jk=w("ZodKSUID",(t,e)=>{Yc.init(t,e),xe.init(t,e)}),Zk=w("ZodIPv4",(t,e)=>{Qc.init(t,e),xe.init(t,e)}),Dk=w("ZodIPv6",(t,e)=>{eu.init(t,e),xe.init(t,e)}),Lk=w("ZodCIDRv4",(t,e)=>{tu.init(t,e),xe.init(t,e)}),qk=w("ZodCIDRv6",(t,e)=>{ru.init(t,e),xe.init(t,e)}),Fk=w("ZodBase64",(t,e)=>{nu.init(t,e),xe.init(t,e)}),Uk=w("ZodBase64URL",(t,e)=>{ou.init(t,e),xe.init(t,e)}),Hk=w("ZodE164",(t,e)=>{su.init(t,e),xe.init(t,e)}),Bk=w("ZodJWT",(t,e)=>{iu.init(t,e),xe.init(t,e)}),Wh=w("ZodNumber",(t,e)=>{Qs.init(t,e),ke.init(t,e),t.gt=(n,o)=>t.check(si(n,o)),t.gte=(n,o)=>t.check(Zo(n,o)),t.min=(n,o)=>t.check(Zo(n,o)),t.lt=(n,o)=>t.check(oi(n,o)),t.lte=(n,o)=>t.check(jo(n,o)),t.max=(n,o)=>t.check(jo(n,o)),t.int=n=>t.check(Bh(n)),t.safe=n=>t.check(Bh(n)),t.positive=n=>t.check(si(0,n)),t.nonnegative=n=>t.check(Zo(0,n)),t.negative=n=>t.check(oi(0,n)),t.nonpositive=n=>t.check(jo(0,n)),t.multipleOf=(n,o)=>t.check(ii(n,o)),t.step=(n,o)=>t.check(ii(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});Vk=w("ZodNumberFormat",(t,e)=>{au.init(t,e),Wh.init(t,e)});Jk=w("ZodBoolean",(t,e)=>{cu.init(t,e),ke.init(t,e)});Wk=w("ZodNull",(t,e)=>{uu.init(t,e),ke.init(t,e)});Kk=w("ZodUnknown",(t,e)=>{lu.init(t,e),ke.init(t,e)});Gk=w("ZodNever",(t,e)=>{du.init(t,e),ke.init(t,e)});Yk=w("ZodArray",(t,e)=>{fu.init(t,e),ke.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(ai(r,n)),t.length=(r,n)=>t.check(ci(r,n)),t.unwrap=()=>t.element});Gh=w("ZodObject",(t,e)=>{ei.init(t,e),ke.init(t,e),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:be()}),t.loose=()=>t.clone({...t._zod.def,catchall:be()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xk()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(Qh,t,r[0]),t.required=(...r)=>ee.required(eg,t,r[0])});Xh=w("ZodUnion",(t,e)=>{ti.init(t,e),ke.init(t,e),t.options=e.options});Qk=w("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),pu.init(t,e)});eS=w("ZodIntersection",(t,e)=>{mu.init(t,e),ke.init(t,e)});tS=w("ZodRecord",(t,e)=>{hu.init(t,e),ke.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});El=w("ZodEnum",(t,e)=>{gu.init(t,e),ke.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 El({...e,checks:[],...ee.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 El({...e,checks:[],...ee.normalizeParams(o),entries:s})}});rS=w("ZodLiteral",(t,e)=>{yu.init(t,e),ke.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]}})});nS=w("ZodTransform",(t,e)=>{_u.init(t,e),ke.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ee.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(ee.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Qh=w("ZodOptional",(t,e)=>{vu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});oS=w("ZodNullable",(t,e)=>{xu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});sS=w("ZodDefault",(t,e)=>{bu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});aS=w("ZodPrefault",(t,e)=>{wu.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});eg=w("ZodNonOptional",(t,e)=>{$u.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});lS=w("ZodCatch",(t,e)=>{ku.init(t,e),ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});fS=w("ZodPipe",(t,e)=>{Su.init(t,e),ke.init(t,e),t.in=e.in,t.out=e.out});pS=w("ZodReadonly",(t,e)=>{Tu.init(t,e),ke.init(t,e)});tg=w("ZodCustom",(t,e)=>{Eu.init(t,e),ke.init(t,e)})});var ng=X(()=>{});var og=X(()=>{});var sg=X(()=>{Ue();kl();_l();Sl();Tl();ng();Ue();wh();ri();$l();og();it(bh())});var ig=X(()=>{sg()});var ag=X(()=>{ig()});function wg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function $g(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Cl,cg,Fn,br,hi,Ee,ug,lg,xZ,xS,bS,Al,ct,qo,dg,Ce,ft,pt,Ae,gi,fg,tr,pg,mg,Ol,rr,O,Nl,Un,Fo,bZ,yi,wS,_i,$S,Uo,qn,hg,kS,SS,TS,ES,zS,RS,vi,Ml,PS,IS,jl,xi,CS,AS,bi,OS,Ho,Bo,NS,Vo,Hn,MS,Jo,wi,$i,ki,wZ,Si,Ti,Ei,gg,yg,_g,Zl,vg,Wo,Bn,xg,jS,zi,ZS,Ri,DS,Dl,LS,Pi,qS,FS,US,HS,BS,VS,JS,WS,KS,GS,Ii,XS,YS,Ci,Ll,ql,Fl,QS,eT,tT,Ul,rT,nT,oT,sT,iT,bg,Ai,aT,Oi,$Z,cT,Vn,uT,kZ,Ko,lT,Hl,dT,fT,pT,mT,hT,gT,yT,mi,_T,vT,xT,Go,Bl,bT,wT,$T,kT,ST,TT,ET,zT,RT,PT,IT,CT,AT,OT,NT,MT,jT,ZT,Jn,DT,LT,qT,Ni,FT,UT,HT,Vl,BT,SZ,TZ,EZ,zZ,RZ,PZ,C,Il,wr=X(()=>{ag();Cl="2025-11-25",cg="2025-03-26",Fn=[Cl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],br="io.modelcontextprotocol/related-task",hi="2.0",Ee=rg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ug=ge([b(),ae().int()]),lg=b(),xZ=He({ttl:ae().optional(),pollInterval:ae().optional()}),xS=I({ttl:ae().optional()}),bS=I({taskId:b()}),Al=He({progressToken:ug.optional(),[br]:bS.optional()}),ct=I({_meta:Al.optional()}),qo=ct.extend({task:xS.optional()}),dg=t=>qo.safeParse(t).success,Ce=I({method:b(),params:ct.loose().optional()}),ft=I({_meta:Al.optional()}),pt=I({method:b(),params:ft.loose().optional()}),Ae=He({_meta:Al.optional()}),gi=ge([b(),ae().int()]),fg=I({jsonrpc:j(hi),id:gi,...Ce.shape}).strict(),tr=t=>fg.safeParse(t).success,pg=I({jsonrpc:j(hi),...pt.shape}).strict(),mg=t=>pg.safeParse(t).success,Ol=I({jsonrpc:j(hi),id:gi,result:Ae}).strict(),rr=t=>Ol.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"})(O||(O={}));Nl=I({jsonrpc:j(hi),id:gi.optional(),error:I({code:ae().int(),message:b(),data:be().optional()})}).strict(),Un=t=>Nl.safeParse(t).success,Fo=ge([fg,pg,Ol,Nl]),bZ=ge([Ol,Nl]),yi=Ae.strict(),wS=ft.extend({requestId:gi.optional(),reason:b().optional()}),_i=pt.extend({method:j("notifications/cancelled"),params:wS}),$S=I({src:b(),mimeType:b().optional(),sizes:te(b()).optional(),theme:Qe(["light","dark"]).optional()}),Uo=I({icons:te($S).optional()}),qn=I({name:b(),title:b().optional()}),hg=qn.extend({...qn.shape,...Uo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),kS=pi(I({applyDefaults:Re().optional()}),he(b(),be())),SS=Pl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,pi(I({form:kS.optional(),url:Ee.optional()}),he(b(),be()).optional())),TS=He({list:Ee.optional(),cancel:Ee.optional(),requests:He({sampling:He({createMessage:Ee.optional()}).optional(),elicitation:He({create:Ee.optional()}).optional()}).optional()}),ES=He({list:Ee.optional(),cancel:Ee.optional(),requests:He({tools:He({call:Ee.optional()}).optional()}).optional()}),zS=I({experimental:he(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:SS.optional(),roots:I({listChanged:Re().optional()}).optional(),tasks:TS.optional(),extensions:he(b(),Ee).optional()}),RS=ct.extend({protocolVersion:b(),capabilities:zS,clientInfo:hg}),vi=Ce.extend({method:j("initialize"),params:RS}),Ml=t=>vi.safeParse(t).success,PS=I({experimental:he(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:I({listChanged:Re().optional()}).optional(),resources:I({subscribe:Re().optional(),listChanged:Re().optional()}).optional(),tools:I({listChanged:Re().optional()}).optional(),tasks:ES.optional(),extensions:he(b(),Ee).optional()}),IS=Ae.extend({protocolVersion:b(),capabilities:PS,serverInfo:hg,instructions:b().optional()}),jl=pt.extend({method:j("notifications/initialized"),params:ft.optional()}),xi=Ce.extend({method:j("ping"),params:ct.optional()}),CS=I({progress:ae(),total:we(ae()),message:we(b())}),AS=I({...ft.shape,...CS.shape,progressToken:ug}),bi=pt.extend({method:j("notifications/progress"),params:AS}),OS=ct.extend({cursor:lg.optional()}),Ho=Ce.extend({params:OS.optional()}),Bo=Ae.extend({nextCursor:lg.optional()}),NS=Qe(["working","input_required","completed","failed","cancelled"]),Vo=I({taskId:b(),status:NS,ttl:ge([ae(),Kh()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:we(ae()),statusMessage:we(b())}),Hn=Ae.extend({task:Vo}),MS=ft.merge(Vo),Jo=pt.extend({method:j("notifications/tasks/status"),params:MS}),wi=Ce.extend({method:j("tasks/get"),params:ct.extend({taskId:b()})}),$i=Ae.merge(Vo),ki=Ce.extend({method:j("tasks/result"),params:ct.extend({taskId:b()})}),wZ=Ae.loose(),Si=Ho.extend({method:j("tasks/list")}),Ti=Bo.extend({tasks:te(Vo)}),Ei=Ce.extend({method:j("tasks/cancel"),params:ct.extend({taskId:b()})}),gg=Ae.merge(Vo),yg=I({uri:b(),mimeType:we(b()),_meta:he(b(),be()).optional()}),_g=yg.extend({text:b()}),Zl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vg=yg.extend({blob:Zl}),Wo=Qe(["user","assistant"]),Bn=I({audience:te(Wo).optional(),priority:ae().min(0).max(1).optional(),lastModified:Do.datetime({offset:!0}).optional()}),xg=I({...qn.shape,...Uo.shape,uri:b(),description:we(b()),mimeType:we(b()),size:we(ae()),annotations:Bn.optional(),_meta:we(He({}))}),jS=I({...qn.shape,...Uo.shape,uriTemplate:b(),description:we(b()),mimeType:we(b()),annotations:Bn.optional(),_meta:we(He({}))}),zi=Ho.extend({method:j("resources/list")}),ZS=Bo.extend({resources:te(xg)}),Ri=Ho.extend({method:j("resources/templates/list")}),DS=Bo.extend({resourceTemplates:te(jS)}),Dl=ct.extend({uri:b()}),LS=Dl,Pi=Ce.extend({method:j("resources/read"),params:LS}),qS=Ae.extend({contents:te(ge([_g,vg]))}),FS=pt.extend({method:j("notifications/resources/list_changed"),params:ft.optional()}),US=Dl,HS=Ce.extend({method:j("resources/subscribe"),params:US}),BS=Dl,VS=Ce.extend({method:j("resources/unsubscribe"),params:BS}),JS=ft.extend({uri:b()}),WS=pt.extend({method:j("notifications/resources/updated"),params:JS}),KS=I({name:b(),description:we(b()),required:we(Re())}),GS=I({...qn.shape,...Uo.shape,description:we(b()),arguments:we(te(KS)),_meta:we(He({}))}),Ii=Ho.extend({method:j("prompts/list")}),XS=Bo.extend({prompts:te(GS)}),YS=ct.extend({name:b(),arguments:he(b(),b()).optional()}),Ci=Ce.extend({method:j("prompts/get"),params:YS}),Ll=I({type:j("text"),text:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),ql=I({type:j("image"),data:Zl,mimeType:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),Fl=I({type:j("audio"),data:Zl,mimeType:b(),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),QS=I({type:j("tool_use"),name:b(),id:b(),input:he(b(),be()),_meta:he(b(),be()).optional()}),eT=I({type:j("resource"),resource:ge([_g,vg]),annotations:Bn.optional(),_meta:he(b(),be()).optional()}),tT=xg.extend({type:j("resource_link")}),Ul=ge([Ll,ql,Fl,tT,eT]),rT=I({role:Wo,content:Ul}),nT=Ae.extend({description:b().optional(),messages:te(rT)}),oT=pt.extend({method:j("notifications/prompts/list_changed"),params:ft.optional()}),sT=I({title:b().optional(),readOnlyHint:Re().optional(),destructiveHint:Re().optional(),idempotentHint:Re().optional(),openWorldHint:Re().optional()}),iT=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),bg=I({...qn.shape,...Uo.shape,description:b().optional(),inputSchema:I({type:j("object"),properties:he(b(),Ee).optional(),required:te(b()).optional()}).catchall(be()),outputSchema:I({type:j("object"),properties:he(b(),Ee).optional(),required:te(b()).optional()}).catchall(be()).optional(),annotations:sT.optional(),execution:iT.optional(),_meta:he(b(),be()).optional()}),Ai=Ho.extend({method:j("tools/list")}),aT=Bo.extend({tools:te(bg)}),Oi=Ae.extend({content:te(Ul).default([]),structuredContent:he(b(),be()).optional(),isError:Re().optional()}),$Z=Oi.or(Ae.extend({toolResult:be()})),cT=qo.extend({name:b(),arguments:he(b(),be()).optional()}),Vn=Ce.extend({method:j("tools/call"),params:cT}),uT=pt.extend({method:j("notifications/tools/list_changed"),params:ft.optional()}),kZ=I({autoRefresh:Re().default(!0),debounceMs:ae().int().nonnegative().default(300)}),Ko=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),lT=ct.extend({level:Ko}),Hl=Ce.extend({method:j("logging/setLevel"),params:lT}),dT=ft.extend({level:Ko,logger:b().optional(),data:be()}),fT=pt.extend({method:j("notifications/message"),params:dT}),pT=I({name:b().optional()}),mT=I({hints:te(pT).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),hT=I({mode:Qe(["auto","required","none"]).optional()}),gT=I({type:j("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:te(Ul).default([]),structuredContent:I({}).loose().optional(),isError:Re().optional(),_meta:he(b(),be()).optional()}),yT=Rl("type",[Ll,ql,Fl]),mi=Rl("type",[Ll,ql,Fl,QS,gT]),_T=I({role:Wo,content:ge([mi,te(mi)]),_meta:he(b(),be()).optional()}),vT=qo.extend({messages:te(_T),modelPreferences:mT.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:te(b()).optional(),metadata:Ee.optional(),tools:te(bg).optional(),toolChoice:hT.optional()}),xT=Ce.extend({method:j("sampling/createMessage"),params:vT}),Go=Ae.extend({model:b(),stopReason:we(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:Wo,content:yT}),Bl=Ae.extend({model:b(),stopReason:we(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Wo,content:ge([mi,te(mi)])}),bT=I({type:j("boolean"),title:b().optional(),description:b().optional(),default:Re().optional()}),wT=I({type:j("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),$T=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),kT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),default:b().optional()}),ST=I({type:j("string"),title:b().optional(),description:b().optional(),oneOf:te(I({const:b(),title:b()})),default:b().optional()}),TT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),enumNames:te(b()).optional(),default:b().optional()}),ET=ge([kT,ST]),zT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:j("string"),enum:te(b())}),default:te(b()).optional()}),RT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:te(I({const:b(),title:b()}))}),default:te(b()).optional()}),PT=ge([zT,RT]),IT=ge([TT,ET,PT]),CT=ge([IT,bT,wT,$T]),AT=qo.extend({mode:j("form").optional(),message:b(),requestedSchema:I({type:j("object"),properties:he(b(),CT),required:te(b()).optional()})}),OT=qo.extend({mode:j("url"),message:b(),elicitationId:b(),url:b().url()}),NT=ge([AT,OT]),MT=Ce.extend({method:j("elicitation/create"),params:NT}),jT=ft.extend({elicitationId:b()}),ZT=pt.extend({method:j("notifications/elicitation/complete"),params:jT}),Jn=Ae.extend({action:Qe(["accept","decline","cancel"]),content:Pl(t=>t===null?void 0:t,he(b(),ge([b(),ae(),Re(),te(b())])).optional())}),DT=I({type:j("ref/resource"),uri:b()}),LT=I({type:j("ref/prompt"),name:b()}),qT=ct.extend({ref:ge([LT,DT]),argument:I({name:b(),value:b()}),context:I({arguments:he(b(),b()).optional()}).optional()}),Ni=Ce.extend({method:j("completion/complete"),params:qT});FT=Ae.extend({completion:He({values:te(b()).max(100),total:we(ae().int()),hasMore:we(Re())})}),UT=I({uri:b().startsWith("file://"),name:b().optional(),_meta:he(b(),be()).optional()}),HT=Ce.extend({method:j("roots/list"),params:ct.optional()}),Vl=Ae.extend({roots:te(UT)}),BT=pt.extend({method:j("notifications/roots/list_changed"),params:ft.optional()}),SZ=ge([xi,vi,Ni,Hl,Ci,Ii,zi,Ri,Pi,HS,VS,Vn,Ai,wi,ki,Si,Ei]),TZ=ge([_i,bi,jl,BT,Jo]),EZ=ge([yi,Go,Bl,Jn,Vl,$i,Ti,Hn]),zZ=ge([xi,xT,MT,HT,wi,ki,Si,Ei]),RZ=ge([_i,bi,fT,WS,FS,uT,oT,Jo,ZT]),PZ=ge([yi,IS,FT,nT,XS,ZS,DS,qS,Oi,aT,$i,Ti,Hn]),C=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===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Il(o.elicitations,r)}return new t(e,r,n)}},Il=class extends C{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var es=z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var Yo=class{};ie._CodeOrName=Yo;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var dn=class extends Yo{constructor(e){if(super(),!ie.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}}};ie.Name=dn;var mt=class extends Yo{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 dn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ie._Code=mt;ie.nil=new mt("");function oy(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rd(r,e[n]),r.push(t[++n]);return new mt(r)}ie._=oy;var td=new mt("+");function sy(t,...e){let r=[Qo(t[0])],n=0;for(;n<e.length;)r.push(td),rd(r,e[n]),r.push(td,Qo(t[++n]));return rE(r),new mt(r)}ie.str=sy;function rd(t,e){e instanceof mt?t.push(...e._items):e instanceof dn?t.push(e):t.push(sE(e))}ie.addCodeArg=rd;function rE(t){let e=1;for(;e<t.length-1;){if(t[e]===td){let r=nE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function nE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof dn||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 dn))return`"${t}${e.slice(1)}`}function oE(t,e){return e.emptyStr()?t:t.emptyStr()?e:sy`${t}${e}`}ie.strConcat=oE;function sE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Qo(Array.isArray(t)?t.join(","):t)}function iE(t){return new mt(Qo(t))}ie.stringify=iE;function Qo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=Qo;function aE(t){return typeof t=="string"&&ie.IDENTIFIER.test(t)?new mt(`.${t}`):oy`[${t}]`}ie.getProperty=aE;function cE(t){if(typeof t=="string"&&ie.IDENTIFIER.test(t))return new mt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ie.getEsmExportName=cE;function uE(t){return new mt(t.toString())}ie.regexpCode=uE});var sd=z(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=es(),nd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},qi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(qi||(tt.UsedValueState=qi={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var Fi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.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}}};tt.Scope=Fi;var Ui=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=Ui;var lE=(0,et._)`\n`,od=class extends Fi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lE:et.nil}}get(){return this._scope}name(e){return new Ui(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,et._)`${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=et.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,qi.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new nd(u);c.set(u,qi.Completed)})}return s}};tt.ValueScope=od});var W=z(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 ne=es(),Tt=sd(),kr=es();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return kr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return kr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return kr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return kr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return kr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return kr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return kr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return kr.Name}});var Ji=sd();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Ji.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Ji.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Ji.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Ji.varKinds}});K.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},id=class extends nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Tt.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=Kn(this.rhs,e,r)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},Hi=class extends nr{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Kn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Vi(e,this.rhs)}},ad=class extends Hi{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},cd=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ud=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ld=class extends nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},dd=class extends nr{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=Kn(this.code,e,r),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},ts=class extends nr{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)||(dE(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>mn(e,r.names),{})}},or=class extends ts{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},fd=class extends ts{},Wn=class extends or{};Wn.kind="else";var fn=class t extends or{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 Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(iy(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=Kn(this.condition,e,r),this}get names(){let e=super.names;return Vi(e,this.condition),this.else&&mn(e,this.else.names),e}};fn.kind="if";var pn=class extends or{};pn.kind="for";var pd=class extends pn{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=Kn(this.iteration,e,r),this}get names(){return mn(super.names,this.iteration.names)}},md=class extends pn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Tt.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=Vi(super.names,this.from);return Vi(e,this.to)}},Bi=class extends pn{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=Kn(this.iterable,e,r),this}get names(){return mn(super.names,this.iterable.names)}},rs=class extends or{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)}};rs.kind="func";var ns=class extends ts{render(e){return"return "+super.render(e)}};ns.kind="return";var hd=class extends or{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&&mn(e,this.catch.names),this.finally&&mn(e,this.finally.names),e}},os=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};os.kind="catch";var ss=class extends or{render(e){return"finally"+super.render(e)}};ss.kind="finally";var gd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
- `:""},this._extScope=e,this._scope=new Tt.Scope({parent:e}),this._nodes=[new fd]}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 id(e,s,n)),s}const(e,r,n){return this._def(Tt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Tt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Tt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hi(e,r,n))}add(e,r){return this._leafNode(new ad(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new dd(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,ne.addCodeArg)(r,o));return r.push("}"),new ne._Code(r)}if(e,r,n){if(this._blockNode(new fn(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 fn(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(fn,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new pd(e),r)}forRange(e,r,n,o,s=this.opts.es5?Tt.varKinds.var:Tt.varKinds.let){let i=this._scope.toName(e);return this._for(new md(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Tt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ne.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ne._)`${i}.length`,a=>{this.var(s,(0,ne._)`${i}[${a}]`),n(s)})}return this._for(new Bi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Tt.varKinds.var:Tt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`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(pn)}label(e){return this._leafNode(new cd(e))}break(e){return this._leafNode(new ud(e))}return(e){let r=new ns;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ns)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new hd;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new os(s),r(s)}return n&&(this._currNode=o.finally=new ss,this.code(n)),this._endBlockNode(os,ss)}throw(e){return this._leafNode(new ld(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=ne.nil,n,o){return this._blockNode(new rs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(rs)}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 fn))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=gd;function mn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Vi(t,e){return e instanceof ne._CodeOrName?mn(t,e.names):t}function Kn(t,e,r){if(t instanceof ne.Name)return n(t);if(!o(t))return t;return new ne._Code(t._items.reduce((s,i)=>(i instanceof ne.Name&&(i=n(i)),i instanceof ne._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 ne._Code&&s._items.some(i=>i instanceof ne.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function dE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function iy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ne._)`!${yd(t)}`}K.not=iy;var fE=ay(K.operators.AND);function pE(...t){return t.reduce(fE)}K.and=pE;var mE=ay(K.operators.OR);function hE(...t){return t.reduce(mE)}K.or=hE;function ay(t){return(e,r)=>e===ne.nil?r:r===ne.nil?e:(0,ne._)`${yd(e)} ${t} ${yd(r)}`}function yd(t){return t instanceof ne.Name?t:(0,ne._)`(${t})`}});var oe=z(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var fe=W(),gE=es();function yE(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=yE;function _E(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ly(t,e),!dy(e,t.self.RULES.all))}G.alwaysValidSchema=_E;function ly(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]||my(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=ly;function dy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=dy;function vE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=vE;function xE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,fe._)`${r}`}return(0,fe._)`${t}${e}${(0,fe.getProperty)(n)}`}G.schemaRefOrVal=xE;function bE(t){return fy(decodeURIComponent(t))}G.unescapeFragment=bE;function wE(t){return encodeURIComponent(vd(t))}G.escapeFragment=wE;function vd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=vd;function fy(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=fy;function $E(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=$E;function cy({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof fe.Name?(s instanceof fe.Name?t(o,s,i):e(o,s,i),i):s instanceof fe.Name?(e(o,i,s),s):r(s,i);return a===fe.Name&&!(c instanceof fe.Name)?n(o,c):c}}G.mergeEvaluated={props:cy({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,fe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,fe._)`${r} || {}`).code((0,fe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,fe._)`${r} || {}`),xd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:py}),items:cy({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,fe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,fe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function py(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,fe._)`{}`);return e!==void 0&&xd(t,r,e),r}G.evaluatedPropsToName=py;function xd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,fe._)`${e}${(0,fe.getProperty)(n)}`,!0))}G.setEvaluated=xd;var uy={};function kE(t,e){return t.scopeValue("func",{ref:e,code:uy[e.code]||(uy[e.code]=new gE._Code(e.code))})}G.useFunc=kE;var _d;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_d||(G.Type=_d={}));function SE(t,e,r){if(t instanceof fe.Name){let n=e===_d.Num;return r?n?(0,fe._)`"[" + ${t} + "]"`:(0,fe._)`"['" + ${t} + "']"`:n?(0,fe._)`"/" + ${t}`:(0,fe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,fe.getProperty)(t).toString():"/"+vd(t)}G.getErrorPath=SE;function my(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=my});var sr=z(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Ze=W(),TE={data:new Ze.Name("data"),valCxt:new Ze.Name("valCxt"),instancePath:new Ze.Name("instancePath"),parentData:new Ze.Name("parentData"),parentDataProperty:new Ze.Name("parentDataProperty"),rootData:new Ze.Name("rootData"),dynamicAnchors:new Ze.Name("dynamicAnchors"),vErrors:new Ze.Name("vErrors"),errors:new Ze.Name("errors"),this:new Ze.Name("this"),self:new Ze.Name("self"),scope:new Ze.Name("scope"),json:new Ze.Name("json"),jsonPos:new Ze.Name("jsonPos"),jsonLen:new Ze.Name("jsonLen"),jsonPart:new Ze.Name("jsonPart")};bd.default=TE});var is=z(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var se=W(),Wi=oe(),Ve=sr();De.keywordError={message:({keyword:t})=>(0,se.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,se.str)`"${t}" keyword must be ${e} ($data)`:(0,se.str)`"${t}" keyword is invalid ($data)`};function EE(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=yy(t,e,r);n??(i||a)?hy(s,c):gy(o,(0,se._)`[${c}]`)}De.reportError=EE;function zE(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=yy(t,e,r);hy(o,a),s||i||gy(n,Ve.default.vErrors)}De.reportExtraError=zE;function RE(t,e){t.assign(Ve.default.errors,e),t.if((0,se._)`${Ve.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,se._)`${Ve.default.vErrors}.length`,e),()=>t.assign(Ve.default.vErrors,null)))}De.resetErrorsCount=RE;function PE({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,Ve.default.errors,a=>{t.const(i,(0,se._)`${Ve.default.vErrors}[${a}]`),t.if((0,se._)`${i}.instancePath === undefined`,()=>t.assign((0,se._)`${i}.instancePath`,(0,se.strConcat)(Ve.default.instancePath,s.errorPath))),t.assign((0,se._)`${i}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,se._)`${i}.schema`,r),t.assign((0,se._)`${i}.data`,n))})}De.extendErrors=PE;function hy(t,e){let r=t.const("err",e);t.if((0,se._)`${Ve.default.vErrors} === null`,()=>t.assign(Ve.default.vErrors,(0,se._)`[${r}]`),(0,se._)`${Ve.default.vErrors}.push(${r})`),t.code((0,se._)`${Ve.default.errors}++`)}function gy(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,se._)`new ${t.ValidationError}(${e})`):(r.assign((0,se._)`${n}.errors`,e),r.return(!1))}var hn={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function yy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,se._)`{}`:IE(t,e,r)}function IE(t,e,r={}){let{gen:n,it:o}=t,s=[CE(o,r),AE(t,r)];return OE(t,e,s),n.object(...s)}function CE({errorPath:t},{instancePath:e}){let r=e?(0,se.str)`${t}${(0,Wi.getErrorPath)(e,Wi.Type.Str)}`:t;return[Ve.default.instancePath,(0,se.strConcat)(Ve.default.instancePath,r)]}function AE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,se.str)`${e}/${t}`;return r&&(o=(0,se.str)`${o}${(0,Wi.getErrorPath)(r,Wi.Type.Str)}`),[hn.schemaPath,o]}function OE(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([hn.keyword,o],[hn.params,typeof e=="function"?e(t):e||(0,se._)`{}`]),c.messages&&n.push([hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([hn.schema,i],[hn.parentSchema,(0,se._)`${l}${d}`],[Ve.default.data,s]),u&&n.push([hn.propertyName,u])}});var vy=z(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.boolOrEmptySchema=Gn.topBoolOrEmptySchema=void 0;var NE=is(),ME=W(),jE=sr(),ZE={message:"boolean schema is false"};function DE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?_y(t,!1):typeof r=="object"&&r.$async===!0?e.return(jE.default.data):(e.assign((0,ME._)`${n}.errors`,null),e.return(!0))}Gn.topBoolOrEmptySchema=DE;function LE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),_y(t)):r.var(e,!0)}Gn.boolOrEmptySchema=LE;function _y(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,NE.reportError)(o,ZE,void 0,e)}});var wd=z(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.getRules=Xn.isJSONType=void 0;var qE=["string","number","integer","boolean","null","object","array"],FE=new Set(qE);function UE(t){return typeof t=="string"&&FE.has(t)}Xn.isJSONType=UE;function HE(){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:{}}}Xn.getRules=HE});var $d=z(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.shouldUseRule=Sr.shouldUseGroup=Sr.schemaHasRulesForType=void 0;function BE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&xy(t,n)}Sr.schemaHasRulesForType=BE;function xy(t,e){return e.rules.some(r=>by(t,r))}Sr.shouldUseGroup=xy;function by(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))}Sr.shouldUseRule=by});var as=z(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var VE=wd(),JE=$d(),WE=is(),V=W(),wy=oe(),Yn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Yn||(Le.DataType=Yn={}));function KE(t){let e=$y(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}Le.getSchemaTypes=KE;function $y(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(VE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=$y;function GE(t,e){let{gen:r,data:n,opts:o}=t,s=XE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,JE.schemaHasRulesForType)(t,e[0]));if(i){let a=Sd(e,n,o.strictNumbers,Yn.Wrong);r.if(a,()=>{s.length?YE(t,e,s):Td(t)})}return i}Le.coerceAndCheckDataType=GE;var ky=new Set(["string","number","integer","boolean","null"]);function XE(t,e){return e?t.filter(r=>ky.has(r)||e==="array"&&r==="array"):[]}function YE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,V._)`typeof ${o}`),a=n.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&n.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(Sd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,V._)`${a} !== undefined`);for(let u of r)(ky.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Td(t),n.endIf(),n.if((0,V._)`${a} !== undefined`,()=>{n.assign(o,a),QE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${i} == "boolean" || ${o} === null
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 p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){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 m=this.seen.get(l),p=m.def??m.schema,f={...p};if(m.ref===null)return;let g=m.ref;if(m.ref=null,g){a(g,d);let h=this.seen.get(g).schema;h.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(h)):(Object.assign(p,h),Object.assign(p,f))}m.isParent||this.override({zodSchema:l,jsonSchema:p,path:m.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 jh=X(()=>{});var He=X(()=>{Dn();jc();Pc();Sh();Qs();Fc();qt();Ys();si();Cu();Uc();Nh();Oh();Mh();jh()});var bl=X(()=>{He()});var Uo={};To(Uo,{ZodISODate:()=>qh,ZodISODateTime:()=>Lh,ZodISODuration:()=>Fh,ZodISOTime:()=>Uh,date:()=>$l,datetime:()=>wl,duration:()=>Sl,time:()=>kl});function wl(t){return Rh(Lh,t)}function $l(t){return Ph(qh,t)}function kl(t){return Ih(Uh,t)}function Sl(t){return Ch(Fh,t)}var Lh,qh,Uh,Fh,Tl=X(()=>{He();El();Lh=w("ZodISODateTime",(t,e)=>{xh.init(t,e),be.init(t,e)});qh=w("ZodISODate",(t,e)=>{bh.init(t,e),be.init(t,e)});Uh=w("ZodISOTime",(t,e)=>{wh.init(t,e),be.init(t,e)});Fh=w("ZodISODuration",(t,e)=>{$h.init(t,e),be.init(t,e)})});var Hh,mZ,Fo,zl=X(()=>{He();He();Hh=(t,e)=>{Gs.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Rc(t,r)},flatten:{value:r=>zc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},mZ=w("ZodError",Hh),Fo=w("ZodError",Hh,{Parent:Error})});var Bh,Vh,Jh,Wh,Rl=X(()=>{He();zl();Bh=Ic(Fo),Vh=Ac(Fo),Jh=Nc(Fo),Wh=Mc(Fo)});function b(t){return Au(Dk,t)}function ue(t){return tl(Qh,t)}function Gh(t){return rl(nS,t)}function Pe(t){return nl(oS,t)}function eg(t){return ol(sS,t)}function we(){return sl(iS)}function cS(t){return il(aS,t)}function te(t,e){return Ah(uS,t,e)}function I(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new tg(r)}function Be(t,e){return new tg({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:we(),...ee.normalizeParams(e)})}function ye(t,e){return new rg({type:"union",options:t,...ee.normalizeParams(e)})}function Cl(t,e,r){return new lS({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}function gi(t,e){return new dS({type:"intersection",left:t,right:e})}function ge(t,e,r){return new fS({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Pl({type:"enum",entries:r,...ee.normalizeParams(e)})}function j(t,e){return new pS({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}function ng(t){return new mS({type:"transform",transform:t})}function $e(t){return new og({type:"optional",innerType:t})}function Xh(t){return new hS({type:"nullable",innerType:t})}function yS(t,e){return new gS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function vS(t,e){return new _S({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function xS(t,e){return new sg({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}function wS(t,e){return new bS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Il(t,e){return new $S({type:"pipe",in:t,out:e})}function SS(t){return new kS({type:"readonly",innerType:t})}function TS(t){let e=new Ce({check:"custom"});return e._zod.check=t,e}function ag(t,e){return yl(ig,t??(()=>!0),e)}function ES(t,e={}){return _l(ig,t,e)}function zS(t){let e=TS(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ee.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(ee.issue(o))}},t(r.value,r)));return e}function Al(t,e){return Il(ng(t),e)}var Se,Yh,Dk,be,Lk,Kh,hi,qk,Uk,Fk,Hk,Bk,Vk,Jk,Wk,Kk,Gk,Xk,Yk,Qk,eS,tS,rS,Qh,nS,oS,sS,iS,aS,uS,tg,rg,lS,dS,fS,Pl,pS,mS,og,hS,gS,_S,sg,bS,$S,kS,ig,El=X(()=>{He();He();bl();Tl();Rl();Se=w("ZodType",(t,e)=>(le.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)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Bh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Jh(t,r,n),t.parseAsync=async(r,n)=>Vh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(ES(r,n)),t.superRefine=r=>t.check(zS(r)),t.overwrite=r=>t.check(ln(r)),t.optional=()=>$e(t),t.nullable=()=>Xh(t),t.nullish=()=>$e(Xh(t)),t.nonoptional=r=>xS(t,r),t.array=()=>te(t),t.or=r=>ye([t,r]),t.and=r=>gi(t,r),t.transform=r=>Il(t,ng(r)),t.default=r=>yS(t,r),t.prefault=r=>vS(t,r),t.catch=r=>wS(t,r),t.pipe=r=>Il(t,r),t.readonly=()=>SS(t),t.describe=r=>{let n=t.clone();return br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return br.get(t);let n=t.clone();return br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Yh=w("_ZodString",(t,e)=>{Zo.init(t,e),Se.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(al(...n)),t.includes=(...n)=>t.check(ll(...n)),t.startsWith=(...n)=>t.check(dl(...n)),t.endsWith=(...n)=>t.check(fl(...n)),t.min=(...n)=>t.check(Un(...n)),t.max=(...n)=>t.check(li(...n)),t.length=(...n)=>t.check(di(...n)),t.nonempty=(...n)=>t.check(Un(1,...n)),t.lowercase=n=>t.check(cl(n)),t.uppercase=n=>t.check(ul(n)),t.trim=()=>t.check(ml()),t.normalize=(...n)=>t.check(pl(...n)),t.toLowerCase=()=>t.check(hl()),t.toUpperCase=()=>t.check(gl())}),Dk=w("ZodString",(t,e)=>{Zo.init(t,e),Yh.init(t,e),t.email=r=>t.check(Ou(Lk,r)),t.url=r=>t.check(Du(qk,r)),t.jwt=r=>t.check(el(rS,r)),t.emoji=r=>t.check(Lu(Uk,r)),t.guid=r=>t.check(ii(Kh,r)),t.uuid=r=>t.check(Nu(hi,r)),t.uuidv4=r=>t.check(Mu(hi,r)),t.uuidv6=r=>t.check(ju(hi,r)),t.uuidv7=r=>t.check(Zu(hi,r)),t.nanoid=r=>t.check(qu(Fk,r)),t.guid=r=>t.check(ii(Kh,r)),t.cuid=r=>t.check(Uu(Hk,r)),t.cuid2=r=>t.check(Fu(Bk,r)),t.ulid=r=>t.check(Hu(Vk,r)),t.base64=r=>t.check(Xu(Qk,r)),t.base64url=r=>t.check(Yu(eS,r)),t.xid=r=>t.check(Bu(Jk,r)),t.ksuid=r=>t.check(Vu(Wk,r)),t.ipv4=r=>t.check(Ju(Kk,r)),t.ipv6=r=>t.check(Wu(Gk,r)),t.cidrv4=r=>t.check(Ku(Xk,r)),t.cidrv6=r=>t.check(Gu(Yk,r)),t.e164=r=>t.check(Qu(tS,r)),t.datetime=r=>t.check(wl(r)),t.date=r=>t.check($l(r)),t.time=r=>t.check(kl(r)),t.duration=r=>t.check(Sl(r))});be=w("ZodStringFormat",(t,e)=>{he.init(t,e),Yh.init(t,e)}),Lk=w("ZodEmail",(t,e)=>{Jc.init(t,e),be.init(t,e)}),Kh=w("ZodGUID",(t,e)=>{Bc.init(t,e),be.init(t,e)}),hi=w("ZodUUID",(t,e)=>{Vc.init(t,e),be.init(t,e)}),qk=w("ZodURL",(t,e)=>{Wc.init(t,e),be.init(t,e)}),Uk=w("ZodEmoji",(t,e)=>{Kc.init(t,e),be.init(t,e)}),Fk=w("ZodNanoID",(t,e)=>{Gc.init(t,e),be.init(t,e)}),Hk=w("ZodCUID",(t,e)=>{Xc.init(t,e),be.init(t,e)}),Bk=w("ZodCUID2",(t,e)=>{Yc.init(t,e),be.init(t,e)}),Vk=w("ZodULID",(t,e)=>{Qc.init(t,e),be.init(t,e)}),Jk=w("ZodXID",(t,e)=>{eu.init(t,e),be.init(t,e)}),Wk=w("ZodKSUID",(t,e)=>{tu.init(t,e),be.init(t,e)}),Kk=w("ZodIPv4",(t,e)=>{ru.init(t,e),be.init(t,e)}),Gk=w("ZodIPv6",(t,e)=>{nu.init(t,e),be.init(t,e)}),Xk=w("ZodCIDRv4",(t,e)=>{ou.init(t,e),be.init(t,e)}),Yk=w("ZodCIDRv6",(t,e)=>{su.init(t,e),be.init(t,e)}),Qk=w("ZodBase64",(t,e)=>{iu.init(t,e),be.init(t,e)}),eS=w("ZodBase64URL",(t,e)=>{au.init(t,e),be.init(t,e)}),tS=w("ZodE164",(t,e)=>{cu.init(t,e),be.init(t,e)}),rS=w("ZodJWT",(t,e)=>{uu.init(t,e),be.init(t,e)}),Qh=w("ZodNumber",(t,e)=>{ri.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ci(n,o)),t.gte=(n,o)=>t.check(qo(n,o)),t.min=(n,o)=>t.check(qo(n,o)),t.lt=(n,o)=>t.check(ai(n,o)),t.lte=(n,o)=>t.check(Lo(n,o)),t.max=(n,o)=>t.check(Lo(n,o)),t.int=n=>t.check(Gh(n)),t.safe=n=>t.check(Gh(n)),t.positive=n=>t.check(ci(0,n)),t.nonnegative=n=>t.check(qo(0,n)),t.negative=n=>t.check(ai(0,n)),t.nonpositive=n=>t.check(Lo(0,n)),t.multipleOf=(n,o)=>t.check(ui(n,o)),t.step=(n,o)=>t.check(ui(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});nS=w("ZodNumberFormat",(t,e)=>{lu.init(t,e),Qh.init(t,e)});oS=w("ZodBoolean",(t,e)=>{du.init(t,e),Se.init(t,e)});sS=w("ZodNull",(t,e)=>{fu.init(t,e),Se.init(t,e)});iS=w("ZodUnknown",(t,e)=>{pu.init(t,e),Se.init(t,e)});aS=w("ZodNever",(t,e)=>{mu.init(t,e),Se.init(t,e)});uS=w("ZodArray",(t,e)=>{hu.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Un(r,n)),t.nonempty=r=>t.check(Un(1,r)),t.max=(r,n)=>t.check(li(r,n)),t.length=(r,n)=>t.check(di(r,n)),t.unwrap=()=>t.element});tg=w("ZodObject",(t,e)=>{ni.init(t,e),Se.init(t,e),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:we()}),t.loose=()=>t.clone({...t._zod.def,catchall:we()}),t.strict=()=>t.clone({...t._zod.def,catchall:cS()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(og,t,r[0]),t.required=(...r)=>ee.required(sg,t,r[0])});rg=w("ZodUnion",(t,e)=>{oi.init(t,e),Se.init(t,e),t.options=e.options});lS=w("ZodDiscriminatedUnion",(t,e)=>{rg.init(t,e),gu.init(t,e)});dS=w("ZodIntersection",(t,e)=>{yu.init(t,e),Se.init(t,e)});fS=w("ZodRecord",(t,e)=>{_u.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Pl=w("ZodEnum",(t,e)=>{vu.init(t,e),Se.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 Pl({...e,checks:[],...ee.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 Pl({...e,checks:[],...ee.normalizeParams(o),entries:s})}});pS=w("ZodLiteral",(t,e)=>{xu.init(t,e),Se.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]}})});mS=w("ZodTransform",(t,e)=>{bu.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ee.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(ee.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});og=w("ZodOptional",(t,e)=>{wu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});hS=w("ZodNullable",(t,e)=>{$u.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});gS=w("ZodDefault",(t,e)=>{ku.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});_S=w("ZodPrefault",(t,e)=>{Su.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});sg=w("ZodNonOptional",(t,e)=>{Tu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});bS=w("ZodCatch",(t,e)=>{Eu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});$S=w("ZodPipe",(t,e)=>{zu.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});kS=w("ZodReadonly",(t,e)=>{Ru.init(t,e),Se.init(t,e)});ig=w("ZodCustom",(t,e)=>{Pu.init(t,e),Se.init(t,e)})});var cg=X(()=>{});var ug=X(()=>{});var lg=X(()=>{He();El();bl();zl();Rl();cg();He();Eh();si();Tl();ug();at(Th())});var dg=X(()=>{lg()});var fg=X(()=>{dg()});function Eg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Nl,pg,Vn,kr,_i,ze,mg,hg,PZ,IS,CS,Ml,ut,Ho,gg,Ae,pt,mt,Oe,vi,yg,nr,_g,vg,jl,or,O,Zl,Jn,Bo,IZ,xi,AS,bi,OS,Vo,Bn,xg,NS,MS,jS,ZS,DS,LS,wi,Dl,qS,US,Ll,$i,FS,HS,ki,BS,Jo,Wo,VS,Ko,Wn,JS,Go,Si,Ti,Ei,CZ,zi,Ri,Pi,bg,wg,$g,ql,kg,Xo,Kn,Sg,WS,Ii,KS,Ci,GS,Ul,XS,Ai,YS,QS,eT,tT,rT,nT,oT,sT,iT,aT,Oi,cT,uT,Ni,Fl,Hl,Bl,lT,dT,fT,Vl,pT,mT,hT,gT,yT,Tg,Mi,_T,ji,AZ,vT,Gn,xT,OZ,Yo,bT,Jl,wT,$T,kT,ST,TT,ET,zT,yi,RT,PT,IT,Qo,Wl,CT,AT,OT,NT,MT,jT,ZT,DT,LT,qT,UT,FT,HT,BT,VT,JT,WT,KT,Xn,GT,XT,YT,Zi,QT,eE,tE,Kl,rE,NZ,MZ,jZ,ZZ,DZ,LZ,C,Ol,Sr=X(()=>{fg();Nl="2025-11-25",pg="2025-03-26",Vn=[Nl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],kr="io.modelcontextprotocol/related-task",_i="2.0",ze=ag(t=>t!==null&&(typeof t=="object"||typeof t=="function")),mg=ye([b(),ue().int()]),hg=b(),PZ=Be({ttl:ue().optional(),pollInterval:ue().optional()}),IS=I({ttl:ue().optional()}),CS=I({taskId:b()}),Ml=Be({progressToken:mg.optional(),[kr]:CS.optional()}),ut=I({_meta:Ml.optional()}),Ho=ut.extend({task:IS.optional()}),gg=t=>Ho.safeParse(t).success,Ae=I({method:b(),params:ut.loose().optional()}),pt=I({_meta:Ml.optional()}),mt=I({method:b(),params:pt.loose().optional()}),Oe=Be({_meta:Ml.optional()}),vi=ye([b(),ue().int()]),yg=I({jsonrpc:j(_i),id:vi,...Ae.shape}).strict(),nr=t=>yg.safeParse(t).success,_g=I({jsonrpc:j(_i),...mt.shape}).strict(),vg=t=>_g.safeParse(t).success,jl=I({jsonrpc:j(_i),id:vi,result:Oe}).strict(),or=t=>jl.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"})(O||(O={}));Zl=I({jsonrpc:j(_i),id:vi.optional(),error:I({code:ue().int(),message:b(),data:we().optional()})}).strict(),Jn=t=>Zl.safeParse(t).success,Bo=ye([yg,_g,jl,Zl]),IZ=ye([jl,Zl]),xi=Oe.strict(),AS=pt.extend({requestId:vi.optional(),reason:b().optional()}),bi=mt.extend({method:j("notifications/cancelled"),params:AS}),OS=I({src:b(),mimeType:b().optional(),sizes:te(b()).optional(),theme:et(["light","dark"]).optional()}),Vo=I({icons:te(OS).optional()}),Bn=I({name:b(),title:b().optional()}),xg=Bn.extend({...Bn.shape,...Vo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),NS=gi(I({applyDefaults:Pe().optional()}),ge(b(),we())),MS=Al(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,gi(I({form:NS.optional(),url:ze.optional()}),ge(b(),we()).optional())),jS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({sampling:Be({createMessage:ze.optional()}).optional(),elicitation:Be({create:ze.optional()}).optional()}).optional()}),ZS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({tools:Be({call:ze.optional()}).optional()}).optional()}),DS=I({experimental:ge(b(),ze).optional(),sampling:I({context:ze.optional(),tools:ze.optional()}).optional(),elicitation:MS.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:jS.optional(),extensions:ge(b(),ze).optional()}),LS=ut.extend({protocolVersion:b(),capabilities:DS,clientInfo:xg}),wi=Ae.extend({method:j("initialize"),params:LS}),Dl=t=>wi.safeParse(t).success,qS=I({experimental:ge(b(),ze).optional(),logging:ze.optional(),completions:ze.optional(),prompts:I({listChanged:Pe().optional()}).optional(),resources:I({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:I({listChanged:Pe().optional()}).optional(),tasks:ZS.optional(),extensions:ge(b(),ze).optional()}),US=Oe.extend({protocolVersion:b(),capabilities:qS,serverInfo:xg,instructions:b().optional()}),Ll=mt.extend({method:j("notifications/initialized"),params:pt.optional()}),$i=Ae.extend({method:j("ping"),params:ut.optional()}),FS=I({progress:ue(),total:$e(ue()),message:$e(b())}),HS=I({...pt.shape,...FS.shape,progressToken:mg}),ki=mt.extend({method:j("notifications/progress"),params:HS}),BS=ut.extend({cursor:hg.optional()}),Jo=Ae.extend({params:BS.optional()}),Wo=Oe.extend({nextCursor:hg.optional()}),VS=et(["working","input_required","completed","failed","cancelled"]),Ko=I({taskId:b(),status:VS,ttl:ye([ue(),eg()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:$e(ue()),statusMessage:$e(b())}),Wn=Oe.extend({task:Ko}),JS=pt.merge(Ko),Go=mt.extend({method:j("notifications/tasks/status"),params:JS}),Si=Ae.extend({method:j("tasks/get"),params:ut.extend({taskId:b()})}),Ti=Oe.merge(Ko),Ei=Ae.extend({method:j("tasks/result"),params:ut.extend({taskId:b()})}),CZ=Oe.loose(),zi=Jo.extend({method:j("tasks/list")}),Ri=Wo.extend({tasks:te(Ko)}),Pi=Ae.extend({method:j("tasks/cancel"),params:ut.extend({taskId:b()})}),bg=Oe.merge(Ko),wg=I({uri:b(),mimeType:$e(b()),_meta:ge(b(),we()).optional()}),$g=wg.extend({text:b()}),ql=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),kg=wg.extend({blob:ql}),Xo=et(["user","assistant"]),Kn=I({audience:te(Xo).optional(),priority:ue().min(0).max(1).optional(),lastModified:Uo.datetime({offset:!0}).optional()}),Sg=I({...Bn.shape,...Vo.shape,uri:b(),description:$e(b()),mimeType:$e(b()),size:$e(ue()),annotations:Kn.optional(),_meta:$e(Be({}))}),WS=I({...Bn.shape,...Vo.shape,uriTemplate:b(),description:$e(b()),mimeType:$e(b()),annotations:Kn.optional(),_meta:$e(Be({}))}),Ii=Jo.extend({method:j("resources/list")}),KS=Wo.extend({resources:te(Sg)}),Ci=Jo.extend({method:j("resources/templates/list")}),GS=Wo.extend({resourceTemplates:te(WS)}),Ul=ut.extend({uri:b()}),XS=Ul,Ai=Ae.extend({method:j("resources/read"),params:XS}),YS=Oe.extend({contents:te(ye([$g,kg]))}),QS=mt.extend({method:j("notifications/resources/list_changed"),params:pt.optional()}),eT=Ul,tT=Ae.extend({method:j("resources/subscribe"),params:eT}),rT=Ul,nT=Ae.extend({method:j("resources/unsubscribe"),params:rT}),oT=pt.extend({uri:b()}),sT=mt.extend({method:j("notifications/resources/updated"),params:oT}),iT=I({name:b(),description:$e(b()),required:$e(Pe())}),aT=I({...Bn.shape,...Vo.shape,description:$e(b()),arguments:$e(te(iT)),_meta:$e(Be({}))}),Oi=Jo.extend({method:j("prompts/list")}),cT=Wo.extend({prompts:te(aT)}),uT=ut.extend({name:b(),arguments:ge(b(),b()).optional()}),Ni=Ae.extend({method:j("prompts/get"),params:uT}),Fl=I({type:j("text"),text:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),Hl=I({type:j("image"),data:ql,mimeType:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),Bl=I({type:j("audio"),data:ql,mimeType:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),lT=I({type:j("tool_use"),name:b(),id:b(),input:ge(b(),we()),_meta:ge(b(),we()).optional()}),dT=I({type:j("resource"),resource:ye([$g,kg]),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),fT=Sg.extend({type:j("resource_link")}),Vl=ye([Fl,Hl,Bl,fT,dT]),pT=I({role:Xo,content:Vl}),mT=Oe.extend({description:b().optional(),messages:te(pT)}),hT=mt.extend({method:j("notifications/prompts/list_changed"),params:pt.optional()}),gT=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),yT=I({taskSupport:et(["required","optional","forbidden"]).optional()}),Tg=I({...Bn.shape,...Vo.shape,description:b().optional(),inputSchema:I({type:j("object"),properties:ge(b(),ze).optional(),required:te(b()).optional()}).catchall(we()),outputSchema:I({type:j("object"),properties:ge(b(),ze).optional(),required:te(b()).optional()}).catchall(we()).optional(),annotations:gT.optional(),execution:yT.optional(),_meta:ge(b(),we()).optional()}),Mi=Jo.extend({method:j("tools/list")}),_T=Wo.extend({tools:te(Tg)}),ji=Oe.extend({content:te(Vl).default([]),structuredContent:ge(b(),we()).optional(),isError:Pe().optional()}),AZ=ji.or(Oe.extend({toolResult:we()})),vT=Ho.extend({name:b(),arguments:ge(b(),we()).optional()}),Gn=Ae.extend({method:j("tools/call"),params:vT}),xT=mt.extend({method:j("notifications/tools/list_changed"),params:pt.optional()}),OZ=I({autoRefresh:Pe().default(!0),debounceMs:ue().int().nonnegative().default(300)}),Yo=et(["debug","info","notice","warning","error","critical","alert","emergency"]),bT=ut.extend({level:Yo}),Jl=Ae.extend({method:j("logging/setLevel"),params:bT}),wT=pt.extend({level:Yo,logger:b().optional(),data:we()}),$T=mt.extend({method:j("notifications/message"),params:wT}),kT=I({name:b().optional()}),ST=I({hints:te(kT).optional(),costPriority:ue().min(0).max(1).optional(),speedPriority:ue().min(0).max(1).optional(),intelligencePriority:ue().min(0).max(1).optional()}),TT=I({mode:et(["auto","required","none"]).optional()}),ET=I({type:j("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:te(Vl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:ge(b(),we()).optional()}),zT=Cl("type",[Fl,Hl,Bl]),yi=Cl("type",[Fl,Hl,Bl,lT,ET]),RT=I({role:Xo,content:ye([yi,te(yi)]),_meta:ge(b(),we()).optional()}),PT=Ho.extend({messages:te(RT),modelPreferences:ST.optional(),systemPrompt:b().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:ue().optional(),maxTokens:ue().int(),stopSequences:te(b()).optional(),metadata:ze.optional(),tools:te(Tg).optional(),toolChoice:TT.optional()}),IT=Ae.extend({method:j("sampling/createMessage"),params:PT}),Qo=Oe.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens"]).or(b())),role:Xo,content:zT}),Wl=Oe.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Xo,content:ye([yi,te(yi)])}),CT=I({type:j("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),AT=I({type:j("string"),title:b().optional(),description:b().optional(),minLength:ue().optional(),maxLength:ue().optional(),format:et(["email","uri","date","date-time"]).optional(),default:b().optional()}),OT=I({type:et(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ue().optional(),maximum:ue().optional(),default:ue().optional()}),NT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),default:b().optional()}),MT=I({type:j("string"),title:b().optional(),description:b().optional(),oneOf:te(I({const:b(),title:b()})),default:b().optional()}),jT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),enumNames:te(b()).optional(),default:b().optional()}),ZT=ye([NT,MT]),DT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:I({type:j("string"),enum:te(b())}),default:te(b()).optional()}),LT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:I({anyOf:te(I({const:b(),title:b()}))}),default:te(b()).optional()}),qT=ye([DT,LT]),UT=ye([jT,ZT,qT]),FT=ye([UT,CT,AT,OT]),HT=Ho.extend({mode:j("form").optional(),message:b(),requestedSchema:I({type:j("object"),properties:ge(b(),FT),required:te(b()).optional()})}),BT=Ho.extend({mode:j("url"),message:b(),elicitationId:b(),url:b().url()}),VT=ye([HT,BT]),JT=Ae.extend({method:j("elicitation/create"),params:VT}),WT=pt.extend({elicitationId:b()}),KT=mt.extend({method:j("notifications/elicitation/complete"),params:WT}),Xn=Oe.extend({action:et(["accept","decline","cancel"]),content:Al(t=>t===null?void 0:t,ge(b(),ye([b(),ue(),Pe(),te(b())])).optional())}),GT=I({type:j("ref/resource"),uri:b()}),XT=I({type:j("ref/prompt"),name:b()}),YT=ut.extend({ref:ye([XT,GT]),argument:I({name:b(),value:b()}),context:I({arguments:ge(b(),b()).optional()}).optional()}),Zi=Ae.extend({method:j("completion/complete"),params:YT});QT=Oe.extend({completion:Be({values:te(b()).max(100),total:$e(ue().int()),hasMore:$e(Pe())})}),eE=I({uri:b().startsWith("file://"),name:b().optional(),_meta:ge(b(),we()).optional()}),tE=Ae.extend({method:j("roots/list"),params:ut.optional()}),Kl=Oe.extend({roots:te(eE)}),rE=mt.extend({method:j("notifications/roots/list_changed"),params:pt.optional()}),NZ=ye([$i,wi,Zi,Jl,Ni,Oi,Ii,Ci,Ai,tT,nT,Gn,Mi,Si,Ei,zi,Pi]),MZ=ye([bi,ki,Ll,rE,Go]),jZ=ye([xi,Qo,Wl,Xn,Kl,Ti,Ri,Wn]),ZZ=ye([$i,IT,JT,tE,Si,Ei,zi,Pi]),DZ=ye([bi,ki,$T,sT,QS,xT,hT,Go,KT]),LZ=ye([xi,US,QT,mT,cT,KS,GS,YS,ji,_T,Ti,Ri,Wn]),C=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===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ol(o.elicitations,r)}return new t(e,r,n)}},Ol=class extends C{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var ns=z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var ts=class{};ie._CodeOrName=ts;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends ts{constructor(e){if(super(),!ie.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}}};ie.Name=pn;var ht=class extends ts{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 pn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ie._Code=ht;ie.nil=new ht("");function uy(t,...e){let r=[t[0]],n=0;for(;n<e.length;)sd(r,e[n]),r.push(t[++n]);return new ht(r)}ie._=uy;var od=new ht("+");function ly(t,...e){let r=[rs(t[0])],n=0;for(;n<e.length;)r.push(od),sd(r,e[n]),r.push(od,rs(t[++n]));return pE(r),new ht(r)}ie.str=ly;function sd(t,e){e instanceof ht?t.push(...e._items):e instanceof pn?t.push(e):t.push(gE(e))}ie.addCodeArg=sd;function pE(t){let e=1;for(;e<t.length-1;){if(t[e]===od){let r=mE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function mE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof pn||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 pn))return`"${t}${e.slice(1)}`}function hE(t,e){return e.emptyStr()?t:t.emptyStr()?e:ly`${t}${e}`}ie.strConcat=hE;function gE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:rs(Array.isArray(t)?t.join(","):t)}function yE(t){return new ht(rs(t))}ie.stringify=yE;function rs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=rs;function _E(t){return typeof t=="string"&&ie.IDENTIFIER.test(t)?new ht(`.${t}`):uy`[${t}]`}ie.getProperty=_E;function vE(t){if(typeof t=="string"&&ie.IDENTIFIER.test(t))return new ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ie.getEsmExportName=vE;function xE(t){return new ht(t.toString())}ie.regexpCode=xE});var cd=z(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.ValueScope=rt.ValueScopeName=rt.Scope=rt.varKinds=rt.UsedValueState=void 0;var tt=ns(),id=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Hi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Hi||(rt.UsedValueState=Hi={}));rt.varKinds={const:new tt.Name("const"),let:new tt.Name("let"),var:new tt.Name("var")};var Bi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof tt.Name?e:this.name(e)}name(e){return new tt.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}}};rt.Scope=Bi;var Vi=class extends tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,tt._)`.${new tt.Name(r)}[${n}]`}};rt.ValueScopeName=Vi;var bE=(0,tt._)`\n`,ad=class extends Bi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?bE:tt.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,tt._)`${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=tt.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,Hi.Started);let l=r(u);if(l){let d=this.opts.es5?rt.varKinds.var:rt.varKinds.const;s=(0,tt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,tt._)`${s}${l}${this.opts._n}`;else throw new id(u);c.set(u,Hi.Completed)})}return s}};rt.ValueScope=ad});var W=z(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 ne=ns(),zt=cd(),Er=ns();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return Er.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return Er.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return Er.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return Er.Name}});var Gi=cd();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Gi.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Gi.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Gi.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Gi.varKinds}});K.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var sr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ud=class extends sr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?zt.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=Qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},Ji=class extends sr{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Ki(e,this.rhs)}},ld=class extends Ji{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},dd=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},fd=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},pd=class extends sr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},md=class extends sr{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=Qn(this.code,e,r),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},os=class extends sr{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)||(wE(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>gn(e,r.names),{})}},ir=class extends os{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hd=class extends os{},Yn=class extends ir{};Yn.kind="else";var mn=class t extends ir{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 Yn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(dy(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=Qn(this.condition,e,r),this}get names(){let e=super.names;return Ki(e,this.condition),this.else&&gn(e,this.else.names),e}};mn.kind="if";var hn=class extends ir{};hn.kind="for";var gd=class extends hn{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=Qn(this.iteration,e,r),this}get names(){return gn(super.names,this.iteration.names)}},yd=class extends hn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?zt.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=Ki(super.names,this.from);return Ki(e,this.to)}},Wi=class extends hn{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=Qn(this.iterable,e,r),this}get names(){return gn(super.names,this.iterable.names)}},ss=class extends ir{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)}};ss.kind="func";var is=class extends os{render(e){return"return "+super.render(e)}};is.kind="return";var _d=class extends ir{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&&gn(e,this.catch.names),this.finally&&gn(e,this.finally.names),e}},as=class extends ir{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};as.kind="catch";var cs=class extends ir{render(e){return"finally"+super.render(e)}};cs.kind="finally";var vd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
+ `:""},this._extScope=e,this._scope=new zt.Scope({parent:e}),this._nodes=[new hd]}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 ud(e,s,n)),s}const(e,r,n){return this._def(zt.varKinds.const,e,r,n)}let(e,r,n){return this._def(zt.varKinds.let,e,r,n)}var(e,r,n){return this._def(zt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ji(e,r,n))}add(e,r){return this._leafNode(new ld(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new md(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,ne.addCodeArg)(r,o));return r.push("}"),new ne._Code(r)}if(e,r,n){if(this._blockNode(new mn(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 mn(e))}else(){return this._elseNode(new Yn)}endIf(){return this._endBlockNode(mn,Yn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new gd(e),r)}forRange(e,r,n,o,s=this.opts.es5?zt.varKinds.var:zt.varKinds.let){let i=this._scope.toName(e);return this._for(new yd(s,i,r,n),()=>o(i))}forOf(e,r,n,o=zt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ne.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ne._)`${i}.length`,a=>{this.var(s,(0,ne._)`${i}[${a}]`),n(s)})}return this._for(new Wi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?zt.varKinds.var:zt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Wi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(hn)}label(e){return this._leafNode(new dd(e))}break(e){return this._leafNode(new fd(e))}return(e){let r=new is;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(is)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new _d;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new as(s),r(s)}return n&&(this._currNode=o.finally=new cs,this.code(n)),this._endBlockNode(as,cs)}throw(e){return this._leafNode(new pd(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=ne.nil,n,o){return this._blockNode(new ss(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ss)}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 mn))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=vd;function gn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ki(t,e){return e instanceof ne._CodeOrName?gn(t,e.names):t}function Qn(t,e,r){if(t instanceof ne.Name)return n(t);if(!o(t))return t;return new ne._Code(t._items.reduce((s,i)=>(i instanceof ne.Name&&(i=n(i)),i instanceof ne._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 ne._Code&&s._items.some(i=>i instanceof ne.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function wE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function dy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ne._)`!${xd(t)}`}K.not=dy;var $E=fy(K.operators.AND);function kE(...t){return t.reduce($E)}K.and=kE;var SE=fy(K.operators.OR);function TE(...t){return t.reduce(SE)}K.or=TE;function fy(t){return(e,r)=>e===ne.nil?r:r===ne.nil?e:(0,ne._)`${xd(e)} ${t} ${xd(r)}`}function xd(t){return t instanceof ne.Name?t:(0,ne._)`(${t})`}});var oe=z(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var fe=W(),EE=ns();function zE(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=zE;function RE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hy(t,e),!gy(e,t.self.RULES.all))}G.alwaysValidSchema=RE;function hy(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]||vy(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=hy;function gy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=gy;function PE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=PE;function IE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,fe._)`${r}`}return(0,fe._)`${t}${e}${(0,fe.getProperty)(n)}`}G.schemaRefOrVal=IE;function CE(t){return yy(decodeURIComponent(t))}G.unescapeFragment=CE;function AE(t){return encodeURIComponent(wd(t))}G.escapeFragment=AE;function wd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=wd;function yy(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=yy;function OE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=OE;function py({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof fe.Name?(s instanceof fe.Name?t(o,s,i):e(o,s,i),i):s instanceof fe.Name?(e(o,i,s),s):r(s,i);return a===fe.Name&&!(c instanceof fe.Name)?n(o,c):c}}G.mergeEvaluated={props:py({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,fe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,fe._)`${r} || {}`).code((0,fe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,fe._)`${r} || {}`),$d(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:_y}),items:py({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,fe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,fe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function _y(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,fe._)`{}`);return e!==void 0&&$d(t,r,e),r}G.evaluatedPropsToName=_y;function $d(t,e,r){Object.keys(r).forEach(n=>t.assign((0,fe._)`${e}${(0,fe.getProperty)(n)}`,!0))}G.setEvaluated=$d;var my={};function NE(t,e){return t.scopeValue("func",{ref:e,code:my[e.code]||(my[e.code]=new EE._Code(e.code))})}G.useFunc=NE;var bd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(bd||(G.Type=bd={}));function ME(t,e,r){if(t instanceof fe.Name){let n=e===bd.Num;return r?n?(0,fe._)`"[" + ${t} + "]"`:(0,fe._)`"['" + ${t} + "']"`:n?(0,fe._)`"/" + ${t}`:(0,fe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,fe.getProperty)(t).toString():"/"+wd(t)}G.getErrorPath=ME;function vy(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=vy});var ar=z(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var De=W(),jE={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};kd.default=jE});var us=z(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var se=W(),Xi=oe(),Je=ar();Le.keywordError={message:({keyword:t})=>(0,se.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,se.str)`"${t}" keyword must be ${e} ($data)`:(0,se.str)`"${t}" keyword is invalid ($data)`};function ZE(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=wy(t,e,r);n??(i||a)?xy(s,c):by(o,(0,se._)`[${c}]`)}Le.reportError=ZE;function DE(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=wy(t,e,r);xy(o,a),s||i||by(n,Je.default.vErrors)}Le.reportExtraError=DE;function LE(t,e){t.assign(Je.default.errors,e),t.if((0,se._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,se._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Le.resetErrorsCount=LE;function qE({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,Je.default.errors,a=>{t.const(i,(0,se._)`${Je.default.vErrors}[${a}]`),t.if((0,se._)`${i}.instancePath === undefined`,()=>t.assign((0,se._)`${i}.instancePath`,(0,se.strConcat)(Je.default.instancePath,s.errorPath))),t.assign((0,se._)`${i}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,se._)`${i}.schema`,r),t.assign((0,se._)`${i}.data`,n))})}Le.extendErrors=qE;function xy(t,e){let r=t.const("err",e);t.if((0,se._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,se._)`[${r}]`),(0,se._)`${Je.default.vErrors}.push(${r})`),t.code((0,se._)`${Je.default.errors}++`)}function by(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,se._)`new ${t.ValidationError}(${e})`):(r.assign((0,se._)`${n}.errors`,e),r.return(!1))}var yn={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function wy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,se._)`{}`:UE(t,e,r)}function UE(t,e,r={}){let{gen:n,it:o}=t,s=[FE(o,r),HE(t,r)];return BE(t,e,s),n.object(...s)}function FE({errorPath:t},{instancePath:e}){let r=e?(0,se.str)`${t}${(0,Xi.getErrorPath)(e,Xi.Type.Str)}`:t;return[Je.default.instancePath,(0,se.strConcat)(Je.default.instancePath,r)]}function HE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,se.str)`${e}/${t}`;return r&&(o=(0,se.str)`${o}${(0,Xi.getErrorPath)(r,Xi.Type.Str)}`),[yn.schemaPath,o]}function BE(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([yn.keyword,o],[yn.params,typeof e=="function"?e(t):e||(0,se._)`{}`]),c.messages&&n.push([yn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([yn.schema,i],[yn.parentSchema,(0,se._)`${l}${d}`],[Je.default.data,s]),u&&n.push([yn.propertyName,u])}});var ky=z(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;var VE=us(),JE=W(),WE=ar(),KE={message:"boolean schema is false"};function GE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?$y(t,!1):typeof r=="object"&&r.$async===!0?e.return(WE.default.data):(e.assign((0,JE._)`${n}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=GE;function XE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),$y(t)):r.var(e,!0)}eo.boolOrEmptySchema=XE;function $y(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,VE.reportError)(o,KE,void 0,e)}});var Sd=z(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.getRules=to.isJSONType=void 0;var YE=["string","number","integer","boolean","null","object","array"],QE=new Set(YE);function ez(t){return typeof t=="string"&&QE.has(t)}to.isJSONType=ez;function tz(){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:{}}}to.getRules=tz});var Td=z(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function rz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Sy(t,n)}zr.schemaHasRulesForType=rz;function Sy(t,e){return e.rules.some(r=>Ty(t,r))}zr.shouldUseGroup=Sy;function Ty(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))}zr.shouldUseRule=Ty});var ls=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var nz=Sd(),oz=Td(),sz=us(),V=W(),Ey=oe(),ro;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ro||(qe.DataType=ro={}));function iz(t){let e=zy(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}qe.getSchemaTypes=iz;function zy(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(nz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=zy;function az(t,e){let{gen:r,data:n,opts:o}=t,s=cz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,oz.schemaHasRulesForType)(t,e[0]));if(i){let a=zd(e,n,o.strictNumbers,ro.Wrong);r.if(a,()=>{s.length?uz(t,e,s):Rd(t)})}return i}qe.coerceAndCheckDataType=az;var Ry=new Set(["string","number","integer","boolean","null"]);function cz(t,e){return e?t.filter(r=>Ry.has(r)||e==="array"&&r==="array"):[]}function uz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,V._)`typeof ${o}`),a=n.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&n.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(zd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,V._)`${a} !== undefined`);for(let u of r)(Ry.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Rd(t),n.endIf(),n.if((0,V._)`${a} !== undefined`,()=>{n.assign(o,a),lz(t,a)});function c(u){switch(u){case"string":n.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${i} == "boolean" || ${o} === null
32
32
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,V._)`+${o}`);return;case"integer":n.elseIf((0,V._)`${i} === "boolean" || ${o} === null
33
33
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,V._)`+${o}`);return;case"boolean":n.elseIf((0,V._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,V._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,V._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,V._)`${i} === "string" || ${i} === "number"
34
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function QE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,V._)`${e} !== undefined`,()=>t.assign((0,V._)`${e}[${r}]`,n))}function kd(t,e,r,n=Yn.Correct){let o=n===Yn.Correct?V.operators.EQ:V.operators.NEQ,s;switch(t){case"null":return(0,V._)`${e} ${o} null`;case"array":s=(0,V._)`Array.isArray(${e})`;break;case"object":s=(0,V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,V._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${e} ${o} ${t}`}return n===Yn.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${e} == "number"`,a,r?(0,V._)`isFinite(${e})`:V.nil)}}Le.checkDataType=kd;function Sd(t,e,r,n){if(t.length===1)return kd(t[0],e,r,n);let o,s=(0,wy.toHash)(t);if(s.array&&s.object){let i=(0,V._)`typeof ${e} != "object"`;o=s.null?i:(0,V._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(let i in s)o=(0,V.and)(o,kd(i,e,r,n));return o}Le.checkDataTypes=Sd;var ez={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,V._)`{type: ${t}}`:(0,V._)`{type: ${e}}`};function Td(t){let e=tz(t);(0,WE.reportError)(e,ez)}Le.reportTypeError=Td;function tz(t){let{gen:e,data:r,schema:n}=t,o=(0,wy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Ty=z(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.assignDefaults=void 0;var Qn=W(),rz=oe();function nz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Sy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Sy(t,s,o.default))}Ki.assignDefaults=nz;function Sy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Qn._)`${s}${(0,Qn.getProperty)(e)}`;if(o){(0,rz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Qn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Qn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Qn._)`${a} = ${(0,Qn.stringify)(r)}`)}});var ht=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var ye=W(),Ed=oe(),Tr=sr(),oz=oe();function sz(t,e){let{gen:r,data:n,it:o}=t;r.if(Rd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ye._)`${e}`},!0),t.error()})}de.checkReportMissingProp=sz;function iz({gen:t,data:e,it:{opts:r}},n,o){return(0,ye.or)(...n.map(s=>(0,ye.and)(Rd(t,e,s,r.ownProperties),(0,ye._)`${o} = ${s}`)))}de.checkMissingProp=iz;function az(t,e){t.setParams({missingProperty:e},!0),t.error()}de.reportMissingProp=az;function Ey(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Ey;function zd(t,e,r){return(0,ye._)`${Ey(t)}.call(${e}, ${r})`}de.isOwnProperty=zd;function cz(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} !== undefined`;return n?(0,ye._)`${o} && ${zd(t,e,r)}`:o}de.propertyInData=cz;function Rd(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} === undefined`;return n?(0,ye.or)(o,(0,ye.not)(zd(t,e,r))):o}de.noPropertyInData=Rd;function zy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=zy;function uz(t,e){return zy(e).filter(r=>!(0,Ed.alwaysValidSchema)(t,e[r]))}de.schemaProperties=uz;function lz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ye._)`${t}, ${e}, ${n}${o}`:e,d=[[Tr.default.instancePath,(0,ye.strConcat)(Tr.default.instancePath,s)],[Tr.default.parentData,i.parentData],[Tr.default.parentDataProperty,i.parentDataProperty],[Tr.default.rootData,Tr.default.rootData]];i.opts.dynamicRef&&d.push([Tr.default.dynamicAnchors,Tr.default.dynamicAnchors]);let m=(0,ye._)`${l}, ${r.object(...d)}`;return c!==ye.nil?(0,ye._)`${a}.call(${c}, ${m})`:(0,ye._)`${a}(${m})`}de.callValidateCode=lz;var dz=(0,ye._)`new RegExp`;function fz({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,ye._)`${o.code==="new RegExp"?dz:(0,oz.useFunc)(t,o)}(${r}, ${n})`})}de.usePattern=fz;function pz(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,ye._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ed.Type.Num},s),e.if((0,ye.not)(s),a)})}}de.validateArray=pz;function mz(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,Ed.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,ye._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ye.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}de.validateUnion=mz});var Iy=z(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.validateKeywordUsage=Lt.validSchemaType=Lt.funcKeywordCode=Lt.macroKeywordCode=void 0;var Je=W(),gn=sr(),hz=ht(),gz=is();function yz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Py(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Je.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Lt.macroKeywordCode=yz;function _z(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;xz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Py(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)g(),e.modifying&&Ry(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&Ry(t),h(()=>vz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Je._)`await `),v=>n.assign(d,!1).if((0,Je._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Je._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Je._)`${l}.errors`;return n.assign(_,null),g(Je.nil),_}function g(_=e.async?(0,Je._)`await `:Je.nil){let v=c.opts.passContext?gn.default.this:gn.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Je._)`${_}${(0,hz.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,Je.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Lt.funcKeywordCode=_z;function Ry(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Je._)`${n.parentData}[${n.parentDataProperty}]`))}function vz(t,e){let{gen:r}=t;r.if((0,Je._)`Array.isArray(${e})`,()=>{r.assign(gn.default.vErrors,(0,Je._)`${gn.default.vErrors} === null ? ${e} : ${gn.default.vErrors}.concat(${e})`).assign(gn.default.errors,(0,Je._)`${gn.default.vErrors}.length`),(0,gz.extendErrors)(t)},()=>t.error())}function xz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Py(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,Je.stringify)(r)})}function bz(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")}Lt.validSchemaType=bz;function wz({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)}}Lt.validateKeywordUsage=wz});var Ay=z(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.extendSubschemaMode=Er.extendSubschemaData=Er.getSubschema=void 0;var qt=W(),Cy=oe();function $z(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,qt._)`${t.schemaPath}${(0,qt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,qt._)`${t.schemaPath}${(0,qt.getProperty)(e)}${(0,qt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Cy.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')}Er.getSubschema=$z;function kz(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,m=a.let("data",(0,qt._)`${e.data}${(0,qt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,qt.str)`${u}${(0,Cy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,qt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof qt.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]}}Er.extendSubschemaData=kz;function Sz(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}Er.extendSubschemaMode=Sz});var Pd=z((V4,Oy)=>{"use strict";Oy.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 My=z((J4,Ny)=>{"use strict";var zr=Ny.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(){};Gi(e,n,o,t,"",t)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Gi(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 zr.arrayKeywords)for(var m=0;m<d.length;m++)Gi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in zr.propsKeywords){if(d&&typeof d=="object")for(var p in d)Gi(t,e,r,d[p],o+"/"+l+"/"+Tz(p),s,o,l,n,p)}else(l in zr.keywords||t.allKeys&&!(l in zr.skipKeywords))&&Gi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function Tz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var cs=z(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var Ez=oe(),zz=Pd(),Rz=My(),Pz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Iz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Id(t):e?jy(t)<=e:!1}rt.inlineRef=Iz;var Cz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Id(t){for(let e in t){if(Cz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Id)||typeof r=="object"&&Id(r))return!0}return!1}function jy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Pz.has(r)&&(typeof t[r]=="object"&&(0,Ez.eachItem)(t[r],n=>e+=jy(n)),e===1/0))return 1/0}return e}function Zy(t,e="",r){r!==!1&&(e=eo(e));let n=t.parse(e);return Dy(t,n)}rt.getFullPath=Zy;function Dy(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=Dy;var Az=/#\/?$/;function eo(t){return t?t.replace(Az,""):""}rt.normalizeId=eo;function Oz(t,e,r){return r=eo(r),t.resolve(e,r)}rt.resolveUrl=Oz;var Nz=/^[a-z_][-a-z0-9._]*$/i;function Mz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=eo(t[r]||e),s={"":o},i=Zy(n,o,!1),a={},c=new Set;return Rz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let g=i+m,h=s[f];typeof d[r]=="string"&&(h=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=h;function _(y){let x=this.opts.uriResolver.resolve;if(y=eo(h?x(h,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==eo(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!Nz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!zz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=Mz});var ds=z(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.getData=Rr.KeywordCxt=Rr.validateFunctionCode=void 0;var Hy=vy(),Ly=as(),Ad=$d(),Xi=as(),jz=Ty(),ls=Iy(),Cd=Ay(),Z=W(),U=sr(),Zz=cs(),ir=oe(),us=is();function Dz(t){if(Jy(t)&&(Wy(t),Vy(t))){Fz(t);return}By(t,()=>(0,Hy.topBoolOrEmptySchema)(t))}Rr.validateFunctionCode=Dz;function By({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${qy(r,o)}`),qz(t,o),t.code(s)}):t.func(e,(0,Z._)`${U.default.data}, ${Lz(o)}`,n.$async,()=>t.code(qy(r,o)).code(s))}function Lz(t){return(0,Z._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,Z._)`, ${U.default.dynamicAnchors}={}`:Z.nil}}={}`}function qz(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,Z._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,Z._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,Z._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,Z._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,Z._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,Z._)`""`),t.var(U.default.parentData,(0,Z._)`undefined`),t.var(U.default.parentDataProperty,(0,Z._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,Z._)`{}`)})}function Fz(t){let{schema:e,opts:r,gen:n}=t;By(t,()=>{r.$comment&&e.$comment&&Gy(t),Jz(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&Uz(t),Ky(t),Gz(t)})}function Uz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function qy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function Hz(t,e){if(Jy(t)&&(Wy(t),Vy(t))){Bz(t,e);return}(0,Hy.boolOrEmptySchema)(t,e)}function Vy({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 Jy(t){return typeof t.schema!="boolean"}function Bz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Gy(t),Wz(t),Kz(t);let s=n.const("_errs",U.default.errors);Ky(t,s),n.var(e,(0,Z._)`${s} === ${U.default.errors}`)}function Wy(t){(0,ir.checkUnknownRules)(t),Vz(t)}function Ky(t,e){if(t.opts.jtd)return Fy(t,[],!1,e);let r=(0,Ly.getSchemaTypes)(t.schema),n=(0,Ly.coerceAndCheckDataType)(t,r);Fy(t,r,!n,e)}function Vz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Jz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function Wz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Zz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Kz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${U.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Gz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,Z._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,U.default.vErrors),s.unevaluated&&Xz(t),e.return((0,Z._)`${U.default.errors} === 0`))}function Xz({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Fy(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,ir.schemaHasRulesButRef)(s,l))){o.block(()=>Yy(t,"$ref",l.all.$ref.definition));return}c.jtd||Yz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ad.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Xi.checkDataType)(m.type,i,c.strictNumbers)),Uy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Xi.reportTypeError)(t)),o.endIf()):Uy(t,m),a||o.if((0,Z._)`${U.default.errors} === ${n||0}`))}}function Uy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,jz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ad.shouldUseRule)(n,s)&&Yy(t,s.keyword,s.definition,e.type)})}function Yz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Qz(t,e),t.opts.allowUnionTypes||eR(t,e),tR(t,t.dataTypes))}function Qz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Xy(t.dataTypes,r)||Od(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),nR(t,e)}}function eR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Od(t,"use allowUnionTypes to allow union type keyword")}function tR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ad.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>rR(e,i))&&Od(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function rR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Xy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function nR(t,e){let r=[];for(let n of t.dataTypes)Xy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Od(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var Yi=class{constructor(e,r,n){if((0,ls.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,ir.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",Qy(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ls.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",U.default.errors))}result(e,r,n){this.failResult((0,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?us.reportExtraError:us.reportError)(this,this.def.error,r)}$dataError(){(0,us.reportError)(this,this.def.$dataError||us.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,us.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,Xi.checkDataTypes)(c,r,s.opts.strictNumbers,Xi.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,Cd.getSubschema)(this.it,e);(0,Cd.extendSubschemaData)(n,this.it,e),(0,Cd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Hz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ir.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,Z.Name)),!0}};Rr.KeywordCxt=Yi;function Yy(t,e,r,n){let o=new Yi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ls.funcKeywordCode)(o,r):"macro"in r?(0,ls.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ls.funcKeywordCode)(o,r)}var oR=/^\/(?:[^~]|~0|~1)*$/,sR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qy(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!oR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.default.rootData}else{let u=sR.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,Z._)`${s}${(0,Z.getProperty)((0,ir.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Rr.getData=Qy});var Qi=z(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Md.default=Nd});var fs=z(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var jd=cs(),Zd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,jd.resolveUrl)(e,r,n),this.missingSchema=(0,jd.normalizeId)((0,jd.getFullPath)(e,this.missingRef))}};Dd.default=Zd});var ta=z(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.resolveSchema=gt.getCompilingSchema=gt.resolveRef=gt.compileSchema=gt.SchemaEnv=void 0;var Et=W(),iR=Qi(),yn=sr(),zt=cs(),e_=oe(),aR=ds(),to=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,zt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};gt.SchemaEnv=to;function qd(t){let e=t_.call(this,t);if(e)return e;let r=(0,zt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:iR.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,aR.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(yn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${yn.default.self}`,`${yn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:g}=u;p.evaluated={props:f instanceof Et.Name?void 0:f,items:g instanceof Et.Name?void 0:g,dynamicProps:f instanceof Et.Name,dynamicItems:g instanceof Et.Name},p.source&&(p.source.evaluated=(0,Et.stringify)(p.evaluated))}return t.validate=p,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)}}gt.compileSchema=qd;function cR(t,e,r){var n;r=(0,zt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=dR.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 to({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=uR.call(this,s)}gt.resolveRef=cR;function uR(t){return(0,zt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qd.call(this,t)}function t_(t){for(let e of this._compilations)if(lR(e,t))return e}gt.getCompilingSchema=t_;function lR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function dR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ea.call(this,t,e)}function ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,zt._getFullPath)(this.opts.uriResolver,r),o=(0,zt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ld.call(this,r,t);let s=(0,zt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ea.call(this,t,i);return typeof a?.schema!="object"?void 0:Ld.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||qd.call(this,i),s===(0,zt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,zt.resolveUrl)(this.opts.uriResolver,o,u)),new to({schema:a,schemaId:c,root:t,baseId:o})}return Ld.call(this,r,i)}}gt.resolveSchema=ea;var fR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ld(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,e_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!fR.has(a)&&u&&(e=(0,zt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,e_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,zt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new to({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var r_=z((Q4,pR)=>{pR.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 Jd=z((eL,l_)=>{"use strict";var mR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ud=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),hR=RegExp.prototype.test.bind(/^\d*$/u),_n=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Bd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),gR=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),nt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)nt[e]="%"+t[e>>4]+t[e&15]}function qe(t){return t<2048?nt[192|t>>6]+nt[128|t&63]:t<65536?nt[224|t>>12]+nt[128|t>>6&63]+nt[128|t&63]:nt[240|t>>18]+nt[128|t>>12&63]+nt[128|t>>6&63]+nt[128|t&63]}function yR(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 _R=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),vR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),xR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),bR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!xR(t[e])){if(t[e]==="%"&&e+2<t.length&&_n(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function n_(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 $R(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||!Ud(c))return;s+=2;continue}if(!_R(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:n_(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 n_(i)}function Fd(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&&vR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(kR(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),!wR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=$R(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function kR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function s_(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("")}function SR(t){if(t===""||t[0]==="/")return s_(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var TR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ER=/[@/?#:]/g,zR=/[@/?#]/g;function i_(t,e){let r=e?zR:ER;return r.lastIndex=0,t.replace(r,n=>TR[n])}function a_(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Hd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function RR(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Hd(i)?e+=i:e+="%"+s,r+=2;continue}}if(o_(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=u_(o)?n:nt[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function PR(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(_n(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),o_(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=nt[i];else if(i<55296||i>57343)r+=qe(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=qe(65536+(i-55296<<10)+(a-56320)),o++):r+=qe(65533)}else r+=qe(65533)}}return r}function Vd(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(_n(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=nt[s];else if(s<55296||s>57343)r+=qe(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=qe(65536+(s-55296<<10)+(i-56320)),n++):r+=qe(65533)}else r+=qe(65533)}}return r}function c_(t){return Vd(t,gR)}function IR(t){return Vd(t,Bd)}function CR(t){return Vd(t,Bd)}function u_(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 AR(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(_n(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Hd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Bd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=u_(o)?n:nt[o];else if(o<55296||o>57343)e+=qe(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=qe(65536+(o-55296<<10)+(s-56320)),r++):e+=qe(65533)}else e+=qe(65533)}}return e}function OR(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(_n(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function NR(t){let e=[];if(t.userinfo!==void 0&&(e.push(c_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Ud(r)){let n=Fd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=a_(r,!0),n=Fd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=i_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!hR(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}l_.exports={nonSimpleDomain:bR,recomposeAuthority:NR,reescapeHostDelimiters:i_,normalizePercentEncoding:a_,normalizePathEncoding:RR,serializePathEncoding:PR,normalizeQueryFragmentEncoding:AR,encodeUserinfo:c_,encodeQuery:IR,encodeFragment:CR,escapePreservingEscapes:OR,removeDotSegments:s_,removeDotSegmentsRelative:SR,isIPv4:Ud,isUUID:mR,normalizeIPv6:Fd,stringArrayToHexStripped:yR}});var h_=z((tL,m_)=>{"use strict";var{isUUID:MR}=Jd(),jR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,ZR=["http","https","ws","wss","urn","urn:uuid"];function DR(t){return ZR.indexOf(t)!==-1}function Wd(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 d_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function f_(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 LR(t){return t.secure=Wd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function qR(t){if((t.port===(Wd(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 FR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jR);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=Kd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function UR(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=Kd(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 HR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!MR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var p_={scheme:"http",domainHost:!0,parse:d_,serialize:f_},VR={scheme:"https",domainHost:p_.domainHost,parse:d_,serialize:f_},ra={scheme:"ws",domainHost:!0,parse:LR,serialize:qR},JR={scheme:"wss",domainHost:ra.domainHost,parse:ra.parse,serialize:ra.serialize},WR={scheme:"urn",parse:FR,serialize:UR,skipNormalize:!0},KR={scheme:"urn:uuid",parse:HR,serialize:BR,skipNormalize:!0},na={http:p_,https:VR,ws:ra,wss:JR,urn:WR,"urn:uuid":KR};Object.setPrototypeOf(na,null);function Kd(t){return t&&(na[t]||na[t.toLowerCase()])||void 0}m_.exports={wsIsSecure:Wd,SCHEMES:na,isValidSchemeName:DR,getSchemeHandler:Kd}});var P_=z((rL,ca)=>{"use strict";var{normalizeIPv6:x_,removeDotSegments:ms,removeDotSegmentsRelative:b_,recomposeAuthority:GR,normalizePercentEncoding:Gd,normalizePathEncoding:XR,serializePathEncoding:g_,normalizeQueryFragmentEncoding:y_,encodeQuery:YR,encodeFragment:QR,reescapeHostDelimiters:eP,isIPv4:w_,nonSimpleDomain:tP}=Jd(),{SCHEMES:$_,getSchemeHandler:Xd}=h_(),k_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,S_="URI scheme is malformed.",oa="URI host is malformed.",rP=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function __(t){let e=String(t);if(!k_.test(e))throw new TypeError(S_);return e}function nP(t,e){return typeof t=="string"?t=fP(t,e):typeof t=="object"&&(t=ia(vn(t,e),e)),t}function oP(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}=sa(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=sa(e,n);if(s||d||i||m||a||p||c||f||u||g)throw new Error(o.error||l.error||"URI is malformed.");let h=T_(o,l,n,!0),_=Xd(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(w_(v)||x_(v).isIPV6);if(z_(h,r||{},_,y))throw new Error(oa);E_(h,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(h.error&&!x)throw new Error(h.error);return n.skipEscape=!0,vn(h,n)}function T_(t,e,r,n){let o={};if(n||(t=ia(vn(t,r),r),e=ia(vn(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=ms(e.path||""),o.query=e.query;else{if(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=ms(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ms(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?b_(o.path):ms(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function sP(t,e,r){let n=v_(t,r),o=v_(e,r);return n!==void 0&&o!==void 0&&n===o}function vn(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=__(r.scheme));let s=Xd(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=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Gd(r.path):r.path=g_(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=__(r.scheme),o.push(r.scheme,":"));let u=GR(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=a&&l[0]!=="/"?b_(l):ms(l)),a&&(l=g_(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",YR(r.query)),r.fragment!==void 0&&o.push("#",QR(r.fragment)),o.join("")}var iP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,aP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,cP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function uP(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 ps(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 aa(t){return t[0]==="["&&t[t.length-1]==="]"}function lP(t){let e=t[4];return ps(t[3])||e!==void 0&&!aa(e)&&ps(e)||ps(t[6])||ps(t[7])||ps(t[8])}function E_(t,e,r,n){if(z_(t,e,r,n))return t.error=t.error||oa,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!aa(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&tP(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!dP(o))return t.error=t.error||oa,!0;t.host=o.hostname}return!1}function z_(t,e,r,n){return!!(t.host&&n===!1&&!aa(t.host)&&(e.domainHost||r&&r.domainHost)&&rP.test(t.host))}function dP(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function sa(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(aP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(cP);if(m!==null){let f=m[1],g=f.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(iP);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(k_.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||S_,u=!0)),s=lP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=uP(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(w_(n.host)===!1){let _=aa(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=x_(n.host);l=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=l?y.host:y.host.toLowerCase(),c&&(n.error=n.error||oa,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 g=Xd(r.scheme||n.scheme);if(c||(a=E_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Gd(n.host,!0);l||(h=Gd(h.toLowerCase())),n.host=l||r.scheme!=="null"?eP(h,l):h}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=XR(n.path)),n.query&&(n.query=y_(n.query)),n.fragment&&(n.fragment=y_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===$_.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 ia(t,e){return sa(t,e).parsed}function fP(t,e){return R_(t,e).normalized}function R_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=sa(t,e);return{normalized:n||o||s||i||a?t:vn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function v_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:vn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=R_(r,e);return o||s||i||a||c?void 0:n}var Yd={SCHEMES:$_,normalize:nP,resolve:oP,resolveComponent:T_,equal:sP,serialize:vn,parse:ia};ca.exports=Yd;ca.exports.default=Yd;ca.exports.fastUri=Yd});var C_=z(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var I_=P_();I_.code='require("ajv/dist/runtime/uri").default';Qd.default=I_});var L_=z(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 pP=ds();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return pP.KeywordCxt}});var ro=W();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return ro._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return ro.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return ro.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return ro.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return ro.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return ro.CodeGen}});var mP=Qi(),j_=fs(),hP=wd(),hs=ta(),gP=W(),gs=cs(),ua=as(),tf=oe(),A_=r_(),yP=C_(),Z_=(t,e)=>new RegExp(t,e);Z_.code="new RegExp";var _P=["removeAdditional","useDefaults","coerceTypes"],vP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xP={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."},bP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},O_=200;function wP(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,N,A,ce,ue;let ze=t.strict,H=(e=t.code)===null||e===void 0?void 0:e.optimize,ve=H===!0||H===void 0?1:H||0,At=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Z_,Dr=(o=t.uriResolver)!==null&&o!==void 0?o:yP.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ze)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ze)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:ze)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:ze)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:ve,regExp:At}:{optimize:ve,regExp:At},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:O_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:O_,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:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(A=t.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(ce=t.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(ue=t.int32range)!==null&&ue!==void 0?ue:!0,uriResolver:Dr}}var ys=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,...wP(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new gP.ValueScope({scope:{},prefixes:vP,es5:r,lines:n}),this.logger=zP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hP.getRules)(),N_.call(this,xP,e,"NOT SUPPORTED"),N_.call(this,bP,e,"DEPRECATED","warn"),this._metaOpts=TP.call(this),e.formats&&kP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&SP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),$P.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(l,d){await s.call(this,l.$schema);let m=this._addSchema(l,d);return m.validate||i.call(this,m)}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 j_.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,gs.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=M_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new hs.SchemaEnv({schema:{},schemaId:n});if(r=hs.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=M_.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,gs.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(PP.call(this,n,r),!r)return(0,tf.eachItem)(n,s=>ef.call(this,s)),this;CP.call(this,r);let o={...r,type:(0,ua.getJSONTypes)(r.type),schemaType:(0,ua.getJSONTypes)(r.schemaType)};return(0,tf.eachItem)(n,o.type.length===0?s=>ef.call(this,s,o):s=>o.type.forEach(i=>ef.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]=D_(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,gs.normalizeId)(i||n);let u=gs.getSchemaRefs.call(this,e,n);return c=new hs.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):hs.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{hs.compileSchema.call(this,e)}finally{this.opts=r}}};ys.ValidationError=mP.default;ys.MissingRefError=j_.default;Oe.default=ys;function N_(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 M_(t){return t=(0,gs.normalizeId)(t),this.schemas[t]||this.refs[t]}function $P(){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 kP(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function SP(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 TP(){let t={...this.opts};for(let e of _P)delete t[e];return t}var EP={log(){},warn(){},error(){}};function zP(t){if(t===!1)return EP;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 RP=/^[a-z_$][a-z0-9_$:-]*$/i;function PP(t,e){let{RULES:r}=this;if((0,tf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!RP.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 ef(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,ua.getJSONTypes)(e.type),schemaType:(0,ua.getJSONTypes)(e.schemaType)}};e.before?IP.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 IP(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 CP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=D_(e)),t.validateSchema=this.compile(e,!0))}var AP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function D_(t){return{anyOf:[t,AP]}}});var q_=z(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var OP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rf.default=OP});var B_=z(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.callRef=xn.getValidate=void 0;var NP=fs(),F_=ht(),ot=W(),no=sr(),U_=ta(),la=oe(),MP={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=U_.resolveRef.call(c,u,o,r);if(l===void 0)throw new NP.default(n.opts.uriResolver,o,r);if(l instanceof U_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return da(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return da(t,(0,ot._)`${f}.validate`,u,u.$async)}function m(f){let g=H_(t,f);da(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,ot.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:ot.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function H_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ot._)`${r.scopeValue("wrapper",{ref:e})}.validate`}xn.getValidate=H_;function da(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?no.default.this:ot.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,ot._)`await ${(0,F_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,ot._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,F_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,ot._)`${f}.errors`;o.assign(no.default.vErrors,(0,ot._)`${no.default.vErrors} === null ? ${g} : ${no.default.vErrors}.concat(${g})`),o.assign(no.default.errors,(0,ot._)`${no.default.vErrors}.length`)}function p(f){var g;if(!s.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=la.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,ot._)`${f}.evaluated.props`);s.props=la.mergeEvaluated.props(o,_,s.props,ot.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=la.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,ot._)`${f}.evaluated.items`);s.items=la.mergeEvaluated.items(o,_,s.items,ot.Name)}}}xn.callRef=da;xn.default=MP});var V_=z(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var jP=q_(),ZP=B_(),DP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jP.default,ZP.default];nf.default=DP});var J_=z(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var fa=W(),Pr=fa.operators,pa={maximum:{okStr:"<=",ok:Pr.LTE,fail:Pr.GT},minimum:{okStr:">=",ok:Pr.GTE,fail:Pr.LT},exclusiveMaximum:{okStr:"<",ok:Pr.LT,fail:Pr.GTE},exclusiveMinimum:{okStr:">",ok:Pr.GT,fail:Pr.LTE}},LP={message:({keyword:t,schemaCode:e})=>(0,fa.str)`must be ${pa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,fa._)`{comparison: ${pa[t].okStr}, limit: ${e}}`},qP={keyword:Object.keys(pa),type:"number",schemaType:"number",$data:!0,error:LP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,fa._)`${r} ${pa[e].fail} ${n} || isNaN(${r})`)}};of.default=qP});var W_=z(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var _s=W(),FP={message:({schemaCode:t})=>(0,_s.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,_s._)`{multipleOf: ${t}}`},UP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,_s._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,_s._)`${i} !== parseInt(${i})`;t.fail$data((0,_s._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};sf.default=UP});var G_=z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});function K_(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}af.default=K_;K_.code='require("ajv/dist/runtime/ucs2length").default'});var X_=z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var bn=W(),HP=oe(),BP=G_(),VP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,bn._)`{limit: ${t}}`},JP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?bn.operators.GT:bn.operators.LT,i=o.opts.unicode===!1?(0,bn._)`${r}.length`:(0,bn._)`${(0,HP.useFunc)(t.gen,BP.default)}(${r})`;t.fail$data((0,bn._)`${i} ${s} ${n}`)}};cf.default=JP});var Y_=z(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var WP=ht(),KP=oe(),oo=W(),GP={message:({schemaCode:t})=>(0,oo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,oo._)`{pattern: ${t}}`},XP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GP,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,oo._)`new RegExp`:(0,KP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,oo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,oo._)`!${l}`)}else{let c=(0,WP.usePattern)(t,o);t.fail$data((0,oo._)`!${c}.test(${r})`)}}};uf.default=XP});var Q_=z(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var vs=W(),YP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,vs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,vs._)`{limit: ${t}}`},QP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?vs.operators.GT:vs.operators.LT;t.fail$data((0,vs._)`Object.keys(${r}).length ${o} ${n}`)}};lf.default=QP});var e0=z(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var xs=ht(),bs=W(),e1=oe(),t1={message:({params:{missingProperty:t}})=>(0,bs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,bs._)`{missingProperty: ${t}}`},r1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:t1,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 p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let g of r)if(p?.[g]===void 0&&!f.has(g)){let h=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,e1.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(bs.nil,d);else for(let p of r)(0,xs.checkReportMissingProp)(t,p)}function l(){let p=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>m(p,f)),t.ok(f)}else e.if((0,xs.checkMissingProp)(t,r,p)),(0,xs.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,xs.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,xs.propertyInData)(e,o,p,a.ownProperties)),e.if((0,bs.not)(f),()=>{t.error(),e.break()})},bs.nil)}}};df.default=r1});var t0=z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var ws=W(),n1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},o1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ws.operators.GT:ws.operators.LT;t.fail$data((0,ws._)`${r}.length ${o} ${n}`)}};ff.default=o1});var ma=z(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var r0=Pd();r0.code='require("ajv/dist/runtime/equal").default';pf.default=r0});var n0=z(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var mf=as(),Ne=W(),s1=oe(),i1=ma(),a1={message:({params:{i:t,j:e}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ne._)`{i: ${t}, j: ${e}}`},c1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a1,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,mf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ne._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Ne._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Ne._)`${f} > 1`,()=>(d()?m:p)(f,g))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,g){let h=e.name("item"),_=(0,mf.checkDataTypes)(u,h,a.opts.strictNumbers,mf.DataType.Wrong),v=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${f}--;`,()=>{e.let(h,(0,Ne._)`${r}[${f}]`),e.if(_,(0,Ne._)`continue`),u.length>1&&e.if((0,Ne._)`typeof ${h} == "string"`,(0,Ne._)`${h} += "_"`),e.if((0,Ne._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Ne._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Ne._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,s1.useFunc)(e,i1.default),_=e.name("outer");e.label(_).for((0,Ne._)`;${f}--;`,()=>e.for((0,Ne._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Ne._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};hf.default=c1});var o0=z(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var gf=W(),u1=oe(),l1=ma(),d1={message:"must be equal to constant",params:({schemaCode:t})=>(0,gf._)`{allowedValue: ${t}}`},f1={keyword:"const",$data:!0,error:d1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,gf._)`!${(0,u1.useFunc)(e,l1.default)}(${r}, ${o})`):t.fail((0,gf._)`${s} !== ${r}`)}};yf.default=f1});var s0=z(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var $s=W(),p1=oe(),m1=ma(),h1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,$s._)`{allowedValues: ${t}}`},g1={keyword:"enum",schemaType:"array",$data:!0,error:h1,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,p1.useFunc)(e,m1.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 p=e.const("vSchema",s);l=(0,$s.or)(...o.map((f,g)=>m(p,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,$s._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,$s._)`${u()}(${r}, ${p}[${f}])`:(0,$s._)`${r} === ${g}`}}};_f.default=g1});var i0=z(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var y1=J_(),_1=W_(),v1=X_(),x1=Y_(),b1=Q_(),w1=e0(),$1=t0(),k1=n0(),S1=o0(),T1=s0(),E1=[y1.default,_1.default,v1.default,x1.default,b1.default,w1.default,$1.default,k1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},S1.default,T1.default];vf.default=E1});var bf=z(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.validateAdditionalItems=void 0;var wn=W(),xf=oe(),z1={message:({params:{len:t}})=>(0,wn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,wn._)`{limit: ${t}}`},R1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:z1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,xf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}a0(t,n)}};function a0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,wn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,wn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,xf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,wn._)`${a} <= ${e.length}`);r.if((0,wn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:xf.Type.Num},u),i.allErrors||r.if((0,wn.not)(u),()=>r.break())})}}ks.validateAdditionalItems=a0;ks.default=R1});var wf=z(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.validateTuple=void 0;var c0=W(),ha=oe(),P1=ht(),I1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return u0(t,"additionalItems",e);r.items=!0,!(0,ha.alwaysValidSchema)(r,e)&&t.ok((0,P1.validateArray)(t))}};function u0(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=ha.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,c0._)`${s}.length`);r.forEach((d,m)=>{(0,ha.alwaysValidSchema)(a,d)||(n.if((0,c0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:p}=a,f=r.length,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!g){let h=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,ha.checkStrictMode)(a,h,m.strictTuples)}}}Ss.validateTuple=u0;Ss.default=I1});var l0=z($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var C1=wf(),A1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,C1.validateTuple)(t,"items")};$f.default=A1});var f0=z(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var d0=W(),O1=oe(),N1=ht(),M1=bf(),j1={message:({params:{len:t}})=>(0,d0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,d0._)`{limit: ${t}}`},Z1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:j1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,O1.alwaysValidSchema)(n,e)&&(o?(0,M1.validateAdditionalItems)(t,o):t.ok((0,N1.validateArray)(t)))}};kf.default=Z1});var p0=z(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var yt=W(),ga=oe(),D1={message:({params:{min:t,max:e}})=>e===void 0?(0,yt.str)`must contain at least ${t} valid item(s)`:(0,yt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,yt._)`{minContains: ${t}}`:(0,yt._)`{minContains: ${t}, maxContains: ${e}}`},L1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:D1,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,yt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ga.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ga.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ga.alwaysValidSchema)(s,r)){let g=(0,yt._)`${l} >= ${i}`;a!==void 0&&(g=(0,yt._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,yt._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let g=e.name("_valid"),h=e.let("count",0);p(g,()=>e.if(g,()=>f(h)))}function p(g,h){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:ga.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,yt._)`${g}++`),a===void 0?e.if((0,yt._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,yt._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,yt._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Sf.default=L1});var g0=z(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateSchemaDeps=Ft.validatePropertyDeps=Ft.error=void 0;var Tf=W(),q1=oe(),Ts=ht();Ft.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Tf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Tf._)`{property: ${t},
34
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function lz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,V._)`${e} !== undefined`,()=>t.assign((0,V._)`${e}[${r}]`,n))}function Ed(t,e,r,n=ro.Correct){let o=n===ro.Correct?V.operators.EQ:V.operators.NEQ,s;switch(t){case"null":return(0,V._)`${e} ${o} null`;case"array":s=(0,V._)`Array.isArray(${e})`;break;case"object":s=(0,V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,V._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${e} ${o} ${t}`}return n===ro.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${e} == "number"`,a,r?(0,V._)`isFinite(${e})`:V.nil)}}qe.checkDataType=Ed;function zd(t,e,r,n){if(t.length===1)return Ed(t[0],e,r,n);let o,s=(0,Ey.toHash)(t);if(s.array&&s.object){let i=(0,V._)`typeof ${e} != "object"`;o=s.null?i:(0,V._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(let i in s)o=(0,V.and)(o,Ed(i,e,r,n));return o}qe.checkDataTypes=zd;var dz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,V._)`{type: ${t}}`:(0,V._)`{type: ${e}}`};function Rd(t){let e=fz(t);(0,sz.reportError)(e,dz)}qe.reportTypeError=Rd;function fz(t){let{gen:e,data:r,schema:n}=t,o=(0,Ey.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Iy=z(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.assignDefaults=void 0;var no=W(),pz=oe();function mz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Py(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Py(t,s,o.default))}Yi.assignDefaults=mz;function Py(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,no._)`${s}${(0,no.getProperty)(e)}`;if(o){(0,pz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,no._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,no._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,no._)`${a} = ${(0,no.stringify)(r)}`)}});var gt=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var _e=W(),Pd=oe(),Rr=ar(),hz=oe();function gz(t,e){let{gen:r,data:n,it:o}=t;r.if(Cd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}de.checkReportMissingProp=gz;function yz({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(Cd(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}de.checkMissingProp=yz;function _z(t,e){t.setParams({missingProperty:e},!0),t.error()}de.reportMissingProp=_z;function Cy(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Cy;function Id(t,e,r){return(0,_e._)`${Cy(t)}.call(${e}, ${r})`}de.isOwnProperty=Id;function vz(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${Id(t,e,r)}`:o}de.propertyInData=vz;function Cd(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(Id(t,e,r))):o}de.noPropertyInData=Cd;function Ay(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=Ay;function xz(t,e){return Ay(e).filter(r=>!(0,Pd.alwaysValidSchema)(t,e[r]))}de.schemaProperties=xz;function bz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,_e._)`${t}, ${e}, ${n}${o}`:e,d=[[Rr.default.instancePath,(0,_e.strConcat)(Rr.default.instancePath,s)],[Rr.default.parentData,i.parentData],[Rr.default.parentDataProperty,i.parentDataProperty],[Rr.default.rootData,Rr.default.rootData]];i.opts.dynamicRef&&d.push([Rr.default.dynamicAnchors,Rr.default.dynamicAnchors]);let m=(0,_e._)`${l}, ${r.object(...d)}`;return c!==_e.nil?(0,_e._)`${a}.call(${c}, ${m})`:(0,_e._)`${a}(${m})`}de.callValidateCode=bz;var wz=(0,_e._)`new RegExp`;function $z({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,_e._)`${o.code==="new RegExp"?wz:(0,hz.useFunc)(t,o)}(${r}, ${n})`})}de.usePattern=$z;function kz(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,_e._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Pd.Type.Num},s),e.if((0,_e.not)(s),a)})}}de.validateArray=kz;function Sz(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,Pd.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,_e._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}de.validateUnion=Sz});var My=z(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateKeywordUsage=Ft.validSchemaType=Ft.funcKeywordCode=Ft.macroKeywordCode=void 0;var We=W(),_n=ar(),Tz=gt(),Ez=us();function zz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ny(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ft.macroKeywordCode=zz;function Rz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Iz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Ny(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)g(),e.modifying&&Oy(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&Oy(t),h(()=>Pz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),v=>n.assign(d,!1).if((0,We._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let v=c.opts.passContext?_n.default.this:_n.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,Tz.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,We.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Ft.funcKeywordCode=Rz;function Oy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function Pz(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(_n.default.vErrors,(0,We._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,We._)`${_n.default.vErrors}.length`),(0,Ez.extendErrors)(t)},()=>t.error())}function Iz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ny(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,We.stringify)(r)})}function Cz(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")}Ft.validSchemaType=Cz;function Az({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)}}Ft.validateKeywordUsage=Az});var Zy=z(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.extendSubschemaMode=Pr.extendSubschemaData=Pr.getSubschema=void 0;var Ht=W(),jy=oe();function Oz(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,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,jy.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')}Pr.getSubschema=Oz;function Nz(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,m=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Ht.str)`${u}${(0,jy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.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]}}Pr.extendSubschemaData=Nz;function Mz(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}Pr.extendSubschemaMode=Mz});var Ad=z((rL,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 qy=z((nL,Ly)=>{"use strict";var Ir=Ly.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(){};Qi(e,n,o,t,"",t)};Ir.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ir.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ir.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ir.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 Qi(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 Ir.arrayKeywords)for(var m=0;m<d.length;m++)Qi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in Ir.propsKeywords){if(d&&typeof d=="object")for(var p in d)Qi(t,e,r,d[p],o+"/"+l+"/"+jz(p),s,o,l,n,p)}else(l in Ir.keywords||t.allKeys&&!(l in Ir.skipKeywords))&&Qi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function jz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ds=z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.getSchemaRefs=nt.resolveUrl=nt.normalizeId=nt._getFullPath=nt.getFullPath=nt.inlineRef=void 0;var Zz=oe(),Dz=Ad(),Lz=qy(),qz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Uz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Od(t):e?Uy(t)<=e:!1}nt.inlineRef=Uz;var Fz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Od(t){for(let e in t){if(Fz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Od)||typeof r=="object"&&Od(r))return!0}return!1}function Uy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!qz.has(r)&&(typeof t[r]=="object"&&(0,Zz.eachItem)(t[r],n=>e+=Uy(n)),e===1/0))return 1/0}return e}function Fy(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return Hy(t,n)}nt.getFullPath=Fy;function Hy(t,e){return t.serialize(e).split("#")[0]+"#"}nt._getFullPath=Hy;var Hz=/#\/?$/;function oo(t){return t?t.replace(Hz,""):""}nt.normalizeId=oo;function Bz(t,e,r){return r=oo(r),t.resolve(e,r)}nt.resolveUrl=Bz;var Vz=/^[a-z_][-a-z0-9._]*$/i;function Jz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=oo(t[r]||e),s={"":o},i=Fy(n,o,!1),a={},c=new Set;return Lz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let g=i+m,h=s[f];typeof d[r]=="string"&&(h=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=h;function _(y){let x=this.opts.uriResolver.resolve;if(y=oo(h?x(h,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==oo(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!Vz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!Dz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}nt.getSchemaRefs=Jz});var ms=z(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getData=Cr.KeywordCxt=Cr.validateFunctionCode=void 0;var Ky=ky(),By=ls(),Md=Td(),ea=ls(),Wz=Iy(),ps=My(),Nd=Zy(),Z=W(),F=ar(),Kz=ds(),cr=oe(),fs=us();function Gz(t){if(Yy(t)&&(Qy(t),Xy(t))){Qz(t);return}Gy(t,()=>(0,Ky.topBoolOrEmptySchema)(t))}Cr.validateFunctionCode=Gz;function Gy({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${Vy(r,o)}`),Yz(t,o),t.code(s)}):t.func(e,(0,Z._)`${F.default.data}, ${Xz(o)}`,n.$async,()=>t.code(Vy(r,o)).code(s))}function Xz(t){return(0,Z._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,Z._)`, ${F.default.dynamicAnchors}={}`:Z.nil}}={}`}function Yz(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,Z._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,Z._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,Z._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,Z._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,Z._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,Z._)`""`),t.var(F.default.parentData,(0,Z._)`undefined`),t.var(F.default.parentDataProperty,(0,Z._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,Z._)`{}`)})}function Qz(t){let{schema:e,opts:r,gen:n}=t;Gy(t,()=>{r.$comment&&e.$comment&&t_(t),oR(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&eR(t),e_(t),aR(t)})}function eR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function Vy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function tR(t,e){if(Yy(t)&&(Qy(t),Xy(t))){rR(t,e);return}(0,Ky.boolOrEmptySchema)(t,e)}function Xy({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 Yy(t){return typeof t.schema!="boolean"}function rR(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&t_(t),sR(t),iR(t);let s=n.const("_errs",F.default.errors);e_(t,s),n.var(e,(0,Z._)`${s} === ${F.default.errors}`)}function Qy(t){(0,cr.checkUnknownRules)(t),nR(t)}function e_(t,e){if(t.opts.jtd)return Jy(t,[],!1,e);let r=(0,By.getSchemaTypes)(t.schema),n=(0,By.coerceAndCheckDataType)(t,r);Jy(t,r,!n,e)}function nR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,cr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function oR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,cr.checkStrictMode)(t,"default is ignored in the schema root")}function sR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Kz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function iR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function t_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function aR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,Z._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,F.default.vErrors),s.unevaluated&&cR(t),e.return((0,Z._)`${F.default.errors} === 0`))}function cR({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Jy(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,cr.schemaHasRulesButRef)(s,l))){o.block(()=>n_(t,"$ref",l.all.$ref.definition));return}c.jtd||uR(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Md.shouldUseGroup)(s,m)&&(m.type?(o.if((0,ea.checkDataType)(m.type,i,c.strictNumbers)),Wy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,ea.reportTypeError)(t)),o.endIf()):Wy(t,m),a||o.if((0,Z._)`${F.default.errors} === ${n||0}`))}}function Wy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Wz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Md.shouldUseRule)(n,s)&&n_(t,s.keyword,s.definition,e.type)})}function uR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(lR(t,e),t.opts.allowUnionTypes||dR(t,e),fR(t,t.dataTypes))}function lR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{r_(t.dataTypes,r)||jd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),mR(t,e)}}function dR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&jd(t,"use allowUnionTypes to allow union type keyword")}function fR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Md.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>pR(e,i))&&jd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function pR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function r_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function mR(t,e){let r=[];for(let n of t.dataTypes)r_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function jd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,cr.checkStrictMode)(t,e,t.opts.strictTypes)}var ta=class{constructor(e,r,n){if((0,ps.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,cr.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",o_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ps.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,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?fs.reportExtraError:fs.reportError)(this,this.def.error,r)}$dataError(){(0,fs.reportError)(this,this.def.$dataError||fs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,fs.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,ea.checkDataTypes)(c,r,s.opts.strictNumbers,ea.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,Nd.getSubschema)(this.it,e);(0,Nd.extendSubschemaData)(n,this.it,e),(0,Nd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return tR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=cr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=cr.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,Z.Name)),!0}};Cr.KeywordCxt=ta;function n_(t,e,r,n){let o=new ta(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ps.funcKeywordCode)(o,r):"macro"in r?(0,ps.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ps.funcKeywordCode)(o,r)}var hR=/^\/(?:[^~]|~0|~1)*$/,gR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function o_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!hR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=gR.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,Z._)`${s}${(0,Z.getProperty)((0,cr.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Cr.getData=o_});var ra=z(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Zd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Dd.default=Zd});var hs=z(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Ld=ds(),qd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ld.resolveUrl)(e,r,n),this.missingSchema=(0,Ld.normalizeId)((0,Ld.getFullPath)(e,this.missingRef))}};Ud.default=qd});var oa=z(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Rt=W(),yR=ra(),vn=ar(),Pt=ds(),s_=oe(),_R=ms(),so=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,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=so;function Hd(t){let e=i_.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Rt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:yR.default,code:(0,Rt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:vn.default.data,parentData:vn.default.parentData,parentDataProperty:vn.default.parentDataProperty,dataNames:[vn.default.data],dataPathArr:[Rt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Rt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Rt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,_R.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(vn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${vn.default.self}`,`${vn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:g}=u;p.evaluated={props:f instanceof Rt.Name?void 0:f,items:g instanceof Rt.Name?void 0:g,dynamicProps:f instanceof Rt.Name,dynamicItems:g instanceof Rt.Name},p.source&&(p.source.evaluated=(0,Rt.stringify)(p.evaluated))}return t.validate=p,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)}}yt.compileSchema=Hd;function vR(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=wR.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 so({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=xR.call(this,s)}yt.resolveRef=vR;function xR(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Hd.call(this,t)}function i_(t){for(let e of this._compilations)if(bR(e,t))return e}yt.getCompilingSchema=i_;function bR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function wR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||na.call(this,t,e)}function na(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Fd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=na.call(this,t,i);return typeof a?.schema!="object"?void 0:Fd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Hd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new so({schema:a,schemaId:c,root:t,baseId:o})}return Fd.call(this,r,i)}}yt.resolveSchema=na;var $R=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fd(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,s_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!$R.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,s_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=na.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new so({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var a_=z((uL,kR)=>{kR.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 Gd=z((lL,h_)=>{"use strict";var SR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Vd=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),TR=RegExp.prototype.test.bind(/^\d*$/u),xn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Jd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),u_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Wd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),ER=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ot=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)ot[e]="%"+t[e>>4]+t[e&15]}function Ue(t){return t<2048?ot[192|t>>6]+ot[128|t&63]:t<65536?ot[224|t>>12]+ot[128|t>>6&63]+ot[128|t&63]:ot[240|t>>18]+ot[128|t>>12&63]+ot[128|t>>6&63]+ot[128|t&63]}function zR(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 RR=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),PR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),IR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),CR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function AR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!IR(t[e])){if(t[e]==="%"&&e+2<t.length&&xn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function c_(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 OR(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||!Vd(c))return;s+=2;continue}if(!RR(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:c_(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 c_(i)}function Bd(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&&PR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(NR(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),!AR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=OR(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function NR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function l_(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("")}function MR(t){if(t===""||t[0]==="/")return l_(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var jR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZR=/[@/?#:]/g,DR=/[@/?#]/g;function d_(t,e){let r=e?DR:ZR;return r.lastIndex=0,t.replace(r,n=>jR[n])}function f_(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(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Jd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function LR(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(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Jd(i)?e+=i:e+="%"+s,r+=2;continue}}if(u_(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=m_(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function qR(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(xn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),u_(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=ot[i];else if(i<55296||i>57343)r+=Ue(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Ue(65536+(i-55296<<10)+(a-56320)),o++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function Kd(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(xn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=ot[s];else if(s<55296||s>57343)r+=Ue(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Ue(65536+(s-55296<<10)+(i-56320)),n++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function p_(t){return Kd(t,ER)}function UR(t){return Kd(t,Wd)}function FR(t){return Kd(t,Wd)}function m_(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 HR(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(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Jd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Wd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=m_(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function BR(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(xn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function VR(t){let e=[];if(t.userinfo!==void 0&&(e.push(p_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Vd(r)){let n=Bd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=f_(r,!0),n=Bd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=d_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!TR(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}h_.exports={nonSimpleDomain:CR,recomposeAuthority:VR,reescapeHostDelimiters:d_,normalizePercentEncoding:f_,normalizePathEncoding:LR,serializePathEncoding:qR,normalizeQueryFragmentEncoding:HR,encodeUserinfo:p_,encodeQuery:UR,encodeFragment:FR,escapePreservingEscapes:BR,removeDotSegments:l_,removeDotSegmentsRelative:MR,isIPv4:Vd,isUUID:SR,normalizeIPv6:Bd,stringArrayToHexStripped:zR}});var x_=z((dL,v_)=>{"use strict";var{isUUID:JR}=Gd(),WR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,KR=["http","https","ws","wss","urn","urn:uuid"];function GR(t){return KR.indexOf(t)!==-1}function Xd(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 g_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function y_(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 XR(t){return t.secure=Xd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function YR(t){if((t.port===(Xd(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 QR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WR);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=Yd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function e1(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=Yd(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 t1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!JR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function r1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var __={scheme:"http",domainHost:!0,parse:g_,serialize:y_},n1={scheme:"https",domainHost:__.domainHost,parse:g_,serialize:y_},sa={scheme:"ws",domainHost:!0,parse:XR,serialize:YR},o1={scheme:"wss",domainHost:sa.domainHost,parse:sa.parse,serialize:sa.serialize},s1={scheme:"urn",parse:QR,serialize:e1,skipNormalize:!0},i1={scheme:"urn:uuid",parse:t1,serialize:r1,skipNormalize:!0},ia={http:__,https:n1,ws:sa,wss:o1,urn:s1,"urn:uuid":i1};Object.setPrototypeOf(ia,null);function Yd(t){return t&&(ia[t]||ia[t.toLowerCase()])||void 0}v_.exports={wsIsSecure:Xd,SCHEMES:ia,isValidSchemeName:GR,getSchemeHandler:Yd}});var N_=z((fL,da)=>{"use strict";var{normalizeIPv6:S_,removeDotSegments:ys,removeDotSegmentsRelative:T_,recomposeAuthority:a1,normalizePercentEncoding:Qd,normalizePathEncoding:c1,serializePathEncoding:b_,normalizeQueryFragmentEncoding:w_,encodeQuery:u1,encodeFragment:l1,reescapeHostDelimiters:d1,isIPv4:E_,nonSimpleDomain:f1}=Gd(),{SCHEMES:z_,getSchemeHandler:ef}=x_(),R_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,P_="URI scheme is malformed.",aa="URI host is malformed.",p1=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function $_(t){let e=String(t);if(!R_.test(e))throw new TypeError(P_);return e}function m1(t,e){return typeof t=="string"?t=$1(t,e):typeof t=="object"&&(t=ua(bn(t,e),e)),t}function h1(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}=ca(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=ca(e,n);if(s||d||i||m||a||p||c||f||u||g)throw new Error(o.error||l.error||"URI is malformed.");let h=I_(o,l,n,!0),_=ef(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(E_(v)||S_(v).isIPV6);if(A_(h,r||{},_,y))throw new Error(aa);C_(h,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(h.error&&!x)throw new Error(h.error);return n.skipEscape=!0,bn(h,n)}function I_(t,e,r,n){let o={};if(n||(t=ua(bn(t,r),r),e=ua(bn(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=ys(e.path||""),o.query=e.query;else{if(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=ys(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ys(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?T_(o.path):ys(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function g1(t,e,r){let n=k_(t,r),o=k_(e,r);return n!==void 0&&o!==void 0&&n===o}function bn(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=$_(r.scheme));let s=ef(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=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Qd(r.path):r.path=b_(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=$_(r.scheme),o.push(r.scheme,":"));let u=a1(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=a&&l[0]!=="/"?T_(l):ys(l)),a&&(l=b_(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",u1(r.query)),r.fragment!==void 0&&o.push("#",l1(r.fragment)),o.join("")}var y1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,_1=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,v1=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function x1(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 gs(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 la(t){return t[0]==="["&&t[t.length-1]==="]"}function b1(t){let e=t[4];return gs(t[3])||e!==void 0&&!la(e)&&gs(e)||gs(t[6])||gs(t[7])||gs(t[8])}function C_(t,e,r,n){if(A_(t,e,r,n))return t.error=t.error||aa,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&f1(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!w1(o))return t.error=t.error||aa,!0;t.host=o.hostname}return!1}function A_(t,e,r,n){return!!(t.host&&n===!1&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&p1.test(t.host))}function w1(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function ca(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(_1);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(v1);if(m!==null){let f=m[1],g=f.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(y1);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(R_.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||P_,u=!0)),s=b1(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=x1(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(E_(n.host)===!1){let _=la(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=S_(n.host);l=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=l?y.host:y.host.toLowerCase(),c&&(n.error=n.error||aa,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 g=ef(r.scheme||n.scheme);if(c||(a=C_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Qd(n.host,!0);l||(h=Qd(h.toLowerCase())),n.host=l||r.scheme!=="null"?d1(h,l):h}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=c1(n.path)),n.query&&(n.query=w_(n.query)),n.fragment&&(n.fragment=w_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===z_.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 ua(t,e){return ca(t,e).parsed}function $1(t,e){return O_(t,e).normalized}function O_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=ca(t,e);return{normalized:n||o||s||i||a?t:bn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function k_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:bn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=O_(r,e);return o||s||i||a||c?void 0:n}var tf={SCHEMES:z_,normalize:m1,resolve:h1,resolveComponent:I_,equal:g1,serialize:bn,parse:ua};da.exports=tf;da.exports.default=tf;da.exports.fastUri=tf});var j_=z(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var M_=N_();M_.code='require("ajv/dist/runtime/uri").default';rf.default=M_});var B_=z(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=void 0;var k1=ms();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return k1.KeywordCxt}});var io=W();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return io._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return io.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return io.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return io.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return io.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return io.CodeGen}});var S1=ra(),U_=hs(),T1=Sd(),_s=oa(),E1=W(),vs=ds(),fa=ls(),of=oe(),Z_=a_(),z1=j_(),F_=(t,e)=>new RegExp(t,e);F_.code="new RegExp";var R1=["removeAdditional","useDefaults","coerceTypes"],P1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),I1={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."},C1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},D_=200;function A1(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,N,A,ae,ce;let Re=t.strict,H=(e=t.code)===null||e===void 0?void 0:e.optimize,xe=H===!0||H===void 0?1:H||0,Mt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:F_,qr=(o=t.uriResolver)!==null&&o!==void 0?o:z1.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Re)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:xe,regExp:Mt}:{optimize:xe,regExp:Mt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:D_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:D_,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:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(A=t.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:qr}}var xs=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,...A1(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new E1.ValueScope({scope:{},prefixes:P1,es5:r,lines:n}),this.logger=D1(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,T1.getRules)(),L_.call(this,I1,e,"NOT SUPPORTED"),L_.call(this,C1,e,"DEPRECATED","warn"),this._metaOpts=j1.call(this),e.formats&&N1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&M1.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),O1.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Z_;n==="id"&&(o={...Z_},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 m=this._addSchema(l,d);return m.validate||i.call(this,m)}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 U_.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,vs.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=q_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new _s.SchemaEnv({schema:{},schemaId:n});if(r=_s.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=q_.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,vs.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(q1.call(this,n,r),!r)return(0,of.eachItem)(n,s=>nf.call(this,s)),this;F1.call(this,r);let o={...r,type:(0,fa.getJSONTypes)(r.type),schemaType:(0,fa.getJSONTypes)(r.schemaType)};return(0,of.eachItem)(n,o.type.length===0?s=>nf.call(this,s,o):s=>o.type.forEach(i=>nf.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]=H_(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,vs.normalizeId)(i||n);let u=vs.getSchemaRefs.call(this,e,n);return c=new _s.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):_s.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{_s.compileSchema.call(this,e)}finally{this.opts=r}}};xs.ValidationError=S1.default;xs.MissingRefError=U_.default;Ne.default=xs;function L_(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 q_(t){return t=(0,vs.normalizeId)(t),this.schemas[t]||this.refs[t]}function O1(){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 N1(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function M1(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 j1(){let t={...this.opts};for(let e of R1)delete t[e];return t}var Z1={log(){},warn(){},error(){}};function D1(t){if(t===!1)return Z1;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 L1=/^[a-z_$][a-z0-9_$:-]*$/i;function q1(t,e){let{RULES:r}=this;if((0,of.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!L1.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 nf(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,fa.getJSONTypes)(e.type),schemaType:(0,fa.getJSONTypes)(e.schemaType)}};e.before?U1.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 U1(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 F1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=H_(e)),t.validateSchema=this.compile(e,!0))}var H1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function H_(t){return{anyOf:[t,H1]}}});var V_=z(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var B1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sf.default=B1});var G_=z(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.callRef=wn.getValidate=void 0;var V1=hs(),J_=gt(),st=W(),ao=ar(),W_=oa(),pa=oe(),J1={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=W_.resolveRef.call(c,u,o,r);if(l===void 0)throw new V1.default(n.opts.uriResolver,o,r);if(l instanceof W_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return ma(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return ma(t,(0,st._)`${f}.validate`,u,u.$async)}function m(f){let g=K_(t,f);ma(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,st.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:st.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function K_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:e})}.validate`}wn.getValidate=K_;function ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ao.default.this:st.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,st._)`await ${(0,J_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,st._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,J_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,st._)`${f}.errors`;o.assign(ao.default.vErrors,(0,st._)`${ao.default.vErrors} === null ? ${g} : ${ao.default.vErrors}.concat(${g})`),o.assign(ao.default.errors,(0,st._)`${ao.default.vErrors}.length`)}function p(f){var g;if(!s.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=pa.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,st._)`${f}.evaluated.props`);s.props=pa.mergeEvaluated.props(o,_,s.props,st.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=pa.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,st._)`${f}.evaluated.items`);s.items=pa.mergeEvaluated.items(o,_,s.items,st.Name)}}}wn.callRef=ma;wn.default=J1});var X_=z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var W1=V_(),K1=G_(),G1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",W1.default,K1.default];af.default=G1});var Y_=z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var ha=W(),Ar=ha.operators,ga={maximum:{okStr:"<=",ok:Ar.LTE,fail:Ar.GT},minimum:{okStr:">=",ok:Ar.GTE,fail:Ar.LT},exclusiveMaximum:{okStr:"<",ok:Ar.LT,fail:Ar.GTE},exclusiveMinimum:{okStr:">",ok:Ar.GT,fail:Ar.LTE}},X1={message:({keyword:t,schemaCode:e})=>(0,ha.str)`must be ${ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ha._)`{comparison: ${ga[t].okStr}, limit: ${e}}`},Y1={keyword:Object.keys(ga),type:"number",schemaType:"number",$data:!0,error:X1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ha._)`${r} ${ga[e].fail} ${n} || isNaN(${r})`)}};cf.default=Y1});var Q_=z(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var bs=W(),Q1={message:({schemaCode:t})=>(0,bs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bs._)`{multipleOf: ${t}}`},eP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Q1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,bs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bs._)`${i} !== parseInt(${i})`;t.fail$data((0,bs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};uf.default=eP});var t0=z(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});function e0(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}lf.default=e0;e0.code='require("ajv/dist/runtime/ucs2length").default'});var r0=z(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var $n=W(),tP=oe(),rP=t0(),nP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$n.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$n._)`{limit: ${t}}`},oP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$n.operators.GT:$n.operators.LT,i=o.opts.unicode===!1?(0,$n._)`${r}.length`:(0,$n._)`${(0,tP.useFunc)(t.gen,rP.default)}(${r})`;t.fail$data((0,$n._)`${i} ${s} ${n}`)}};df.default=oP});var n0=z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var sP=gt(),iP=oe(),co=W(),aP={message:({schemaCode:t})=>(0,co.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,co._)`{pattern: ${t}}`},cP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:aP,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,co._)`new RegExp`:(0,iP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,co._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,co._)`!${l}`)}else{let c=(0,sP.usePattern)(t,o);t.fail$data((0,co._)`!${c}.test(${r})`)}}};ff.default=cP});var o0=z(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var ws=W(),uP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},lP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:uP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ws.operators.GT:ws.operators.LT;t.fail$data((0,ws._)`Object.keys(${r}).length ${o} ${n}`)}};pf.default=lP});var s0=z(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var $s=gt(),ks=W(),dP=oe(),fP={message:({params:{missingProperty:t}})=>(0,ks.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ks._)`{missingProperty: ${t}}`},pP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:fP,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 p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let g of r)if(p?.[g]===void 0&&!f.has(g)){let h=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,dP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ks.nil,d);else for(let p of r)(0,$s.checkReportMissingProp)(t,p)}function l(){let p=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>m(p,f)),t.ok(f)}else e.if((0,$s.checkMissingProp)(t,r,p)),(0,$s.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,$s.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,$s.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ks.not)(f),()=>{t.error(),e.break()})},ks.nil)}}};mf.default=pP});var i0=z(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Ss=W(),mP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ss.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ss._)`{limit: ${t}}`},hP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:mP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ss.operators.GT:Ss.operators.LT;t.fail$data((0,Ss._)`${r}.length ${o} ${n}`)}};hf.default=hP});var ya=z(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var a0=Ad();a0.code='require("ajv/dist/runtime/equal").default';gf.default=a0});var c0=z(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var yf=ls(),Me=W(),gP=oe(),yP=ya(),_P={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},vP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:_P,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,yf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Me._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Me._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Me._)`${f} > 1`,()=>(d()?m:p)(f,g))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,g){let h=e.name("item"),_=(0,yf.checkDataTypes)(u,h,a.opts.strictNumbers,yf.DataType.Wrong),v=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${f}--;`,()=>{e.let(h,(0,Me._)`${r}[${f}]`),e.if(_,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${h} == "string"`,(0,Me._)`${h} += "_"`),e.if((0,Me._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Me._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Me._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,gP.useFunc)(e,yP.default),_=e.name("outer");e.label(_).for((0,Me._)`;${f}--;`,()=>e.for((0,Me._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Me._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};_f.default=vP});var u0=z(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var vf=W(),xP=oe(),bP=ya(),wP={message:"must be equal to constant",params:({schemaCode:t})=>(0,vf._)`{allowedValue: ${t}}`},$P={keyword:"const",$data:!0,error:wP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,vf._)`!${(0,xP.useFunc)(e,bP.default)}(${r}, ${o})`):t.fail((0,vf._)`${s} !== ${r}`)}};xf.default=$P});var l0=z(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var Ts=W(),kP=oe(),SP=ya(),TP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ts._)`{allowedValues: ${t}}`},EP={keyword:"enum",schemaType:"array",$data:!0,error:TP,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,kP.useFunc)(e,SP.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 p=e.const("vSchema",s);l=(0,Ts.or)(...o.map((f,g)=>m(p,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,Ts._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,Ts._)`${u()}(${r}, ${p}[${f}])`:(0,Ts._)`${r} === ${g}`}}};bf.default=EP});var d0=z(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var zP=Y_(),RP=Q_(),PP=r0(),IP=n0(),CP=o0(),AP=s0(),OP=i0(),NP=c0(),MP=u0(),jP=l0(),ZP=[zP.default,RP.default,PP.default,IP.default,CP.default,AP.default,OP.default,NP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},MP.default,jP.default];wf.default=ZP});var kf=z(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.validateAdditionalItems=void 0;var kn=W(),$f=oe(),DP={message:({params:{len:t}})=>(0,kn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,kn._)`{limit: ${t}}`},LP={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,$f.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}f0(t,n)}};function f0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,kn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,kn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,$f.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,kn._)`${a} <= ${e.length}`);r.if((0,kn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:$f.Type.Num},u),i.allErrors||r.if((0,kn.not)(u),()=>r.break())})}}Es.validateAdditionalItems=f0;Es.default=LP});var Sf=z(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.validateTuple=void 0;var p0=W(),_a=oe(),qP=gt(),UP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return m0(t,"additionalItems",e);r.items=!0,!(0,_a.alwaysValidSchema)(r,e)&&t.ok((0,qP.validateArray)(t))}};function m0(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=_a.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,p0._)`${s}.length`);r.forEach((d,m)=>{(0,_a.alwaysValidSchema)(a,d)||(n.if((0,p0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:p}=a,f=r.length,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!g){let h=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,_a.checkStrictMode)(a,h,m.strictTuples)}}}zs.validateTuple=m0;zs.default=UP});var h0=z(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var FP=Sf(),HP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,FP.validateTuple)(t,"items")};Tf.default=HP});var y0=z(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var g0=W(),BP=oe(),VP=gt(),JP=kf(),WP={message:({params:{len:t}})=>(0,g0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,g0._)`{limit: ${t}}`},KP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:WP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,BP.alwaysValidSchema)(n,e)&&(o?(0,JP.validateAdditionalItems)(t,o):t.ok((0,VP.validateArray)(t)))}};Ef.default=KP});var _0=z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var _t=W(),va=oe(),GP={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},XP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GP,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,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,va.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,va.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,va.alwaysValidSchema)(s,r)){let g=(0,_t._)`${l} >= ${i}`;a!==void 0&&(g=(0,_t._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let g=e.name("_valid"),h=e.let("count",0);p(g,()=>e.if(g,()=>f(h)))}function p(g,h){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:va.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,_t._)`${g}++`),a===void 0?e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,_t._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};zf.default=XP});var b0=z(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateSchemaDeps=Bt.validatePropertyDeps=Bt.error=void 0;var Rf=W(),YP=oe(),Rs=gt();Bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Rf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Rf._)`{property: ${t},
35
35
  missingProperty: ${n},
36
36
  depsCount: ${e},
37
- deps: ${r}}`};var F1={keyword:"dependencies",type:"object",schemaType:"object",error:Ft.error,code(t){let[e,r]=U1(t);m0(t,e),h0(t,r)}};function U1({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 m0(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,Ts.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,Ts.checkReportMissingProp)(t,u)}):(r.if((0,Tf._)`${c} && (${(0,Ts.checkMissingProp)(t,a,s)})`),(0,Ts.reportMissingProp)(t,s),r.else())}}Ft.validatePropertyDeps=m0;function h0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,q1.alwaysValidSchema)(s,e[a])||(r.if((0,Ts.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))}Ft.validateSchemaDeps=h0;Ft.default=F1});var _0=z(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var y0=W(),H1=oe(),B1={message:"property name must be valid",params:({params:t})=>(0,y0._)`{propertyName: ${t.propertyName}}`},V1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:B1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,H1.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,y0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ef.default=V1});var Rf=z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var ya=ht(),Rt=W(),J1=sr(),_a=oe(),W1={message:"must NOT have additional properties",params:({params:t})=>(0,Rt._)`{additionalProperty: ${t.additionalProperty}}`},K1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:W1,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,_a.alwaysValidSchema)(i,r))return;let u=(0,ya.allSchemaProperties)(n.properties),l=(0,ya.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Rt._)`${s} === ${J1.default.errors}`);function d(){e.forIn("key",o,h=>{!u.length&&!l.length?f(h):e.if(m(h),()=>f(h))})}function m(h){let _;if(u.length>8){let v=(0,_a.schemaRefOrVal)(i,n.properties,"properties");_=(0,ya.isOwnProperty)(e,v,h)}else u.length?_=(0,Rt.or)(...u.map(v=>(0,Rt._)`${h} === ${v}`)):_=Rt.nil;return l.length&&(_=(0,Rt.or)(_,...l.map(v=>(0,Rt._)`${(0,ya.usePattern)(t,v)}.test(${h})`))),(0,Rt.not)(_)}function p(h){e.code((0,Rt._)`delete ${o}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,_a.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,Rt.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,Rt.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:_a.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};zf.default=K1});var b0=z(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var G1=ds(),v0=ht(),Pf=oe(),x0=Rf(),X1={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&&x0.default.code(new G1.KeywordCxt(s,x0.default,"additionalProperties"));let i=(0,v0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Pf.mergeEvaluated.props(e,(0,Pf.toHash)(i),s.props));let a=i.filter(d=>!(0,Pf.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,v0.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)}}};If.default=X1});var S0=z(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var w0=ht(),va=W(),$0=oe(),k0=oe(),Y1={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,w0.allSchemaProperties)(r),c=a.filter(g=>(0,$0.alwaysValidSchema)(s,r[g]));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 va.Name)&&(s.props=(0,k0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let g of a)u&&p(g),s.allErrors?f(g):(e.var(l,!0),f(g),e.if(l))}function p(g){for(let h in u)new RegExp(g).test(h)&&(0,$0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,va._)`${(0,w0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:k0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,va._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,va.not)(l),()=>e.break())})})}}};Cf.default=Y1});var T0=z(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var Q1=oe(),eI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Q1.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"}};Af.default=eI});var E0=z(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tI=ht(),rI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tI.validateUnion,error:{message:"must match a schema in anyOf"}};Of.default=rI});var z0=z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var xa=W(),nI=oe(),oI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,xa._)`{passingSchemas: ${t.passing}}`},sI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oI,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 m;(0,nI.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,xa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,xa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,xa.Name)})})}}};Nf.default=sI});var R0=z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var iI=oe(),aI={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,iI.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Mf.default=aI});var C0=z(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var ba=W(),I0=oe(),cI={message:({params:t})=>(0,ba.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ba._)`{failingKeyword: ${t.ifClause}}`},uI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cI,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,I0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=P0(n,"then"),s=P0(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,ba.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 m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,ba._)`${l}`):t.setParams({ifClause:l})}}}};function P0(t,e){let r=t.schema[e];return r!==void 0&&!(0,I0.alwaysValidSchema)(t,r)}jf.default=uI});var A0=z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var lI=oe(),dI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,lI.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Zf.default=dI});var O0=z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var fI=bf(),pI=l0(),mI=wf(),hI=f0(),gI=p0(),yI=g0(),_I=_0(),vI=Rf(),xI=b0(),bI=S0(),wI=T0(),$I=E0(),kI=z0(),SI=R0(),TI=C0(),EI=A0();function zI(t=!1){let e=[wI.default,$I.default,kI.default,SI.default,TI.default,EI.default,_I.default,vI.default,yI.default,xI.default,bI.default];return t?e.push(pI.default,hI.default):e.push(fI.default,mI.default),e.push(gI.default),e}Df.default=zI});var N0=z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Se=W(),RI={message:({schemaCode:t})=>(0,Se.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Se._)`{format: ${t}}`},PI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RI,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?m():p();function m(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,Se._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,Se._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,Se._)`${g}.type || "string"`).assign(_,(0,Se._)`${g}.validate`),()=>r.assign(h,(0,Se._)`"string"`).assign(_,g)),t.fail$data((0,Se.or)(v(),y()));function v(){return c.strictSchema===!1?Se.nil:(0,Se._)`${i} && !${_}`}function y(){let x=l.$async?(0,Se._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,Se._)`${_}(${n})`,$=(0,Se._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,Se._)`${_} && ${_} !== true && ${h} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[g,h,_]=y(f);g===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 y($){let N=$ instanceof RegExp?(0,Se.regexpCode)($):c.code.formats?(0,Se._)`${c.code.formats}${(0,Se.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:$,code:N});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Se._)`${A}.validate`]:["string",$,A]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Se._)`await ${_}(${n})`}return typeof h=="function"?(0,Se._)`${_}(${n})`:(0,Se._)`${_}.test(${n})`}}}};Lf.default=PI});var M0=z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var II=N0(),CI=[II.default];qf.default=CI});var j0=z(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.contentVocabulary=so.metadataVocabulary=void 0;so.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];so.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var D0=z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var AI=V_(),OI=i0(),NI=O0(),MI=M0(),Z0=j0(),jI=[AI.default,OI.default,(0,NI.default)(),MI.default,Z0.metadataVocabulary,Z0.contentVocabulary];Ff.default=jI});var q0=z(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.DiscrError=void 0;var L0;(function(t){t.Tag="tag",t.Mapping="mapping"})(L0||(wa.DiscrError=L0={}))});var U0=z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var io=W(),Uf=q0(),F0=ta(),ZI=fs(),DI=oe(),LI={message:({params:{discrError:t,tagName:e}})=>t===Uf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,io._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},qI={keyword:"discriminator",type:"object",schemaType:"object",error:LI,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,io._)`${r}${(0,io.getProperty)(a)}`);e.if((0,io._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Uf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,io._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Uf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(g,io.Name),f}function m(){var p;let f={},g=_(o),h=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,DI.schemaHasRulesButRef)($,s.self.RULES)){let A=$.$ref;if($=F0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),$ instanceof F0.SchemaEnv&&($=$.schema),$===void 0)throw new ZI.default(s.opts.uriResolver,s.baseId,A)}let N=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(N,x)}if(!h)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 N of x.enum)y(N,$);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]=$}}}};Hf.default=qI});var H0=z((HL,FI)=>{FI.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 Vf=z((_e,Bf)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv=void 0;var UI=L_(),HI=D0(),BI=U0(),B0=H0(),VI=["/properties"],$a="http://json-schema.org/draft-07/schema",ao=class extends UI.default{_addVocabularies(){super._addVocabularies(),HI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(BI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(B0,VI):B0;this.addMetaSchema(e,$a,!1),this.refs["http://json-schema.org/schema"]=$a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($a)?$a:void 0)}};_e.Ajv=ao;Bf.exports=_e=ao;Bf.exports.Ajv=ao;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=ao;var JI=ds();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return JI.KeywordCxt}});var co=W();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return co._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return co.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return co.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return co.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return co.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return co.CodeGen}});var WI=Qi();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return WI.default}});var KI=fs();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return KI.default}})});var Q0=z(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.formatNames=Ht.fastFormats=Ht.fullFormats=void 0;function Ut(t,e){return{validate:t,compare:e}}Ht.fullFormats={date:Ut(K0,Gf),time:Ut(Wf(!0),Xf),"date-time":Ut(V0(!0),X0),"iso-time":Ut(Wf(),G0),"iso-date-time":Ut(V0(),Y0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tC,"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:cC,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:rC,int32:{type:"number",validate:sC},int64:{type:"number",validate:iC},float:{type:"number",validate:W0},double:{type:"number",validate:W0},password:!0,binary:!0};Ht.fastFormats={...Ht.fullFormats,date:Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Gf),time:Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Xf),"date-time":Ut(/^\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,X0),"iso-time":Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,G0),"iso-date-time":Ut(/^\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,Y0),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};Ht.formatNames=Object.keys(Ht.fullFormats);function GI(t){return t%4===0&&(t%100!==0||t%400===0)}var XI=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function K0(t){let e=XI.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&&GI(r)?29:YI[n])}function Gf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Jf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Wf(t){return function(r){let n=Jf.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,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function Xf(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 G0(t,e){if(!(t&&e))return;let r=Jf.exec(t),n=Jf.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 Kf=/t|\s/i;function V0(t){let e=Wf(t);return function(n){let o=n.split(Kf);return o.length===2&&K0(o[0])&&e(o[1])}}function X0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Y0(t,e){if(!(t&&e))return;let[r,n]=t.split(Kf),[o,s]=e.split(Kf),i=Gf(r,o);if(i!==void 0)return i||Xf(n,s)}var QI=/\/|:/,eC=/^(?:[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 tC(t){return QI.test(t)&&eC.test(t)}var J0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function rC(t){return J0.lastIndex=0,J0.test(t)}var nC=-(2**31),oC=2**31-1;function sC(t){return Number.isInteger(t)&&t<=oC&&t>=nC}function iC(t){return Number.isInteger(t)}function W0(){return!0}var aC=/[^\\]\\Z/;function cC(t){if(aC.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ev=z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.formatLimitDefinition=void 0;var uC=Vf(),Pt=W(),Ir=Pt.operators,ka={formatMaximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},formatMinimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},formatExclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},formatExclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},lC={message:({keyword:t,schemaCode:e})=>(0,Pt.str)`should be ${ka[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pt._)`{comparison: ${ka[t].okStr}, limit: ${e}}`};uo.formatLimitDefinition={keyword:Object.keys(ka),type:"string",schemaType:"string",$data:!0,error:lC,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 uC.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Pt._)`${m}[${c.schemaCode}]`);t.fail$data((0,Pt.or)((0,Pt._)`typeof ${p} != "object"`,(0,Pt._)`${p} instanceof RegExp`,(0,Pt._)`typeof ${p}.compare != "function"`,d(p)))}function l(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:i.code.formats?(0,Pt._)`${i.code.formats}${(0,Pt.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Pt._)`${m}.compare(${r}, ${n}) ${ka[o].fail} 0`}},dependencies:["format"]};var dC=t=>(t.addKeyword(uo.formatLimitDefinition),t);uo.default=dC});var ov=z((Es,nv)=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var lo=Q0(),fC=ev(),Yf=W(),tv=new Yf.Name("fullFormats"),pC=new Yf.Name("fastFormats"),Qf=(t,e={keywords:!0})=>{if(Array.isArray(e))return rv(t,e,lo.fullFormats,tv),t;let[r,n]=e.mode==="fast"?[lo.fastFormats,pC]:[lo.fullFormats,tv],o=e.formats||lo.formatNames;return rv(t,o,r,n),e.keywords&&(0,fC.default)(t),t};Qf.get=(t,e="full")=>{let n=(e==="fast"?lo.fastFormats:lo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function rv(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Yf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}nv.exports=Es=Qf;Object.defineProperty(Es,"__esModule",{value:!0});Es.default=Qf});var ix={};$o(ix,{findEmbeddingModel:()=>sx,ollamaUrl:()=>xp,semanticRerank:()=>XA});import{createHash as LA}from"node:crypto";import{existsSync as qA,mkdirSync as FA,readFileSync as UA,writeFileSync as HA}from"node:fs";import{homedir as BA}from"node:os";import{join as vp}from"node:path";function xp(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 ox(t,e,r=6e4){let n=await fetch(xp()+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 sx(t){let r=((await ox("/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=>VA.test(n))}function Fa(){return vp(process.env.XDG_CACHE_HOME??vp(BA(),".cache"),"context-doctor","embeddings.json")}function JA(){try{return qA(Fa())?JSON.parse(UA(Fa(),"utf8")):{}}catch{return{}}}function WA(t){try{let e=Object.keys(t);if(e.length>nx)for(let r of e.slice(0,e.length-nx))delete t[r];FA(vp(Fa(),".."),{recursive:!0}),HA(Fa(),JSON.stringify(t))}catch{}}async function KA(t,e){let r=[];for(let n=0;n<e.length;n+=rx){let o=await ox("/api/embed",{model:t,input:e.slice(n,n+rx),truncate:!0});r.push(...o.embeddings)}return r}function GA(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 XA(t,e,r={}){let n;try{n=await sx(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${xp()} (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=JA(),s=f=>LA("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 KA(n,[e,...a]);u=f[0],a.forEach((g,h)=>o[s(g)]=f[h+1]),c=i.map(g=>o[s(g)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&WA(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,g)=>g.score-f.score).map((f,g)=>[f,g])),m=t.map((f,g)=>({c:f,s:GA(u,c[g])})).sort((f,g)=>g.s-f.s),p=new Map(m.map((f,g)=>[f.c,g]));for(let f of t){let g=d.get(f);f.score=(g===void 0?0:1/(l+g))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var VA,rx,nx,ax=X(()=>{"use strict";VA=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,rx=64,nx=5e4});var tb,rb=X(()=>{tb="x-hono-already-sent"});var nb,ob=X(()=>{nb=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{STATUS_CODES as RF,ServerResponse as PN,createServer as PF}from"node:http";import{Http2ServerRequest as dr,constants as IN}from"node:http2";import{Readable as sb}from"node:stream";async function rM(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function bb(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 fb(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:bb(t.getReader(),e)}var Ct,CN,AN,ec,ib,ab,Bp,mb,Vp,hb,ON,NN,MN,Zp,jN,ZN,DN,bo,gb,LN,qN,Mp,Dp,yb,Jp,cb,rc,ub,FN,Zr,ur,wo,Ns,_b,vb,As,Lp,qp,jr,tc,fr,lb,Os,nc,Ms,UN,HN,BN,VN,JN,WN,KN,Wp,GN,db,XN,Kt,YN,Sn,Fp,xo,lr,oc,Wt,QN,eM,tM,Up,sc,pb,nM,oM,wb,sM,iM,aM,$b,ic,Hp,kb,jp,Sb,Tb,cM,Kp,uM,lM,dM,fM,pM,OF,Eb=X(()=>{rb();ob();Ct=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},CN=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),AN=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,ec=t=>t===9||t===10||t===13||t===32,ib=t=>{if(!ec(t.charCodeAt(0))&&!ec(t.charCodeAt(t.length-1)))return t;let e=0,r=t.length;for(;e<r&&ec(t.charCodeAt(e));)e++;for(;r>e&&ec(t.charCodeAt(r-1));)r--;return t.slice(e,r)},ab=/[\0\r\n]/,Bp=globalThis.Headers,mb=(t,e=Bp)=>{let r=new e;for(let n=0;n<t.length;n+=2){let o=t[n];o.startsWith(":")||r.append(o,t[n+1])}return r},Vp=class{#e;#t;#n;#o;constructor(t){this.#e=t,t instanceof dr&&(this.#t=t.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=mb(this.#s),this.#t=void 0),this.#n}#i(t){if(typeof t=="string"){if(!AN.test(t))throw new TypeError(`Invalid header name: ${t}`);return t.toLowerCase()}}#a(t){let e=this.#e instanceof dr?void 0:this.#e.headers;if(!e||CN.has(t)||t==="set-cookie"||t==="__proto__")return;if(!Object.hasOwn(e,t))return null;let r=e[t];if(typeof r=="string"){let n=ib(r);return ab.test(n)?void 0:n}}#c(t,e){let r=e==="cookie"?"; ":", ",n=null;for(let o=0;o<t.length;o+=2){let s=t[o];if(s.length===e.length&&s.toLowerCase()===e){let i=ib(t[o+1]);if(ab.test(i)){this.#o=!0;return}n=n===null?i:n+r+i}}return n}append(t,e){this.#r.append(t,e)}delete(t){this.#r.delete(t)}get(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r;let n=this.#c(this.#s,e);if(n!==void 0)return n}return this.#r.get(t)}has(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r!==null;let n=this.#c(this.#s,e);if(n!==void 0)return n!==null}return this.#r.has(t)}set(t,e){this.#r.set(t,e)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(t,e){this.#r.forEach((r,n)=>{t.call(e,r,n,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Vp.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Vp.prototype,Bp.prototype);hb=t=>globalThis.Headers===Bp?new Vp(t):mb(t.rawHeaders,globalThis.Headers),ON=/^\/[!#$&-;=?-\[\]_a-z~]*$/,NN=/\/\.\.?(?:[/?#]|$)/,MN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Zp=t=>{let e=t.indexOf("\\");if(e!==-1){let r=t.indexOf("?");if(r===-1||e<r)throw new Ct("Backslash in request path")}},jN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(MN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ct("Invalid URL");return!ON.test(r)||NN.test(r)?(Zp(r),new URL(n).href):n}else{Zp(r);let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Ct("Invalid host header");return o.href}},ZN=t=>t instanceof Ct?t:new Ct(t.message,{cause:t}),DN=global.Request,bo=class extends DN{constructor(t,e){if(typeof t=="object"&&Zr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[fr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Zr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},gb=Symbol("wrapBodyStream"),LN=new Set(["latin1","binary","hex","base64","base64url"]),qN=t=>t===null||LN.has(t),Mp=Symbol("bodyBufferedBeforeDisconnect"),Dp=Symbol("bodyBufferedLengthBeforeDisconnect"),yb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Jp=t=>!(t instanceof dr)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&qN(t.readableEncoding),cb=t=>{if(t.readableDidRead||!Jp(t))return;let e=t;e[Dp]??=t.readableLength},rc=(t,e)=>{if(t.readableDidRead&&!e||!Jp(t))return;let r=t;if(r[Mp]!==void 0)return r[Mp];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Dp]!==void 0&&t.readableLength!==r[Dp])n=nc();else{let s=e??[],i=t.read();i!==null&&s.push(yb(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=nc())}}return r[Mp]=n,n},ub=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},FN=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new bo(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[gb]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=rc(n);if(l!==void 0){ub(a,l);return}}i||=sb.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=rc(n);i!==void 0?s.body=new ReadableStream({start(a){ub(a,i)}}):s.body=sb.toWeb(n)}return new bo(e,s)},Zr=Symbol("getRequestCache"),ur=Symbol("requestCache"),wo=Symbol("incomingKey"),Ns=Symbol("urlKey"),_b=Symbol("methodKey"),vb=Symbol("headersKey"),As=Symbol("abortControllerKey"),Lp=Symbol("getAbortController"),qp=Symbol("abortRequest"),jr=Symbol("bodyBuffer"),tc=Symbol("bodyReadPromise"),fr=Symbol("bodyConsumedDirectly"),lb=Symbol("bodyLockReader"),Os=Symbol("abortReason"),nc=()=>new TypeError("Body is unusable"),Ms=()=>Promise.reject(nc()),UN=new TextDecoder,HN=t=>{if(t[fr])return Ms();t[fr]=!0},BN=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),VN=t=>(t[vb]||=hb(t[wo])).get("content-type")||"",JN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,WN=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}},KN=t=>{if(!JN.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.`)},Wp=(t,e,r)=>{if(t[fr])return Ms();let n=t.method;if(n==="GET"||n==="HEAD")return t[Zr]()[e]();let o=KN(n);if(o)return Promise.reject(o);if(t[ur]&&n!=="TRACE")return t[ur][e]();let s=HN(t);if(s)return s;let i=GN(t);if(i){let a=Promise.resolve(r(i,t));return t[jr]=void 0,a}return XN(t).then(a=>{let c=r(a,t);return t[jr]=void 0,c})},GN=t=>{let e=t[wo];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},db=(t,e)=>{if(e.errored)return e.errored;let r=t[Os];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},XN=t=>{if(t[jr])return Promise.resolve(t[jr]);if(t[tc])return t[tc];let e=t[wo];if(e.readableDidRead)return Ms();let r=rc(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[jr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,f(),g())},u=g=>{let h=e.errored??g;return!Jp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=rc(e,i);_ instanceof Error?s(_):_===void 0?s(g??db(t,e)):(t[jr]=_,o(_))}),!0)},l=g=>{i.push(yb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[jr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(db(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[tc]=void 0};e.on("data",l),e.on("end",d),e.on("error",m),e.on("close",p),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?m(e.errored):e.destroyed&&p())})});return t[tc]=n,n},Kt={get method(){return this[_b]},get url(){return this[Ns]},get headers(){return this[vb]||=hb(this[wo])},[qp](t){this[Os]===void 0&&(this[Os]=t);let e=this[As];e&&!e.signal.aborted&&e.abort(t)},[Lp](){return this[As]||=new AbortController,this[Os]!==void 0&&!this[As].signal.aborted&&this[As].abort(this[Os]),this[As]},[Zr](){let t=this[Lp]();if(this[ur])return this[ur];let e=this.method;if(this[fr]&&!(e==="GET"||e==="HEAD")){this[jr]=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 bo(this[Ns],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[ur]=n}return this[ur]=FN(this.method,this[Ns],this.headers,this[wo],t)},get body(){if(!this[fr])return this[Zr]().body;let t=this[Zr]();return!this[lb]&&t.body&&(this[lb]=t.body.getReader()),t.body},get bodyUsed(){return this[fr]?!0:this[ur]?this[ur].bodyUsed:!1}};Object.defineProperty(Kt,"signal",{get(){return this[Lp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Kt,t,{get(){return this[Zr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Kt,t,{value:function(){if(this[fr]){if(t==="clone")throw nc();return Ms()}return this[Zr]()[t]()}})});Object.defineProperty(Kt,"text",{value:function(){return Wp(this,"text",t=>UN.decode(t))}});Object.defineProperty(Kt,"arrayBuffer",{value:function(){return Wp(this,"arrayBuffer",t=>BN(t))}});Object.defineProperty(Kt,"blob",{value:function(){return Wp(this,"blob",(t,e)=>{let r=VN(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Kt,"json",{value:function(){return this[fr]?Ms():this.text().then(JSON.parse)}});Object.defineProperty(Kt,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[ur]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Kt,bo.prototype);YN=(t,e)=>{let r=Object.create(Kt);r[wo]=t,r[_b]=WN(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof dr)throw new Ct("Absolute URL for :path is not allowed in HTTP/2");try{Zp(n),r[Ns]=new URL(n).href}catch(i){throw new Ct("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof dr?t.authority:t.headers.host)||e;if(!o)throw new Ct("Missing host header");let s;if(t instanceof dr){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ct("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Ns]=jN(s,o,n)}catch(i){throw i instanceof Ct?i:new Ct("Invalid URL",{cause:i})}return r},Sn="text/plain; charset=UTF-8",Fp=Symbol("responseCache"),xo=Symbol("getResponseCache"),lr=Symbol("cache"),oc=global.Response,Wt=class xb{#e;#t;[xo](){let e=this[lr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[lr],this[Fp]||=new oc(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 oc){let o=r[Fp];if(o){this.#t=o,this[xo]();return}this.#t=r instanceof xb?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[lr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[lr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Sn}))),e[2]):this[xo]().headers}get status(){return this[lr]?.[0]??this[xo]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Wt.prototype,t,{get(){return this[xo]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Wt.prototype,t,{value:function(){return this[xo]()[t]()}})});Object.defineProperty(Wt.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[Fp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Wt,oc);Object.setPrototypeOf(Wt.prototype,oc.prototype);QN=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,eM=t=>t instanceof URL?t.href:QN.test(t)?t:new URL(t).href,tM=new Set([301,302,303,307,308]);Object.defineProperty(Wt,"redirect",{value:function(e,r=302){if(!tM.has(r))throw new RangeError("Invalid status code");return new Wt(null,{status:r,headers:{location:eM(e)}})},writable:!0,configurable:!0});Object.defineProperty(Wt,"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 Wt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Up=(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},sc=Symbol("outgoingEnded"),pb=Symbol("incomingDraining"),nM=500,oM=64*1024*1024,wb=t=>{let e=t;if(t.destroyed||e[pb])return;if(e[pb]=!0,t instanceof dr){try{t.stream?.close?.(IN.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,nM);s.unref?.();let i=a=>{r+=a.length,r>oM&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},sM=(t,e,r,n)=>()=>{e.errored?(cb(e),t[qp](e.errored.toString())):(!r.writableFinished||e instanceof dr&&e.aborted)&&(cb(e),t[qp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{wb(e)})})},iM=t=>{if(!(lr in t))return!1;let e=t[lr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},aM=()=>new Response(null,{status:400}),$b=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),ic=(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 instanceof PN&&(e._contentLength=null),e.writeHead(500,{"Content-Type":"text/plain"})),e.end(`Error: ${r.message}`),e.destroy(r))},Hp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},kb=(t,e,r)=>{let n=t;return n._contentLength===null&&n._hasBody&&n.useChunkedEncodingByDefault&&!n._removedContLen&&e>=200&&e!==204&&e!==304&&!t.hasHeader("content-length")&&!t.hasHeader("transfer-encoding")&&!t.hasHeader("trailer")?(n._contentLength=r,!0):!1},jp=(t,e,r)=>{kb(t,e,r)?t.writeHead(e,{"Content-Type":Sn}):t.writeHead(e,{"Content-Type":Sn,"Content-Length":r})},Sb=async(t,e)=>{let[r,n,o]=t[lr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(jp(e,r,Buffer.byteLength(n)),e.end(n)):n instanceof Uint8Array?(jp(e,r,n.byteLength),e.end(n)):n instanceof Blob?(jp(e,r,n.size),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Sn}),Hp(e),await fb(n,e)?.catch(c=>ic(c,e))),e[sc]?.();return}let s=!1,i=!1,a=!0;if(o instanceof Headers)s=o.has("content-length"),o=Up(o,n===null?void 0:Sn);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=Up(c,n===null?void 0:Sn)}else{i=!0;for(let c in o){if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}(c.length===17&&c.toLowerCase()==="transfer-encoding"||c.length===7&&c.toLowerCase()==="trailer")&&(a=!1)}}if(!s){let c;typeof n=="string"?c=Buffer.byteLength(n):n instanceof Uint8Array?c=n.byteLength:n instanceof Blob&&(c=n.size),c!==void 0&&(!i||!a||!kb(e,r,c))&&(i&&(o={...o}),o["Content-Length"]=c)}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())):(Hp(e),await fb(n,e)?.catch(c=>ic(c,e))),e[sc]?.()},Tb=t=>typeof t.then=="function",cM=async(t,e,r={})=>{if(Tb(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($b);if(lr in t)return Sb(t,e);let n=Up(t.headers,t.body===null?void 0:Sn);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 rM(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&&Hp(e),await bb(o,e,a))}else n[tb]||(e.writeHead(t.status,n),e.end());e[sc]?.()},Kp=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==bo&&(Object.defineProperty(global,"Request",{value:bo}),Object.defineProperty(global,"Response",{value:Wt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",sM(i,n,o,a)))};try{if(i=YN(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[gb]=!0,n instanceof dr&&(o[sc]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!Tb(s)&&iM(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||wb(n)}),Sb(s,o);u()}catch(l){if(s)return ic(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:ZN(l)),!s)return}else i?s=$b(l):s=aM()}try{return await cM(s,o,e)}catch(l){return ic(l,o)}}},uM=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??""}},lM=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}},dM=()=>Symbol("connection"),fM=Symbol("CONNECTION_SYMBOL_KEY"),pM=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),OF=nb(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[pM];if(!o||!n.incoming)return new Response(null,{status:500});let s=dM();return n[fM]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,m)=>{a.push([d,m])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,m){i.close(d,m)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,m){i.send(d,{compress:m?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,m)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{e?.onMessage?.(new MessageEvent("message",{data:m?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(g){(r?.onError??console.error)(g)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,m)=>{l(d,m)}),i.on("close",(d,m)=>{try{e?.onClose?.(new uM("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new lM("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var Ib=z(Gp=>{"use strict";var zb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,mM=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Rb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,hM=/\\([\u000b\u0020-\u00ff])/g,gM=/([\\"])/g,Pb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Gp.format=yM;Gp.parse=_M;function yM(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Pb.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],!Rb.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+xM(e[o])}return n}function _M(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?vM(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(!Pb.test(n))throw new TypeError("invalid media type");var o=new bM(n.toLowerCase());if(r!==-1){var s,i,a;for(zb.lastIndex=r;i=zb.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(hM,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function vM(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 xM(t){var e=String(t);if(Rb.test(e))return e;if(e.length>0&&!mM.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(gM,"\\$1")+'"'}function bM(t){this.parameters=Object.create(null),this.type=t}});function wM(t){if(t)try{return Cb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Ab(t){return t==="application/json"?!0:wM(t)==="application/json"}var Cb,Ob=X(()=>{Cb=lc(Ib(),1)});function Nb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function Mb(t){if(t===void 0)return 4194304;if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function jb(t,e=4194304){if(Number(t.headers.get("content-length"))>e)return{tooLarge:!0};if(t.body===null)return{tooLarge:!1,text:""};let r=t.body.getReader(),n=new TextDecoder,o=0,s="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(o+=a.byteLength,o>e)return{tooLarge:!0};s+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:s+n.decode()}}var Zb=X(()=>{});function Db(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Lb=X(()=>{});var ac,qb=X(()=>{Ob();Zb();Lb();wr();ac=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,this._maxRequestBodySize=Mb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=Db(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
37
+ deps: ${r}}`};var QP={keyword:"dependencies",type:"object",schemaType:"object",error:Bt.error,code(t){let[e,r]=eI(t);v0(t,e),x0(t,r)}};function eI({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 v0(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,Rs.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,Rs.checkReportMissingProp)(t,u)}):(r.if((0,Rf._)`${c} && (${(0,Rs.checkMissingProp)(t,a,s)})`),(0,Rs.reportMissingProp)(t,s),r.else())}}Bt.validatePropertyDeps=v0;function x0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,YP.alwaysValidSchema)(s,e[a])||(r.if((0,Rs.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))}Bt.validateSchemaDeps=x0;Bt.default=QP});var $0=z(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var w0=W(),tI=oe(),rI={message:"property name must be valid",params:({params:t})=>(0,w0._)`{propertyName: ${t.propertyName}}`},nI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rI,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,tI.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,w0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Pf.default=nI});var Cf=z(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var xa=gt(),It=W(),oI=ar(),ba=oe(),sI={message:"must NOT have additional properties",params:({params:t})=>(0,It._)`{additionalProperty: ${t.additionalProperty}}`},iI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:sI,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,ba.alwaysValidSchema)(i,r))return;let u=(0,xa.allSchemaProperties)(n.properties),l=(0,xa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,It._)`${s} === ${oI.default.errors}`);function d(){e.forIn("key",o,h=>{!u.length&&!l.length?f(h):e.if(m(h),()=>f(h))})}function m(h){let _;if(u.length>8){let v=(0,ba.schemaRefOrVal)(i,n.properties,"properties");_=(0,xa.isOwnProperty)(e,v,h)}else u.length?_=(0,It.or)(...u.map(v=>(0,It._)`${h} === ${v}`)):_=It.nil;return l.length&&(_=(0,It.or)(_,...l.map(v=>(0,It._)`${(0,xa.usePattern)(t,v)}.test(${h})`))),(0,It.not)(_)}function p(h){e.code((0,It._)`delete ${o}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ba.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,It.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,It.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:ba.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};If.default=iI});var T0=z(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var aI=ms(),k0=gt(),Af=oe(),S0=Cf(),cI={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&&S0.default.code(new aI.KeywordCxt(s,S0.default,"additionalProperties"));let i=(0,k0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Af.mergeEvaluated.props(e,(0,Af.toHash)(i),s.props));let a=i.filter(d=>!(0,Af.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,k0.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)}}};Of.default=cI});var P0=z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var E0=gt(),wa=W(),z0=oe(),R0=oe(),uI={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,E0.allSchemaProperties)(r),c=a.filter(g=>(0,z0.alwaysValidSchema)(s,r[g]));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 wa.Name)&&(s.props=(0,R0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let g of a)u&&p(g),s.allErrors?f(g):(e.var(l,!0),f(g),e.if(l))}function p(g){for(let h in u)new RegExp(g).test(h)&&(0,z0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,wa._)`${(0,E0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:R0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,wa._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,wa.not)(l),()=>e.break())})})}}};Nf.default=uI});var I0=z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var lI=oe(),dI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,lI.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"}};Mf.default=dI});var C0=z(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var fI=gt(),pI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fI.validateUnion,error:{message:"must match a schema in anyOf"}};jf.default=pI});var A0=z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var $a=W(),mI=oe(),hI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,$a._)`{passingSchemas: ${t.passing}}`},gI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hI,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 m;(0,mI.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,$a._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$a._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,$a.Name)})})}}};Zf.default=gI});var O0=z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var yI=oe(),_I={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,yI.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Df.default=_I});var j0=z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var ka=W(),M0=oe(),vI={message:({params:t})=>(0,ka.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ka._)`{failingKeyword: ${t.ifClause}}`},xI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vI,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,M0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=N0(n,"then"),s=N0(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,ka.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 m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,ka._)`${l}`):t.setParams({ifClause:l})}}}};function N0(t,e){let r=t.schema[e];return r!==void 0&&!(0,M0.alwaysValidSchema)(t,r)}Lf.default=xI});var Z0=z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var bI=oe(),wI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,bI.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};qf.default=wI});var D0=z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var $I=kf(),kI=h0(),SI=Sf(),TI=y0(),EI=_0(),zI=b0(),RI=$0(),PI=Cf(),II=T0(),CI=P0(),AI=I0(),OI=C0(),NI=A0(),MI=O0(),jI=j0(),ZI=Z0();function DI(t=!1){let e=[AI.default,OI.default,NI.default,MI.default,jI.default,ZI.default,RI.default,PI.default,zI.default,II.default,CI.default];return t?e.push(kI.default,TI.default):e.push($I.default,SI.default),e.push(EI.default),e}Uf.default=DI});var L0=z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Te=W(),LI={message:({schemaCode:t})=>(0,Te.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Te._)`{format: ${t}}`},qI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:LI,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?m():p();function m(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,Te._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,Te._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,Te._)`${g}.type || "string"`).assign(_,(0,Te._)`${g}.validate`),()=>r.assign(h,(0,Te._)`"string"`).assign(_,g)),t.fail$data((0,Te.or)(v(),y()));function v(){return c.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${_}`}function y(){let x=l.$async?(0,Te._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,Te._)`${_}(${n})`,$=(0,Te._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,Te._)`${_} && ${_} !== true && ${h} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[g,h,_]=y(f);g===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 y($){let N=$ instanceof RegExp?(0,Te.regexpCode)($):c.code.formats?(0,Te._)`${c.code.formats}${(0,Te.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:$,code:N});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Te._)`${A}.validate`]:["string",$,A]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${_}(${n})`}return typeof h=="function"?(0,Te._)`${_}(${n})`:(0,Te._)`${_}.test(${n})`}}}};Ff.default=qI});var q0=z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var UI=L0(),FI=[UI.default];Hf.default=FI});var U0=z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.contentVocabulary=uo.metadataVocabulary=void 0;uo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];uo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var H0=z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var HI=X_(),BI=d0(),VI=D0(),JI=q0(),F0=U0(),WI=[HI.default,BI.default,(0,VI.default)(),JI.default,F0.metadataVocabulary,F0.contentVocabulary];Bf.default=WI});var V0=z(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.DiscrError=void 0;var B0;(function(t){t.Tag="tag",t.Mapping="mapping"})(B0||(Sa.DiscrError=B0={}))});var W0=z(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var lo=W(),Vf=V0(),J0=oa(),KI=hs(),GI=oe(),XI={message:({params:{discrError:t,tagName:e}})=>t===Vf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},YI={keyword:"discriminator",type:"object",schemaType:"object",error:XI,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,lo._)`${r}${(0,lo.getProperty)(a)}`);e.if((0,lo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Vf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,lo._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Vf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(g,lo.Name),f}function m(){var p;let f={},g=_(o),h=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,GI.schemaHasRulesButRef)($,s.self.RULES)){let A=$.$ref;if($=J0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),$ instanceof J0.SchemaEnv&&($=$.schema),$===void 0)throw new KI.default(s.opts.uriResolver,s.baseId,A)}let N=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(N,x)}if(!h)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 N of x.enum)y(N,$);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]=$}}}};Jf.default=YI});var K0=z((eq,QI)=>{QI.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 Kf=z((ve,Wf)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var eC=B_(),tC=H0(),rC=W0(),G0=K0(),nC=["/properties"],Ta="http://json-schema.org/draft-07/schema",fo=class extends eC.default{_addVocabularies(){super._addVocabularies(),tC.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(G0,nC):G0;this.addMetaSchema(e,Ta,!1),this.refs["http://json-schema.org/schema"]=Ta}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ta)?Ta:void 0)}};ve.Ajv=fo;Wf.exports=ve=fo;Wf.exports.Ajv=fo;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=fo;var oC=ms();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return oC.KeywordCxt}});var po=W();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return po._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return po.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return po.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return po.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return po.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return po.CodeGen}});var sC=ra();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return sC.default}});var iC=hs();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return iC.default}})});var ov=z(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.formatNames=Jt.fastFormats=Jt.fullFormats=void 0;function Vt(t,e){return{validate:t,compare:e}}Jt.fullFormats={date:Vt(ev,Qf),time:Vt(Xf(!0),ep),"date-time":Vt(X0(!0),rv),"iso-time":Vt(Xf(),tv),"iso-date-time":Vt(X0(),nv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fC,"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:vC,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:pC,int32:{type:"number",validate:gC},int64:{type:"number",validate:yC},float:{type:"number",validate:Q0},double:{type:"number",validate:Q0},password:!0,binary:!0};Jt.fastFormats={...Jt.fullFormats,date:Vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Qf),time:Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ep),"date-time":Vt(/^\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,rv),"iso-time":Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,tv),"iso-date-time":Vt(/^\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,nv),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};Jt.formatNames=Object.keys(Jt.fullFormats);function aC(t){return t%4===0&&(t%100!==0||t%400===0)}var cC=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ev(t){let e=cC.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&&aC(r)?29:uC[n])}function Qf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Gf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Xf(t){return function(r){let n=Gf.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,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function ep(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 tv(t,e){if(!(t&&e))return;let r=Gf.exec(t),n=Gf.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 Yf=/t|\s/i;function X0(t){let e=Xf(t);return function(n){let o=n.split(Yf);return o.length===2&&ev(o[0])&&e(o[1])}}function rv(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function nv(t,e){if(!(t&&e))return;let[r,n]=t.split(Yf),[o,s]=e.split(Yf),i=Qf(r,o);if(i!==void 0)return i||ep(n,s)}var lC=/\/|:/,dC=/^(?:[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 fC(t){return lC.test(t)&&dC.test(t)}var Y0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function pC(t){return Y0.lastIndex=0,Y0.test(t)}var mC=-(2**31),hC=2**31-1;function gC(t){return Number.isInteger(t)&&t<=hC&&t>=mC}function yC(t){return Number.isInteger(t)}function Q0(){return!0}var _C=/[^\\]\\Z/;function vC(t){if(_C.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var sv=z(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.formatLimitDefinition=void 0;var xC=Kf(),Ct=W(),Or=Ct.operators,Ea={formatMaximum:{okStr:"<=",ok:Or.LTE,fail:Or.GT},formatMinimum:{okStr:">=",ok:Or.GTE,fail:Or.LT},formatExclusiveMaximum:{okStr:"<",ok:Or.LT,fail:Or.GTE},formatExclusiveMinimum:{okStr:">",ok:Or.GT,fail:Or.LTE}},bC={message:({keyword:t,schemaCode:e})=>(0,Ct.str)`should be ${Ea[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ct._)`{comparison: ${Ea[t].okStr}, limit: ${e}}`};mo.formatLimitDefinition={keyword:Object.keys(Ea),type:"string",schemaType:"string",$data:!0,error:bC,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 xC.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Ct._)`${m}[${c.schemaCode}]`);t.fail$data((0,Ct.or)((0,Ct._)`typeof ${p} != "object"`,(0,Ct._)`${p} instanceof RegExp`,(0,Ct._)`typeof ${p}.compare != "function"`,d(p)))}function l(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:i.code.formats?(0,Ct._)`${i.code.formats}${(0,Ct.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Ct._)`${m}.compare(${r}, ${n}) ${Ea[o].fail} 0`}},dependencies:["format"]};var wC=t=>(t.addKeyword(mo.formatLimitDefinition),t);mo.default=wC});var uv=z((Ps,cv)=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var ho=ov(),$C=sv(),tp=W(),iv=new tp.Name("fullFormats"),kC=new tp.Name("fastFormats"),rp=(t,e={keywords:!0})=>{if(Array.isArray(e))return av(t,e,ho.fullFormats,iv),t;let[r,n]=e.mode==="fast"?[ho.fastFormats,kC]:[ho.fullFormats,iv],o=e.formats||ho.formatNames;return av(t,o,r,n),e.keywords&&(0,$C.default)(t),t};rp.get=(t,e="full")=>{let n=(e==="fast"?ho.fastFormats:ho.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function av(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,tp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}cv.exports=Ps=rp;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.default=rp});var mx={};To(mx,{findEmbeddingModel:()=>px,ollamaUrl:()=>Sp,semanticRerank:()=>aO});import{createHash as GA}from"node:crypto";import{existsSync as XA,mkdirSync as YA,readFileSync as QA,writeFileSync as eO}from"node:fs";import{homedir as tO}from"node:os";import{join as kp}from"node:path";function Sp(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 fx(t,e,r=6e4){let n=await fetch(Sp()+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 px(t){let r=((await fx("/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=>rO.test(n))}function Ba(){return kp(process.env.XDG_CACHE_HOME??kp(tO(),".cache"),"context-doctor","embeddings.json")}function nO(){try{return XA(Ba())?JSON.parse(QA(Ba(),"utf8")):{}}catch{return{}}}function oO(t){try{let e=Object.keys(t);if(e.length>dx)for(let r of e.slice(0,e.length-dx))delete t[r];YA(kp(Ba(),".."),{recursive:!0}),eO(Ba(),JSON.stringify(t))}catch{}}async function sO(t,e){let r=[];for(let n=0;n<e.length;n+=lx){let o=await fx("/api/embed",{model:t,input:e.slice(n,n+lx),truncate:!0});r.push(...o.embeddings)}return r}function iO(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 aO(t,e,r={}){let n;try{n=await px(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${Sp()} (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=nO(),s=f=>GA("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 sO(n,[e,...a]);u=f[0],a.forEach((g,h)=>o[s(g)]=f[h+1]),c=i.map(g=>o[s(g)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&oO(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,g)=>g.score-f.score).map((f,g)=>[f,g])),m=t.map((f,g)=>({c:f,s:iO(u,c[g])})).sort((f,g)=>g.s-f.s),p=new Map(m.map((f,g)=>[f.c,g]));for(let f of t){let g=d.get(f);f.score=(g===void 0?0:1/(l+g))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var rO,lx,dx,hx=X(()=>{"use strict";rO=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,lx=64,dx=5e4});var fb,pb=X(()=>{fb="x-hono-already-sent"});var mb,hb=X(()=>{mb=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{STATUS_CODES as UU,ServerResponse as LN,createServer as FU}from"node:http";import{Http2ServerRequest as mr,constants as qN}from"node:http2";import{Readable as gb}from"node:stream";async function fM(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Cb(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 $b(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Cb(t.getReader(),e)}var Nt,UN,FN,nc,yb,_b,Gp,Sb,Xp,Tb,HN,BN,VN,Fp,JN,WN,KN,ko,Eb,GN,XN,qp,Hp,zb,Yp,vb,sc,xb,YN,Lr,fr,So,Zs,Rb,Pb,Ms,Bp,Vp,Dr,oc,hr,bb,js,ic,Ds,QN,eM,tM,rM,nM,oM,sM,Qp,iM,wb,aM,Xt,cM,Rn,Jp,$o,pr,ac,Gt,uM,lM,dM,Wp,cc,kb,pM,mM,Ab,hM,gM,yM,Ob,uc,Kp,Nb,Up,Mb,jb,_M,em,vM,xM,bM,wM,$M,JU,Zb=X(()=>{pb();hb();Nt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},UN=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),FN=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,nc=t=>t===9||t===10||t===13||t===32,yb=t=>{if(!nc(t.charCodeAt(0))&&!nc(t.charCodeAt(t.length-1)))return t;let e=0,r=t.length;for(;e<r&&nc(t.charCodeAt(e));)e++;for(;r>e&&nc(t.charCodeAt(r-1));)r--;return t.slice(e,r)},_b=/[\0\r\n]/,Gp=globalThis.Headers,Sb=(t,e=Gp)=>{let r=new e;for(let n=0;n<t.length;n+=2){let o=t[n];o.startsWith(":")||r.append(o,t[n+1])}return r},Xp=class{#e;#t;#n;#o;constructor(t){this.#e=t,t instanceof mr&&(this.#t=t.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=Sb(this.#s),this.#t=void 0),this.#n}#i(t){if(typeof t=="string"){if(!FN.test(t))throw new TypeError(`Invalid header name: ${t}`);return t.toLowerCase()}}#a(t){let e=this.#e instanceof mr?void 0:this.#e.headers;if(!e||UN.has(t)||t==="set-cookie"||t==="__proto__")return;if(!Object.hasOwn(e,t))return null;let r=e[t];if(typeof r=="string"){let n=yb(r);return _b.test(n)?void 0:n}}#c(t,e){let r=e==="cookie"?"; ":", ",n=null;for(let o=0;o<t.length;o+=2){let s=t[o];if(s.length===e.length&&s.toLowerCase()===e){let i=yb(t[o+1]);if(_b.test(i)){this.#o=!0;return}n=n===null?i:n+r+i}}return n}append(t,e){this.#r.append(t,e)}delete(t){this.#r.delete(t)}get(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r;let n=this.#c(this.#s,e);if(n!==void 0)return n}return this.#r.get(t)}has(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r!==null;let n=this.#c(this.#s,e);if(n!==void 0)return n!==null}return this.#r.has(t)}set(t,e){this.#r.set(t,e)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(t,e){this.#r.forEach((r,n)=>{t.call(e,r,n,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Xp.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Xp.prototype,Gp.prototype);Tb=t=>globalThis.Headers===Gp?new Xp(t):Sb(t.rawHeaders,globalThis.Headers),HN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,BN=/\/\.\.?(?:[/?#]|$)/,VN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Fp=t=>{let e=t.indexOf("\\");if(e!==-1){let r=t.indexOf("?");if(r===-1||e<r)throw new Nt("Backslash in request path")}},JN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(VN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Nt("Invalid URL");return!HN.test(r)||BN.test(r)?(Fp(r),new URL(n).href):n}else{Fp(r);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}},WN=t=>t instanceof Nt?t:new Nt(t.message,{cause:t}),KN=global.Request,ko=class extends KN{constructor(t,e){if(typeof t=="object"&&Lr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[hr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Lr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Eb=Symbol("wrapBodyStream"),GN=new Set(["latin1","binary","hex","base64","base64url"]),XN=t=>t===null||GN.has(t),qp=Symbol("bodyBufferedBeforeDisconnect"),Hp=Symbol("bodyBufferedLengthBeforeDisconnect"),zb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Yp=t=>!(t instanceof mr)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&XN(t.readableEncoding),vb=t=>{if(t.readableDidRead||!Yp(t))return;let e=t;e[Hp]??=t.readableLength},sc=(t,e)=>{if(t.readableDidRead&&!e||!Yp(t))return;let r=t;if(r[qp]!==void 0)return r[qp];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Hp]!==void 0&&t.readableLength!==r[Hp])n=ic();else{let s=e??[],i=t.read();i!==null&&s.push(zb(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=ic())}}return r[qp]=n,n},xb=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},YN=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ko(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[Eb]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=sc(n);if(l!==void 0){xb(a,l);return}}i||=gb.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=sc(n);i!==void 0?s.body=new ReadableStream({start(a){xb(a,i)}}):s.body=gb.toWeb(n)}return new ko(e,s)},Lr=Symbol("getRequestCache"),fr=Symbol("requestCache"),So=Symbol("incomingKey"),Zs=Symbol("urlKey"),Rb=Symbol("methodKey"),Pb=Symbol("headersKey"),Ms=Symbol("abortControllerKey"),Bp=Symbol("getAbortController"),Vp=Symbol("abortRequest"),Dr=Symbol("bodyBuffer"),oc=Symbol("bodyReadPromise"),hr=Symbol("bodyConsumedDirectly"),bb=Symbol("bodyLockReader"),js=Symbol("abortReason"),ic=()=>new TypeError("Body is unusable"),Ds=()=>Promise.reject(ic()),QN=new TextDecoder,eM=t=>{if(t[hr])return Ds();t[hr]=!0},tM=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),rM=t=>(t[Pb]||=Tb(t[So])).get("content-type")||"",nM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,oM=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}},sM=t=>{if(!nM.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.`)},Qp=(t,e,r)=>{if(t[hr])return Ds();let n=t.method;if(n==="GET"||n==="HEAD")return t[Lr]()[e]();let o=sM(n);if(o)return Promise.reject(o);if(t[fr]&&n!=="TRACE")return t[fr][e]();let s=eM(t);if(s)return s;let i=iM(t);if(i){let a=Promise.resolve(r(i,t));return t[Dr]=void 0,a}return aM(t).then(a=>{let c=r(a,t);return t[Dr]=void 0,c})},iM=t=>{let e=t[So];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},wb=(t,e)=>{if(e.errored)return e.errored;let r=t[js];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},aM=t=>{if(t[Dr])return Promise.resolve(t[Dr]);if(t[oc])return t[oc];let e=t[So];if(e.readableDidRead)return Ds();let r=sc(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Dr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,f(),g())},u=g=>{let h=e.errored??g;return!Yp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=sc(e,i);_ instanceof Error?s(_):_===void 0?s(g??wb(t,e)):(t[Dr]=_,o(_))}),!0)},l=g=>{i.push(zb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[Dr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(wb(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[oc]=void 0};e.on("data",l),e.on("end",d),e.on("error",m),e.on("close",p),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?m(e.errored):e.destroyed&&p())})});return t[oc]=n,n},Xt={get method(){return this[Rb]},get url(){return this[Zs]},get headers(){return this[Pb]||=Tb(this[So])},[Vp](t){this[js]===void 0&&(this[js]=t);let e=this[Ms];e&&!e.signal.aborted&&e.abort(t)},[Bp](){return this[Ms]||=new AbortController,this[js]!==void 0&&!this[Ms].signal.aborted&&this[Ms].abort(this[js]),this[Ms]},[Lr](){let t=this[Bp]();if(this[fr])return this[fr];let e=this.method;if(this[hr]&&!(e==="GET"||e==="HEAD")){this[Dr]=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 ko(this[Zs],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[fr]=n}return this[fr]=YN(this.method,this[Zs],this.headers,this[So],t)},get body(){if(!this[hr])return this[Lr]().body;let t=this[Lr]();return!this[bb]&&t.body&&(this[bb]=t.body.getReader()),t.body},get bodyUsed(){return this[hr]?!0:this[fr]?this[fr].bodyUsed:!1}};Object.defineProperty(Xt,"signal",{get(){return this[Bp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Xt,t,{get(){return this[Lr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Xt,t,{value:function(){if(this[hr]){if(t==="clone")throw ic();return Ds()}return this[Lr]()[t]()}})});Object.defineProperty(Xt,"text",{value:function(){return Qp(this,"text",t=>QN.decode(t))}});Object.defineProperty(Xt,"arrayBuffer",{value:function(){return Qp(this,"arrayBuffer",t=>tM(t))}});Object.defineProperty(Xt,"blob",{value:function(){return Qp(this,"blob",(t,e)=>{let r=rM(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Xt,"json",{value:function(){return this[hr]?Ds():this.text().then(JSON.parse)}});Object.defineProperty(Xt,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[fr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Xt,ko.prototype);cM=(t,e)=>{let r=Object.create(Xt);r[So]=t,r[Rb]=oM(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof mr)throw new Nt("Absolute URL for :path is not allowed in HTTP/2");try{Fp(n),r[Zs]=new URL(n).href}catch(i){throw new Nt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof mr?t.authority:t.headers.host)||e;if(!o)throw new Nt("Missing host header");let s;if(t instanceof mr){if(s=t.scheme,!(s==="http"||s==="https"))throw new Nt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Zs]=JN(s,o,n)}catch(i){throw i instanceof Nt?i:new Nt("Invalid URL",{cause:i})}return r},Rn="text/plain; charset=UTF-8",Jp=Symbol("responseCache"),$o=Symbol("getResponseCache"),pr=Symbol("cache"),ac=global.Response,Gt=class Ib{#e;#t;[$o](){let e=this[pr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[pr],this[Jp]||=new ac(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 ac){let o=r[Jp];if(o){this.#t=o,this[$o]();return}this.#t=r instanceof Ib?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[pr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[pr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Rn}))),e[2]):this[$o]().headers}get status(){return this[pr]?.[0]??this[$o]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Gt.prototype,t,{get(){return this[$o]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Gt.prototype,t,{value:function(){return this[$o]()[t]()}})});Object.defineProperty(Gt.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[Jp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Gt,ac);Object.setPrototypeOf(Gt.prototype,ac.prototype);uM=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,lM=t=>t instanceof URL?t.href:uM.test(t)?t:new URL(t).href,dM=new Set([301,302,303,307,308]);Object.defineProperty(Gt,"redirect",{value:function(e,r=302){if(!dM.has(r))throw new RangeError("Invalid status code");return new Gt(null,{status:r,headers:{location:lM(e)}})},writable:!0,configurable:!0});Object.defineProperty(Gt,"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 Gt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Wp=(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},cc=Symbol("outgoingEnded"),kb=Symbol("incomingDraining"),pM=500,mM=64*1024*1024,Ab=t=>{let e=t;if(t.destroyed||e[kb])return;if(e[kb]=!0,t instanceof mr){try{t.stream?.close?.(qN.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,pM);s.unref?.();let i=a=>{r+=a.length,r>mM&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},hM=(t,e,r,n)=>()=>{e.errored?(vb(e),t[Vp](e.errored.toString())):(!r.writableFinished||e instanceof mr&&e.aborted)&&(vb(e),t[Vp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{Ab(e)})})},gM=t=>{if(!(pr in t))return!1;let e=t[pr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},yM=()=>new Response(null,{status:400}),Ob=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),uc=(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 instanceof LN&&(e._contentLength=null),e.writeHead(500,{"Content-Type":"text/plain"})),e.end(`Error: ${r.message}`),e.destroy(r))},Kp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},Nb=(t,e,r)=>{let n=t;return n._contentLength===null&&n._hasBody&&n.useChunkedEncodingByDefault&&!n._removedContLen&&e>=200&&e!==204&&e!==304&&!t.hasHeader("content-length")&&!t.hasHeader("transfer-encoding")&&!t.hasHeader("trailer")?(n._contentLength=r,!0):!1},Up=(t,e,r)=>{Nb(t,e,r)?t.writeHead(e,{"Content-Type":Rn}):t.writeHead(e,{"Content-Type":Rn,"Content-Length":r})},Mb=async(t,e)=>{let[r,n,o]=t[pr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(Up(e,r,Buffer.byteLength(n)),e.end(n)):n instanceof Uint8Array?(Up(e,r,n.byteLength),e.end(n)):n instanceof Blob?(Up(e,r,n.size),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Rn}),Kp(e),await $b(n,e)?.catch(c=>uc(c,e))),e[cc]?.();return}let s=!1,i=!1,a=!0;if(o instanceof Headers)s=o.has("content-length"),o=Wp(o,n===null?void 0:Rn);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=Wp(c,n===null?void 0:Rn)}else{i=!0;for(let c in o){if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}(c.length===17&&c.toLowerCase()==="transfer-encoding"||c.length===7&&c.toLowerCase()==="trailer")&&(a=!1)}}if(!s){let c;typeof n=="string"?c=Buffer.byteLength(n):n instanceof Uint8Array?c=n.byteLength:n instanceof Blob&&(c=n.size),c!==void 0&&(!i||!a||!Nb(e,r,c))&&(i&&(o={...o}),o["Content-Length"]=c)}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 $b(n,e)?.catch(c=>uc(c,e))),e[cc]?.()},jb=t=>typeof t.then=="function",_M=async(t,e,r={})=>{if(jb(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(Ob);if(pr in t)return Mb(t,e);let n=Wp(t.headers,t.body===null?void 0:Rn);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 fM(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&&Kp(e),await Cb(o,e,a))}else n[fb]||(e.writeHead(t.status,n),e.end());e[cc]?.()},em=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ko&&(Object.defineProperty(global,"Request",{value:ko}),Object.defineProperty(global,"Response",{value:Gt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",hM(i,n,o,a)))};try{if(i=cM(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Eb]=!0,n instanceof mr&&(o[cc]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!jb(s)&&gM(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||Ab(n)}),Mb(s,o);u()}catch(l){if(s)return uc(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:WN(l)),!s)return}else i?s=Ob(l):s=yM()}try{return await _M(s,o,e)}catch(l){return uc(l,o)}}},vM=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??""}},xM=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}},bM=()=>Symbol("connection"),wM=Symbol("CONNECTION_SYMBOL_KEY"),$M=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),JU=mb(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[$M];if(!o||!n.incoming)return new Response(null,{status:500});let s=bM();return n[wM]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,m)=>{a.push([d,m])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,m){i.close(d,m)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,m){i.send(d,{compress:m?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,m)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{e?.onMessage?.(new MessageEvent("message",{data:m?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(g){(r?.onError??console.error)(g)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,m)=>{l(d,m)}),i.on("close",(d,m)=>{try{e?.onClose?.(new vM("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new xM("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var Ub=z(tm=>{"use strict";var Db=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,kM=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Lb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,SM=/\\([\u000b\u0020-\u00ff])/g,TM=/([\\"])/g,qb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;tm.format=EM;tm.parse=zM;function EM(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!qb.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],!Lb.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+PM(e[o])}return n}function zM(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?RM(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(!qb.test(n))throw new TypeError("invalid media type");var o=new IM(n.toLowerCase());if(r!==-1){var s,i,a;for(Db.lastIndex=r;i=Db.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(SM,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function RM(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 PM(t){var e=String(t);if(Lb.test(e))return e;if(e.length>0&&!kM.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(TM,"\\$1")+'"'}function IM(t){this.parameters=Object.create(null),this.type=t}});function CM(t){if(t)try{return Fb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Hb(t){return t==="application/json"?!0:CM(t)==="application/json"}var Fb,Bb=X(()=>{Fb=pc(Ub(),1)});function Vb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function Jb(t){if(t===void 0)return 4194304;if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function Wb(t,e=4194304){if(Number(t.headers.get("content-length"))>e)return{tooLarge:!0};if(t.body===null)return{tooLarge:!1,text:""};let r=t.body.getReader(),n=new TextDecoder,o=0,s="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(o+=a.byteLength,o>e)return{tooLarge:!0};s+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:s+n.decode()}}var Kb=X(()=>{});function Gb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Xb=X(()=>{});var lc,Yb=X(()=>{Bb();Kb();Xb();Sr();lc=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,this._maxRequestBodySize=Jb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=Gb(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:
@@ -48,75 +48,75 @@ data:
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(!Ab(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{let v=await jb(e,this._maxRequestBodySize);if(v.tooLarge){let y=Nb(this._maxRequestBodySize);return this.onerror?.(new Error(y)),this.createJsonErrorResponse(413,-32e3,y)}i=JSON.parse(v.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(i)&&i.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);let a;try{Array.isArray(i)?a=i.map(v=>Fo.parse(v)):a=[Fo.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(Ml);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(tr)){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=>Ml(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??cg;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)tr(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let p=new TextEncoder,f,g,h=new ReadableStream({start:v=>{f=v},cancel:()=>{g!==void 0&&clearInterval(g),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)tr(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,p,l,m);for(let v of a){let y,x;tr(v)&&this._eventStore&&m>="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(l)?.cleanup(),this._resumableStreams.delete(l);for(let y of a)tr(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(g=this.startKeepAlive(f,p)),new Response(h,{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&&!Fn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Fn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Fn.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((rr(e)||Un(e))&&(n=e.id),n===void 0){if(rr(e)||Un(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(rr(e)||Un(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 Fb={};$o(Fb,{StreamableHTTPServerTransport:()=>Yp});var Yp,Ub=X(()=>{Eb();qb();Yp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new ac(e),this._requestListener=Kp(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 Kp(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 D={};$o(D,{BRAND:()=>Sw,DIRTY:()=>qr,EMPTY_PATH:()=>nw,INVALID:()=>L,NEVER:()=>c$,OK:()=>je,ParseStatus:()=>Pe,Schema:()=>J,ZodAny:()=>hr,ZodArray:()=>Qt,ZodBigInt:()=>Ur,ZodBoolean:()=>Hr,ZodBranded:()=>So,ZodCatch:()=>tn,ZodDate:()=>Br,ZodDefault:()=>en,ZodDiscriminatedUnion:()=>Ls,ZodEffects:()=>dt,ZodEnum:()=>Yr,ZodError:()=>Ge,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Fs,ZodIntersection:()=>Kr,ZodIssueCode:()=>k,ZodLazy:()=>Gr,ZodLiteral:()=>Xr,ZodMap:()=>Cn,ZodNaN:()=>On,ZodNativeEnum:()=>Qr,ZodNever:()=>wt,ZodNull:()=>Jr,ZodNullable:()=>Mt,ZodNumber:()=>Fr,ZodObject:()=>Ye,ZodOptional:()=>Xe,ZodParsedType:()=>P,ZodPipeline:()=>To,ZodPromise:()=>gr,ZodReadonly:()=>rn,ZodRecord:()=>qs,ZodSchema:()=>J,ZodSet:()=>An,ZodString:()=>mr,ZodSymbol:()=>Pn,ZodTransformer:()=>dt,ZodTuple:()=>Nt,ZodType:()=>J,ZodUndefined:()=>Vr,ZodUnion:()=>Wr,ZodUnknown:()=>Yt,ZodVoid:()=>In,addIssueToContext:()=>E,any:()=>Ow,array:()=>Zw,bigint:()=>Rw,boolean:()=>dm,coerce:()=>a$,custom:()=>cm,date:()=>Pw,datetimeRegex:()=>im,defaultErrorMap:()=>Gt,discriminatedUnion:()=>qw,effect:()=>Qw,enum:()=>Gw,function:()=>Jw,getErrorMap:()=>En,getParsedType:()=>Ot,instanceof:()=>Ew,intersection:()=>Fw,isAborted:()=>Zs,isAsync:()=>zn,isDirty:()=>Ds,isValid:()=>pr,late:()=>Tw,lazy:()=>Ww,literal:()=>Kw,makeIssue:()=>ko,map:()=>Bw,nan:()=>zw,nativeEnum:()=>Xw,never:()=>Mw,null:()=>Aw,nullable:()=>t$,number:()=>lm,object:()=>mc,objectUtil:()=>dc,oboolean:()=>i$,onumber:()=>s$,optional:()=>e$,ostring:()=>o$,pipeline:()=>n$,preprocess:()=>r$,promise:()=>Yw,quotelessJson:()=>ew,record:()=>Hw,set:()=>Vw,setErrorMap:()=>rw,strictObject:()=>Dw,string:()=>um,symbol:()=>Iw,transformer:()=>Qw,tuple:()=>Uw,undefined:()=>Cw,union:()=>Lw,unknown:()=>Nw,util:()=>Y,void:()=>jw});var Y;(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})(Y||(Y={}));var dc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(dc||(dc={}));var P=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ot=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var k=Y.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"]),ew=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ge=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,Y.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()}};Ge.create=t=>new Ge(t);var tw=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${Y.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}"`:Y.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,Y.assertNever(t)}return{message:r}},Gt=tw;var tm=Gt;function rw(t){tm=t}function En(){return tm}var ko=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}},nw=[];function E(t,e){let r=En(),n=ko({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Gt?void 0:Gt].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 L;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 L;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}}},L=Object.freeze({status:"aborted"}),qr=t=>({status:"dirty",value:t}),je=t=>({status:"valid",value:t}),Zs=t=>t.status==="aborted",Ds=t=>t.status==="dirty",pr=t=>t.status==="valid",zn=t=>typeof Promise<"u"&&t instanceof Promise;var M;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(M||(M={}));var lt=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}},rm=(t,e)=>{if(pr(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 Ge(t.common.issues);return this._error=r,this._error}}};function B(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 J=class{get description(){return this._def.description}_getType(e){return Ot(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ot(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:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zn(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:Ot(e)},o=this._parseSync({data:e,path:n.path,parent:n});return rm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ot(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return pr(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=>pr(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:Ot(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(zn(o)?o:Promise.resolve(o));return rm(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 dt({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 Xe.create(this,this._def)}nullable(){return Mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return gr.create(this,this._def)}or(e){return Wr.create([this,e],this._def)}and(e){return Kr.create(this,e,this._def)}transform(e){return new dt({...B(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new en({...B(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new So({typeName:S.ZodBranded,type:this,...B(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new tn({...B(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 To.create(this,e)}readonly(){return rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ow=/^c[^\s-]{8,}$/i,sw=/^[0-9a-z]+$/,iw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aw=/^[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,cw=/^[a-z0-9_-]{21}$/i,uw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lw=/^[-+]?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)?)??$/,dw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",fc,pw=/^(?:(?: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])$/,mw=/^(?:(?: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])$/,hw=/^(([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]))$/,gw=/^(([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])$/,yw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_w=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,om="((\\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])))",vw=new RegExp(`^${om}$`);function sm(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 xw(t){return new RegExp(`^${sm(t)}$`)}function im(t){let e=`${om}T${sm(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 bw(t,e){return!!((e==="v4"||!e)&&pw.test(t)||(e==="v6"||!e)&&hw.test(t))}function ww(t,e){if(!uw.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 $w(t,e){return!!((e==="v4"||!e)&&mw.test(t)||(e==="v6"||!e)&&gw.test(t))}var mr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.string,received:s.parsedType}),L}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")dw.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")fc||(fc=new RegExp(fw,"u")),fc.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")aw.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")cw.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")ow.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")sw.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")iw.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"?im(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"?vw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?xw(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"?lw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?bw(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"?ww(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"?$w(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"?yw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?_w.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):Y.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,...M.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...M.errToObj(e)})}url(e){return this._addCheck({kind:"url",...M.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...M.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...M.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...M.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...M.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...M.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...M.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...M.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...M.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...M.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...M.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...M.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,...M.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,...M.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...M.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...M.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...M.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...M.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...M.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...M.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...M.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...M.errToObj(r)})}nonempty(e){return this.min(1,M.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}};mr.create=t=>new mr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...B(t)});function kw(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 Fr=class t extends J{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)!==P.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.number,received:s.parsedType}),L}let n,o=new Pe;for(let s of this._def.checks)s.kind==="int"?Y.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"?kw(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()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:M.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:M.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.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"&&Y.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)}};Fr.create=t=>new Fr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...B(t)});var Ur=class t extends J{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)!==P.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()):Y.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.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:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.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}};Ur.create=t=>new Ur({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...B(t)});var Hr=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.boolean,received:n.parsedType}),L}return je(e.data)}};Hr.create=t=>new Hr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...B(t)});var Br=class t extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.date,received:s.parsedType}),L}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),L}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()):Y.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:M.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:M.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}};Br.create=t=>new Br({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...B(t)});var Pn=class extends J{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.symbol,received:n.parsedType}),L}return je(e.data)}};Pn.create=t=>new Pn({typeName:S.ZodSymbol,...B(t)});var Vr=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.undefined,received:n.parsedType}),L}return je(e.data)}};Vr.create=t=>new Vr({typeName:S.ZodUndefined,...B(t)});var Jr=class extends J{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.null,received:n.parsedType}),L}return je(e.data)}};Jr.create=t=>new Jr({typeName:S.ZodNull,...B(t)});var hr=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return je(e.data)}};hr.create=t=>new hr({typeName:S.ZodAny,...B(t)});var Yt=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return je(e.data)}};Yt.create=t=>new Yt({typeName:S.ZodUnknown,...B(t)});var wt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.never,received:r.parsedType}),L}};wt.create=t=>new wt({typeName:S.ZodNever,...B(t)});var In=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.void,received:n.parsedType}),L}return je(e.data)}};In.create=t=>new In({typeName:S.ZodVoid,...B(t)});var Qt=class t extends J{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==P.array)return E(r,{code:k.invalid_type,expected:P.array,received:r.parsedType}),L;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 lt(r,i,r.path,a)))).then(i=>Pe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new lt(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:M.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:M.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:M.toString(r)}})}nonempty(e){return this.min(1,e)}};Qt.create=(t,e)=>new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...B(e)});function Rn(t){if(t instanceof Ye){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Xe.create(Rn(n))}return new Ye({...t._def,shape:()=>e})}else return t instanceof Qt?new Qt({...t._def,type:Rn(t.element)}):t instanceof Xe?Xe.create(Rn(t.unwrap())):t instanceof Mt?Mt.create(Rn(t.unwrap())):t instanceof Nt?Nt.create(t.items.map(e=>Rn(e))):t}var Ye=class t extends J{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=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:P.object,received:u.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof wt&&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 lt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof wt){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 lt(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,m=await l.value;u.push({key:d,value:m,alwaysSet:l.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(n,u)):Pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return M.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:M.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 Y.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 Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Rn(this)}partial(e){let r={};for(let n of Y.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 Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Xe;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return am(Y.objectKeys(this.shape))}};Ye.create=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strip",catchall:wt.create(),typeName:S.ZodObject,...B(e)});Ye.strictCreate=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strict",catchall:wt.create(),typeName:S.ZodObject,...B(e)});Ye.lazycreate=(t,e)=>new Ye({shape:t,unknownKeys:"strip",catchall:wt.create(),typeName:S.ZodObject,...B(e)});var Wr=class extends J{_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 Ge(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),L}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 Ge(c));return E(r,{code:k.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Wr.create=(t,e)=>new Wr({options:t,typeName:S.ZodUnion,...B(e)});var Xt=t=>t instanceof Gr?Xt(t.schema):t instanceof dt?Xt(t.innerType()):t instanceof Xr?[t.value]:t instanceof Yr?t.options:t instanceof Qr?Y.objectValues(t.enum):t instanceof en?Xt(t._def.innerType):t instanceof Vr?[void 0]:t instanceof Jr?[null]:t instanceof Xe?[void 0,...Xt(t.unwrap())]:t instanceof Mt?[null,...Xt(t.unwrap())]:t instanceof So||t instanceof rn?Xt(t.unwrap()):t instanceof tn?Xt(t._def.innerType):[],Ls=class t extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return E(r,{code:k.invalid_type,expected:P.object,received:r.parsedType}),L;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]}),L)}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=Xt(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,...B(n)})}};function pc(t,e){let r=Ot(t),n=Ot(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=pc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.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=pc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Kr=class extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Zs(s)||Zs(i))return L;let a=pc(s.value,i.value);return a.valid?((Ds(s)||Ds(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),L)};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}))}};Kr.create=(t,e,r)=>new Kr({left:t,right:e,typeName:S.ZodIntersection,...B(r)});var Nt=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return E(n,{code:k.invalid_type,expected:P.array,received:n.parsedType}),L;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"}),L;!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 lt(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})}};Nt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nt({items:t,typeName:S.ZodTuple,rest:null,...B(e)})};var qs=class t extends J{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!==P.object)return E(n,{code:k.invalid_type,expected:P.object,received:n.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new lt(n,a,n.path,a)),value:i._parse(new lt(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 J?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...B(n)}):new t({keyType:mr.create(),valueType:e,typeName:S.ZodRecord,...B(r)})}},Cn=class extends J{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!==P.map)return E(n,{code:k.invalid_type,expected:P.map,received:n.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new lt(n,a,n.path,[u,"key"])),value:s._parse(new lt(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 L;(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 L;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Cn.create=(t,e,r)=>new Cn({valueType:e,keyType:t,typeName:S.ZodMap,...B(r)});var An=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return E(n,{code:k.invalid_type,expected:P.set,received:n.parsedType}),L;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 L;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 lt(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:M.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:M.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};An.create=(t,e)=>new An({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...B(e)});var Fs=class t extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return E(r,{code:k.invalid_type,expected:P.function,received:r.parsedType}),L;function n(a,c){return ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,En(),Gt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return ko({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,En(),Gt].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 gr){let a=this;return je(async function(...c){let u=new Ge([]),l=await a._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw u.addIssue(o(d,p)),u})})}else{let a=this;return je(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ge([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ge([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:Nt.create(e).rest(Yt.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||Nt.create([]).rest(Yt.create()),returns:r||Yt.create(),typeName:S.ZodFunction,...B(n)})}},Gr=class extends J{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})}};Gr.create=(t,e)=>new Gr({getter:t,typeName:S.ZodLazy,...B(e)});var Xr=class extends J{_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}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xr.create=(t,e)=>new Xr({value:t,typeName:S.ZodLiteral,...B(e)});function am(t,e){return new Yr({values:t,typeName:S.ZodEnum,...B(e)})}var Yr=class t extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:Y.joinValues(n),received:r.parsedType,code:k.invalid_type}),L}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}),L}return je(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})}};Yr.create=am;var Qr=class extends J{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=Y.objectValues(r);return E(n,{expected:Y.joinValues(o),received:n.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),L}return je(e.data)}get enum(){return this._def.values}};Qr.create=(t,e)=>new Qr({values:t,typeName:S.ZodNativeEnum,...B(e)});var gr=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:P.promise,received:r.parsedType}),L;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return je(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};gr.create=(t,e)=>new gr({type:t,typeName:S.ZodPromise,...B(e)});var dt=class extends J{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 L;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?qr(c.value):r.value==="dirty"?qr(c.value):c});{if(r.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?qr(a.value):r.value==="dirty"?qr(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"?L:(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"?L:(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(!pr(i))return L;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=>pr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):L);Y.assertNever(o)}};dt.create=(t,e,r)=>new dt({schema:t,typeName:S.ZodEffects,effect:e,...B(r)});dt.createWithPreprocess=(t,e,r)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...B(r)});var Xe=class extends J{_parse(e){return this._getType(e)===P.undefined?je(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xe.create=(t,e)=>new Xe({innerType:t,typeName:S.ZodOptional,...B(e)});var Mt=class extends J{_parse(e){return this._getType(e)===P.null?je(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:S.ZodNullable,...B(e)});var en=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};en.create=(t,e)=>new en({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var tn=class extends J{_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 zn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ge(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};tn.create=(t,e)=>new tn({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var On=class extends J{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};On.create=t=>new On({typeName:S.ZodNaN,...B(t)});var Sw=Symbol("zod_brand"),So=class extends J{_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}},To=class t extends J{_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"?L:s.status==="dirty"?(r.dirty(),qr(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"?L: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})}},rn=class extends J{_parse(e){let r=this._def.innerType._parse(e),n=o=>(pr(o)&&(o.value=Object.freeze(o.value)),o);return zn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};rn.create=(t,e)=>new rn({innerType:t,typeName:S.ZodReadonly,...B(e)});function nm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function cm(t,e={},r){return t?hr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=nm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=nm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):hr.create()}var Tw={object:Ye.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 Ew=(t,e={message:`Input not instance of ${t.name}`})=>cm(r=>r instanceof t,e),um=mr.create,lm=Fr.create,zw=On.create,Rw=Ur.create,dm=Hr.create,Pw=Br.create,Iw=Pn.create,Cw=Vr.create,Aw=Jr.create,Ow=hr.create,Nw=Yt.create,Mw=wt.create,jw=In.create,Zw=Qt.create,mc=Ye.create,Dw=Ye.strictCreate,Lw=Wr.create,qw=Ls.create,Fw=Kr.create,Uw=Nt.create,Hw=qs.create,Bw=Cn.create,Vw=An.create,Jw=Fs.create,Ww=Gr.create,Kw=Xr.create,Gw=Yr.create,Xw=Qr.create,Yw=gr.create,Qw=dt.create,e$=Xe.create,t$=Mt.create,r$=dt.createWithPreprocess,n$=To.create,o$=()=>um().optional(),s$=()=>lm().optional(),i$=()=>dm().optional(),a$={string:(t=>mr.create({...t,coerce:!0})),number:(t=>Fr.create({...t,coerce:!0})),boolean:(t=>Hr.create({...t,coerce:!0})),bigint:(t=>Ur.create({...t,coerce:!0})),date:(t=>Br.create({...t,coerce:!0}))};var c$=L;Ue();Ue();Ue();Ue();var yk=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");le.init(t,e),t.def=e,t.parse=(r,n)=>Rc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>sn(t,r,n),t.parseAsync=async(r,n)=>Ic(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>an(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)=>at(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var _k=w("ZodMiniObject",(t,e)=>{ei.init(t,e),yk.init(t,e),ee.defineLazy(t,"shape",()=>e.shape)});function yl(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new _k(r)}Ue();ri();function Dt(t){return!!t._zod}function ln(t){let e=Object.values(t);if(e.length===0)return yl({});let r=e.every(Dt),n=e.every(o=>!Dt(o));if(r)return yl(t);if(n)return mc(t);throw new Error("Mixed Zod versions detected in object shape.")}function vr(t,e){return Dt(t)?sn(t,e):t.safeParse(e)}async function li(t,e){return Dt(t)?await an(t,e):await t.safeParseAsync(e)}function xr(t){if(!t)return;let e;if(Dt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Dn(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 ln(t)}}if(Dt(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 xk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function di(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 ${xk(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 Ah(t){return t.description}function Oh(t){if(Dt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ln(t){if(Dt(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}wr();function $r(t){return t==="completed"||t==="failed"||t==="cancelled"}var Sg=Symbol("Let zodToJsonSchema decide on which parser to use");var kg={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"},Tg=t=>typeof t=="string"?{...kg,name:t}:{...kg,...t};var Eg=t=>{let e=Tg(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 Jl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function re(t,e,r,n,o){t[e]=r,Jl(t,e,n,o)}var Mi=(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 $e(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Mi(e,t.currentPath):e.join("/")}}function zg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&re(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&re(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(re(r,"minItems",t.exactLength.value,t.exactLength.message,e),re(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Rg(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?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Pg(){return{type:"boolean"}}function ji(t,e){return F(t.type._def,e)}var Ig=(t,e)=>F(t.innerType._def,e);function Wl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Wl(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 VT(t,e)}}var VT=(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":re(r,"minimum",n.value,n.message,e);break;case"max":re(r,"maximum",n.value,n.message,e);break}return r};function Cg(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}function Ag(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):$e(e)}function Og(t){return{type:"string",enum:Array.from(t.values)}}var JT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ng(t,e){let r=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(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(JT(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 Mg(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 Kl,kt={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:()=>(Kl===void 0&&(Kl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Kl),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 Zi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":re(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":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Be(r,kt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Be(r,n.regex,n.message,e);break;case"cuid":Be(r,kt.cuid,n.message,e);break;case"cuid2":Be(r,kt.cuid2,n.message,e);break;case"startsWith":Be(r,RegExp(`^${Gl(n.value,e)}`),n.message,e);break;case"endsWith":Be(r,RegExp(`${Gl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Be(r,RegExp(Gl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Be(r,kt.base64url,n.message,e);break;case"jwt":Be(r,kt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Be(r,kt.ipv4Cidr,n.message,e),n.version!=="v4"&&Be(r,kt.ipv6Cidr,n.message,e);break}case"emoji":Be(r,kt.emoji(),n.message,e);break;case"ulid":{Be(r,kt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Be(r,kt.base64,n.message,e);break}}break}case"nanoid":Be(r,kt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Gl(t,e){return e.patternStrategy==="escape"?KT(t):t}var WT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function KT(t){let e="";for(let r=0;r<t.length;r++)WT.has(t[r])||(e+="\\"),e+=t[r];return e}function St(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}}})):re(t,"format",e,r,n)}function Be(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:jg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):re(t,"pattern",jg(e,n),r,n)}function jg(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(!Hb(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{let v=await Wb(e,this._maxRequestBodySize);if(v.tooLarge){let y=Vb(this._maxRequestBodySize);return this.onerror?.(new Error(y)),this.createJsonErrorResponse(413,-32e3,y)}i=JSON.parse(v.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(i)&&i.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);let a;try{Array.isArray(i)?a=i.map(v=>Bo.parse(v)):a=[Bo.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(Dl);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(nr)){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=>Dl(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??pg;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)nr(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let p=new TextEncoder,f,g,h=new ReadableStream({start:v=>{f=v},cancel:()=>{g!==void 0&&clearInterval(g),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)nr(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,p,l,m);for(let v of a){let y,x;nr(v)&&this._eventStore&&m>="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(l)?.cleanup(),this._resumableStreams.delete(l);for(let y of a)nr(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(g=this.startKeepAlive(f,p)),new Response(h,{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&&!Vn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.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((or(e)||Jn(e))&&(n=e.id),n===void 0){if(or(e)||Jn(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(or(e)||Jn(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 Qb={};To(Qb,{StreamableHTTPServerTransport:()=>nm});var nm,ew=X(()=>{Zb();Yb();nm=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new lc(e),this._requestListener=em(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 em(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 D={};To(D,{BRAND:()=>Mw,DIRTY:()=>Fr,EMPTY_PATH:()=>mw,INVALID:()=>L,NEVER:()=>v$,OK:()=>Ze,ParseStatus:()=>Ie,Schema:()=>J,ZodAny:()=>_r,ZodArray:()=>tr,ZodBigInt:()=>Br,ZodBoolean:()=>Vr,ZodBranded:()=>zo,ZodCatch:()=>nn,ZodDate:()=>Jr,ZodDefault:()=>rn,ZodDiscriminatedUnion:()=>Fs,ZodEffects:()=>ft,ZodEnum:()=>en,ZodError:()=>Xe,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Bs,ZodIntersection:()=>Xr,ZodIssueCode:()=>k,ZodLazy:()=>Yr,ZodLiteral:()=>Qr,ZodMap:()=>Mn,ZodNaN:()=>Zn,ZodNativeEnum:()=>tn,ZodNever:()=>kt,ZodNull:()=>Kr,ZodNullable:()=>Dt,ZodNumber:()=>Hr,ZodObject:()=>Qe,ZodOptional:()=>Ye,ZodParsedType:()=>P,ZodPipeline:()=>Ro,ZodPromise:()=>vr,ZodReadonly:()=>on,ZodRecord:()=>Hs,ZodSchema:()=>J,ZodSet:()=>jn,ZodString:()=>yr,ZodSymbol:()=>On,ZodTransformer:()=>ft,ZodTuple:()=>Zt,ZodType:()=>J,ZodUndefined:()=>Wr,ZodUnion:()=>Gr,ZodUnknown:()=>er,ZodVoid:()=>Nn,addIssueToContext:()=>E,any:()=>Bw,array:()=>Kw,bigint:()=>Lw,boolean:()=>gm,coerce:()=>_$,custom:()=>pm,date:()=>qw,datetimeRegex:()=>dm,defaultErrorMap:()=>Yt,discriminatedUnion:()=>Yw,effect:()=>l$,enum:()=>a$,function:()=>o$,getErrorMap:()=>In,getParsedType:()=>jt,instanceof:()=>Zw,intersection:()=>Qw,isAborted:()=>qs,isAsync:()=>Cn,isDirty:()=>Us,isValid:()=>gr,late:()=>jw,lazy:()=>s$,literal:()=>i$,makeIssue:()=>Eo,map:()=>r$,nan:()=>Dw,nativeEnum:()=>c$,never:()=>Jw,null:()=>Hw,nullable:()=>f$,number:()=>hm,object:()=>yc,objectUtil:()=>mc,oboolean:()=>y$,onumber:()=>g$,optional:()=>d$,ostring:()=>h$,pipeline:()=>m$,preprocess:()=>p$,promise:()=>u$,quotelessJson:()=>dw,record:()=>t$,set:()=>n$,setErrorMap:()=>pw,strictObject:()=>Gw,string:()=>mm,symbol:()=>Uw,transformer:()=>l$,tuple:()=>e$,undefined:()=>Fw,union:()=>Xw,unknown:()=>Vw,util:()=>Y,void:()=>Ww});var Y;(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})(Y||(Y={}));var mc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(mc||(mc={}));var P=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),jt=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var k=Y.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"]),dw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Xe=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,Y.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()}};Xe.create=t=>new Xe(t);var fw=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${Y.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}"`:Y.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,Y.assertNever(t)}return{message:r}},Yt=fw;var im=Yt;function pw(t){im=t}function In(){return im}var Eo=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}},mw=[];function E(t,e){let r=In(),n=Eo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Yt?void 0:Yt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=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 L;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 L;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}}},L=Object.freeze({status:"aborted"}),Fr=t=>({status:"dirty",value:t}),Ze=t=>({status:"valid",value:t}),qs=t=>t.status==="aborted",Us=t=>t.status==="dirty",gr=t=>t.status==="valid",Cn=t=>typeof Promise<"u"&&t instanceof Promise;var M;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(M||(M={}));var dt=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}},am=(t,e)=>{if(gr(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 Xe(t.common.issues);return this._error=r,this._error}}};function B(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 J=class{get description(){return this._def.description}_getType(e){return jt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:jt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:jt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Cn(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:jt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return am(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:jt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return gr(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=>gr(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:jt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Cn(o)?o:Promise.resolve(o));return am(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 ft({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 Ye.create(this,this._def)}nullable(){return Dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tr.create(this)}promise(){return vr.create(this,this._def)}or(e){return Gr.create([this,e],this._def)}and(e){return Xr.create(this,e,this._def)}transform(e){return new ft({...B(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new rn({...B(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new zo({typeName:S.ZodBranded,type:this,...B(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new nn({...B(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 Ro.create(this,e)}readonly(){return on.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},hw=/^c[^\s-]{8,}$/i,gw=/^[0-9a-z]+$/,yw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_w=/^[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,vw=/^[a-z0-9_-]{21}$/i,xw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bw=/^[-+]?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)?)??$/,ww=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hc,kw=/^(?:(?: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])$/,Sw=/^(?:(?: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])$/,Tw=/^(([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]))$/,Ew=/^(([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])$/,zw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,um="((\\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])))",Pw=new RegExp(`^${um}$`);function lm(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 Iw(t){return new RegExp(`^${lm(t)}$`)}function dm(t){let e=`${um}T${lm(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 Cw(t,e){return!!((e==="v4"||!e)&&kw.test(t)||(e==="v6"||!e)&&Tw.test(t))}function Aw(t,e){if(!xw.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 Ow(t,e){return!!((e==="v4"||!e)&&Sw.test(t)||(e==="v6"||!e)&&Ew.test(t))}var yr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.string,received:s.parsedType}),L}let n=new Ie,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")ww.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")hc||(hc=new RegExp($w,"u")),hc.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")_w.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")vw.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")hw.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")gw.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")yw.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"?dm(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"?Pw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Iw(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"?bw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Cw(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"?Aw(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"?Ow(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"?zw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Rw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):Y.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,...M.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...M.errToObj(e)})}url(e){return this._addCheck({kind:"url",...M.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...M.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...M.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...M.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...M.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...M.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...M.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...M.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...M.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...M.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...M.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...M.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,...M.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,...M.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...M.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...M.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...M.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...M.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...M.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...M.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...M.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...M.errToObj(r)})}nonempty(e){return this.min(1,M.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}};yr.create=t=>new yr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...B(t)});function Nw(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 Hr=class t extends J{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)!==P.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.number,received:s.parsedType}),L}let n,o=new Ie;for(let s of this._def.checks)s.kind==="int"?Y.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"?Nw(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()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:M.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:M.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.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"&&Y.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)}};Hr.create=t=>new Hr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...B(t)});var Br=class t extends J{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)!==P.bigint)return this._getInvalidInput(e);let n,o=new Ie;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()):Y.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.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:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.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}};Br.create=t=>new Br({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...B(t)});var Vr=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.boolean,received:n.parsedType}),L}return Ze(e.data)}};Vr.create=t=>new Vr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...B(t)});var Jr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.date,received:s.parsedType}),L}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),L}let n=new Ie,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()):Y.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:M.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:M.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}};Jr.create=t=>new Jr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...B(t)});var On=class extends J{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.symbol,received:n.parsedType}),L}return Ze(e.data)}};On.create=t=>new On({typeName:S.ZodSymbol,...B(t)});var Wr=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.undefined,received:n.parsedType}),L}return Ze(e.data)}};Wr.create=t=>new Wr({typeName:S.ZodUndefined,...B(t)});var Kr=class extends J{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.null,received:n.parsedType}),L}return Ze(e.data)}};Kr.create=t=>new Kr({typeName:S.ZodNull,...B(t)});var _r=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return Ze(e.data)}};_r.create=t=>new _r({typeName:S.ZodAny,...B(t)});var er=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ze(e.data)}};er.create=t=>new er({typeName:S.ZodUnknown,...B(t)});var kt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.never,received:r.parsedType}),L}};kt.create=t=>new kt({typeName:S.ZodNever,...B(t)});var Nn=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.void,received:n.parsedType}),L}return Ze(e.data)}};Nn.create=t=>new Nn({typeName:S.ZodVoid,...B(t)});var tr=class t extends J{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==P.array)return E(r,{code:k.invalid_type,expected:P.array,received:r.parsedType}),L;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 dt(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new dt(r,i,r.path,a)));return Ie.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:M.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:M.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:M.toString(r)}})}nonempty(e){return this.min(1,e)}};tr.create=(t,e)=>new tr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...B(e)});function An(t){if(t instanceof Qe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ye.create(An(n))}return new Qe({...t._def,shape:()=>e})}else return t instanceof tr?new tr({...t._def,type:An(t.element)}):t instanceof Ye?Ye.create(An(t.unwrap())):t instanceof Dt?Dt.create(An(t.unwrap())):t instanceof Zt?Zt.create(t.items.map(e=>An(e))):t}var Qe=class t extends J{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=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:P.object,received:u.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof kt&&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 dt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof kt){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 dt(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,m=await l.value;u.push({key:d,value:m,alwaysSet:l.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(n,u)):Ie.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return M.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:M.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 Y.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 Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return An(this)}partial(e){let r={};for(let n of Y.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 Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ye;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return fm(Y.objectKeys(this.shape))}};Qe.create=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...B(e)});Qe.strictCreate=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strict",catchall:kt.create(),typeName:S.ZodObject,...B(e)});Qe.lazycreate=(t,e)=>new Qe({shape:t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...B(e)});var Gr=class extends J{_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 Xe(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),L}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 Xe(c));return E(r,{code:k.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Gr.create=(t,e)=>new Gr({options:t,typeName:S.ZodUnion,...B(e)});var Qt=t=>t instanceof Yr?Qt(t.schema):t instanceof ft?Qt(t.innerType()):t instanceof Qr?[t.value]:t instanceof en?t.options:t instanceof tn?Y.objectValues(t.enum):t instanceof rn?Qt(t._def.innerType):t instanceof Wr?[void 0]:t instanceof Kr?[null]:t instanceof Ye?[void 0,...Qt(t.unwrap())]:t instanceof Dt?[null,...Qt(t.unwrap())]:t instanceof zo||t instanceof on?Qt(t.unwrap()):t instanceof nn?Qt(t._def.innerType):[],Fs=class t extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return E(r,{code:k.invalid_type,expected:P.object,received:r.parsedType}),L;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]}),L)}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=Qt(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,...B(n)})}};function gc(t,e){let r=jt(t),n=jt(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=gc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.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=gc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Xr=class extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qs(s)||qs(i))return L;let a=gc(s.value,i.value);return a.valid?((Us(s)||Us(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),L)};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}))}};Xr.create=(t,e,r)=>new Xr({left:t,right:e,typeName:S.ZodIntersection,...B(r)});var Zt=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return E(n,{code:k.invalid_type,expected:P.array,received:n.parsedType}),L;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"}),L;!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 dt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Zt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:S.ZodTuple,rest:null,...B(e)})};var Hs=class t extends J{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!==P.object)return E(n,{code:k.invalid_type,expected:P.object,received:n.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new dt(n,a,n.path,a)),value:i._parse(new dt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof J?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...B(n)}):new t({keyType:yr.create(),valueType:e,typeName:S.ZodRecord,...B(r)})}},Mn=class extends J{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!==P.map)return E(n,{code:k.invalid_type,expected:P.map,received:n.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new dt(n,a,n.path,[u,"key"])),value:s._parse(new dt(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 L;(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 L;(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,...B(r)});var jn=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return E(n,{code:k.invalid_type,expected:P.set,received:n.parsedType}),L;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 L;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 dt(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:M.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:M.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};jn.create=(t,e)=>new jn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...B(e)});var Bs=class t extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return E(r,{code:k.invalid_type,expected:P.function,received:r.parsedType}),L;function n(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,In(),Yt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,In(),Yt].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 vr){let a=this;return Ze(async function(...c){let u=new Xe([]),l=await a._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw u.addIssue(o(d,p)),u})})}else{let a=this;return Ze(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Xe([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Xe([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:Zt.create(e).rest(er.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||Zt.create([]).rest(er.create()),returns:r||er.create(),typeName:S.ZodFunction,...B(n)})}},Yr=class extends J{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})}};Yr.create=(t,e)=>new Yr({getter:t,typeName:S.ZodLazy,...B(e)});var Qr=class extends J{_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}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Qr.create=(t,e)=>new Qr({value:t,typeName:S.ZodLiteral,...B(e)});function fm(t,e){return new en({values:t,typeName:S.ZodEnum,...B(e)})}var en=class t extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:Y.joinValues(n),received:r.parsedType,code:k.invalid_type}),L}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}),L}return Ze(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})}};en.create=fm;var tn=class extends J{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=Y.objectValues(r);return E(n,{expected:Y.joinValues(o),received:n.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),L}return Ze(e.data)}get enum(){return this._def.values}};tn.create=(t,e)=>new tn({values:t,typeName:S.ZodNativeEnum,...B(e)});var vr=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:P.promise,received:r.parsedType}),L;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Ze(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};vr.create=(t,e)=>new vr({type:t,typeName:S.ZodPromise,...B(e)});var ft=class extends J{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 L;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Fr(c.value):r.value==="dirty"?Fr(c.value):c});{if(r.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?Fr(a.value):r.value==="dirty"?Fr(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"?L:(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"?L:(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(!gr(i))return L;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=>gr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):L);Y.assertNever(o)}};ft.create=(t,e,r)=>new ft({schema:t,typeName:S.ZodEffects,effect:e,...B(r)});ft.createWithPreprocess=(t,e,r)=>new ft({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...B(r)});var Ye=class extends J{_parse(e){return this._getType(e)===P.undefined?Ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:S.ZodOptional,...B(e)});var Dt=class extends J{_parse(e){return this._getType(e)===P.null?Ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:S.ZodNullable,...B(e)});var rn=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rn.create=(t,e)=>new rn({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var nn=class extends J{_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 Cn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};nn.create=(t,e)=>new nn({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Zn=class extends J{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};Zn.create=t=>new Zn({typeName:S.ZodNaN,...B(t)});var Mw=Symbol("zod_brand"),zo=class extends J{_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}},Ro=class t extends J{_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"?L:s.status==="dirty"?(r.dirty(),Fr(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"?L: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})}},on=class extends J{_parse(e){let r=this._def.innerType._parse(e),n=o=>(gr(o)&&(o.value=Object.freeze(o.value)),o);return Cn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};on.create=(t,e)=>new on({innerType:t,typeName:S.ZodReadonly,...B(e)});function cm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function pm(t,e={},r){return t?_r.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=cm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=cm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):_r.create()}var jw={object:Qe.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 Zw=(t,e={message:`Input not instance of ${t.name}`})=>pm(r=>r instanceof t,e),mm=yr.create,hm=Hr.create,Dw=Zn.create,Lw=Br.create,gm=Vr.create,qw=Jr.create,Uw=On.create,Fw=Wr.create,Hw=Kr.create,Bw=_r.create,Vw=er.create,Jw=kt.create,Ww=Nn.create,Kw=tr.create,yc=Qe.create,Gw=Qe.strictCreate,Xw=Gr.create,Yw=Fs.create,Qw=Xr.create,e$=Zt.create,t$=Hs.create,r$=Mn.create,n$=jn.create,o$=Bs.create,s$=Yr.create,i$=Qr.create,a$=en.create,c$=tn.create,u$=vr.create,l$=ft.create,d$=Ye.create,f$=Dt.create,p$=ft.createWithPreprocess,m$=Ro.create,h$=()=>mm().optional(),g$=()=>hm().optional(),y$=()=>gm().optional(),_$={string:(t=>yr.create({...t,coerce:!0})),number:(t=>Hr.create({...t,coerce:!0})),boolean:(t=>Vr.create({...t,coerce:!0})),bigint:(t=>Br.create({...t,coerce:!0})),date:(t=>Jr.create({...t,coerce:!0}))};var v$=L;He();He();He();He();var zk=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");le.init(t,e),t.def=e,t.parse=(r,n)=>Cc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>cn(t,r,n),t.parseAsync=async(r,n)=>Oc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>un(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)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var Rk=w("ZodMiniObject",(t,e)=>{ni.init(t,e),zk.init(t,e),ee.defineLazy(t,"shape",()=>e.shape)});function xl(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new Rk(r)}He();si();function Ut(t){return!!t._zod}function fn(t){let e=Object.values(t);if(e.length===0)return xl({});let r=e.every(Ut),n=e.every(o=>!Ut(o));if(r)return xl(t);if(n)return yc(t);throw new Error("Mixed Zod versions detected in object shape.")}function wr(t,e){return Ut(t)?cn(t,e):t.safeParse(e)}async function pi(t,e){return Ut(t)?await un(t,e):await t.safeParseAsync(e)}function $r(t){if(!t)return;let e;if(Ut(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Fn(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 fn(t)}}if(Ut(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 Ik(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function mi(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 ${Ik(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 Zh(t){return t.description}function Dh(t){if(Ut(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Hn(t){if(Ut(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}Sr();function Tr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Pg=Symbol("Let zodToJsonSchema decide on which parser to use");var Rg={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"},Ig=t=>typeof t=="string"?{...Rg,name:t}:{...Rg,...t};var Cg=t=>{let e=Ig(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 Gl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function re(t,e,r,n,o){t[e]=r,Gl(t,e,n,o)}var Di=(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 ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Di(e,t.currentPath):e.join("/")}}function Ag(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=U(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&re(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&re(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(re(r,"minItems",t.exactLength.value,t.exactLength.message,e),re(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Og(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?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Ng(){return{type:"boolean"}}function Li(t,e){return U(t.type._def,e)}var Mg=(t,e)=>U(t.innerType._def,e);function Xl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Xl(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 nE(t,e)}}var nE=(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":re(r,"minimum",n.value,n.message,e);break;case"max":re(r,"maximum",n.value,n.message,e);break}return r};function jg(t,e){return{...U(t.innerType._def,e),default:t.defaultValue()}}function Zg(t,e){return e.effectStrategy==="input"?U(t.schema._def,e):ke(e)}function Dg(t){return{type:"string",enum:Array.from(t.values)}}var oE=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Lg(t,e){let r=[U(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),U(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(oE(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 qg(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 Yl,Tt={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:()=>(Yl===void 0&&(Yl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yl),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 qi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":re(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":Et(r,"email",n.message,e);break;case"format:idn-email":Et(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,Tt.email,n.message,e);break}break;case"url":Et(r,"uri",n.message,e);break;case"uuid":Et(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,Tt.cuid,n.message,e);break;case"cuid2":Ve(r,Tt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${Ql(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${Ql(n.value,e)}$`),n.message,e);break;case"datetime":Et(r,"date-time",n.message,e);break;case"date":Et(r,"date",n.message,e);break;case"time":Et(r,"time",n.message,e);break;case"duration":Et(r,"duration",n.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(Ql(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Et(r,"ipv4",n.message,e),n.version!=="v4"&&Et(r,"ipv6",n.message,e);break}case"base64url":Ve(r,Tt.base64url,n.message,e);break;case"jwt":Ve(r,Tt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,Tt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,Tt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,Tt.emoji(),n.message,e);break;case"ulid":{Ve(r,Tt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Et(r,"binary",n.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,Tt.base64,n.message,e);break}}break}case"nanoid":Ve(r,Tt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ql(t,e){return e.patternStrategy==="escape"?iE(t):t}var sE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iE(t){let e="";for(let r=0;r<t.length;r++)sE.has(t[r])||(e+="\\"),e+=t[r];return e}function Et(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}}})):re(t,"format",e,r,n)}function Ve(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:Ug(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):re(t,"pattern",Ug(e,n),r,n)}function Ug(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 Di(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]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(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}=Zi(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}=ji(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Zg(t,e){if(e.mapStrategy==="record")return Di(t,e);let r=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),n=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Dg(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 Lg(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function qg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ug(t,e){if(e.target==="openApi3")return Fg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xo[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 Fg(t,e)}var Fg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>F(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 Hg(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:Xo[t.innerType._def.typeName],nullable:!0}:{type:[Xo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Bg(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",Jl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Vg(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=XT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=F(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=GT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function GT(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(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 XT(t){try{return t.isOptional()}catch{return!0}}var Jg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:$e(e)},r]}:$e(e)};var Wg=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let r=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Kg(t,e){return F(t.type._def,e)}function Gg(t,e){let n={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Xg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Yg(t){return{not:$e(t)}}function Qg(t){return $e(t)}var ey=(t,e)=>F(t.innerType._def,e);var ty=(t,e,r)=>{switch(e){case S.ZodString:return Zi(t,r);case S.ZodNumber:return Bg(t,r);case S.ZodObject:return Vg(t,r);case S.ZodBigInt:return Rg(t,r);case S.ZodBoolean:return Pg();case S.ZodDate:return Wl(t,r);case S.ZodUndefined:return Yg(r);case S.ZodNull:return qg(r);case S.ZodArray:return zg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Ug(t,r);case S.ZodIntersection:return Ng(t,r);case S.ZodTuple:return Xg(t,r);case S.ZodRecord:return Di(t,r);case S.ZodLiteral:return Mg(t,r);case S.ZodEnum:return Og(t);case S.ZodNativeEnum:return Dg(t);case S.ZodNullable:return Hg(t,r);case S.ZodOptional:return Jg(t,r);case S.ZodMap:return Zg(t,r);case S.ZodSet:return Gg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Kg(t,r);case S.ZodNaN:case S.ZodNever:return Lg(r);case S.ZodEffects:return Ag(t,r);case S.ZodAny:return $e(r);case S.ZodUnknown:return Qg(r);case S.ZodDefault:return Cg(t,r);case S.ZodBranded:return ji(t,r);case S.ZodReadonly:return ey(t,r);case S.ZodCatch:return Ig(t,r);case S.ZodPipeline:return Wg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function F(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Sg)return a}if(n&&!r){let a=YT(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=ty(t,t.typeName,e),i=typeof s=="function"?F(s(),e):s;if(i&&QT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var YT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Mi(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`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},QT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Xl=(t,e)=>{let r=Eg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??$e(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=F(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??$e(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 eE(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Yl(t,e){return Dt(t)?gl(t,{target:eE(e?.target),io:e?.pipeStrategy??"input"}):Xl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ql(t){let r=xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ln(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ed(t,e){let r=vr(t,e);if(!r.success)throw r.error;return r.data}var tE=6e4,Li=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(_i,r=>{this._oncancel(r)}),this.setNotificationHandler(bi,r=>{this._onprogress(r)}),this.setRequestHandler(xi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ki,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new C(O.InvalidParams,`Task not found: ${s}`);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,m=new C(d.error.code,d.error.message,d.error.data);l(m)}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 C(O.InvalidParams,`Task not found: ${s}`);if(!$r(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if($r(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[br]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Si,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 C(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ei,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,`Task not found: ${r.params.taskId}`);if($r(o.status))throw new C(O.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new C(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(O.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),C.fromError(O.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),rr(s)||Un(s)?this._onresponse(s):tr(s)?this._onrequest(s,i):mg(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=C.fromError(O.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?.[br]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new C(O.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>o?.send(f)).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(f).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=dg(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(f,g)},sendRequest:async(f,g,h)=>{if(l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let v=_.relatedTask?.taskId??s;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(f,g,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let g={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async f=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:O.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&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),rr(e))n(e);else{let i=new C(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(rr(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),rr(e))o(e);else{let i=C.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 C?i:new C(O.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Hn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},$r(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new C(O.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(O.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 C?i:new C(O.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 m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[br]:c}});let f=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof C?v:new C(O.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=vr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??tE,h=()=>f(C.fromError(O.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(m);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(m),l(y)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},$i,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},Ti,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gg,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||{},[br]: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||{},[br]: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||{},[br]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ql(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ed(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=Ql(e);this._notificationHandlers.set(n,o=>{let s=ed(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??this._transport?.sessionId,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"&&tr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(O.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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new C(O.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new C(O.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 C(O.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=Jo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),$r(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 C(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if($r(a.status))throw new C(O.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=Jo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),$r(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function ry(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ny(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];ry(i)&&ry(s)?r[o]={...i,...s}:r[o]=s}return r}wr();var sv=lc(Vf(),1),iv=lc(ov(),1);function mC(){let t=new sv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,iv.default)(t),t}var Sa=class{constructor(e){this._ajv=e??mC()}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)}}};wr();var Ta=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(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))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},Go,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 av(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 cv(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 Ea=class extends Li{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ko.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 Sa,this.setRequestHandler(vi,n=>this._oninitialize(n)),this.setNotificationHandler(jl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Hl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ko.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ta(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ny(this._capabilities,e)}setRequestHandler(e,r){let o=xr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ln(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=vr(Vn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new C(O.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=vr(Hn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new C(O.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=vr(Oi,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new C(O.InvalidParams,`Invalid tools/call result: ${f}`)}return p.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){cv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&av(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:Fn.includes(r)?r:Cl,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"},yi)}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},Bl,r):this.request({method:"sampling/createMessage",params:e},Go,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 C(O.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof C?i:new C(O.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},Vl,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"})}};wr();var lv=Symbol.for("mcp.completable");function ep(t){return!!t&&typeof t=="object"&&lv in t}function dv(t){return t[lv]?.complete}var uv;(function(t){t.Completable="McpCompletable"})(uv||(uv={}));var za=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("*"),l=this.getNames(a),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:c,names:l,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 l=Array.isArray(u)?u.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).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:l}of c)r+=u,n.push({name:l,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],l=s[a+1],d=c.replace("*","");u&&l.includes(",")?i[d]=l.split(","):i[d]=l}return i}};var hC=/^[A-Za-z0-9._-]{1,128}$/;function gC(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"),!hC.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 yC(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 tp(t){let e=gC(t);return yC(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)}};function _C(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function vC(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var Pa=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 Ea(e,r),this._maxToolInputElements=vC(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}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(Cr(Ai)),this.server.assertCanSetRequestHandler(Cr(Vn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ai,()=>({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=Dn(r.inputSchema);return o?Yl(o,{strictUnions:!0,pipeStrategy:"input"}):xC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Dn(r.outputSchema);o&&(n.outputSchema=Yl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Vn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new C(O.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new C(O.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 C(O.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new C(O.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 C&&n.code===O.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(this._maxToolInputElements!==void 0&&_C(r,this._maxToolInputElements)>this._maxToolInputElements)throw new C(O.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Dn(e.inputSchema)??e.inputSchema,i=await li(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=di(a);throw new C(O.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 C(O.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Dn(e.outputSchema),s=await li(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=di(i);throw new C(O.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(m=>setTimeout(m,l));let d=await n.taskStore.getTask(c);if(!d)throw new C(O.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Cr(Ni)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ni,async e=>{switch(e.params.ref.type){case"ref/prompt":return wg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return $g(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(O.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new C(O.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return zs;let s=xr(n.argsSchema)?.[e.params.argument.name];if(!ep(s))return zs;let i=dv(s);if(!i)return zs;let a=await i(e.params.argument.value,e.params.context);return pv(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 zs;throw new C(O.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return zs;let s=await o(e.params.argument.value,e.params.context);return pv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Cr(zi)),this.server.assertCanSetRequestHandler(Cr(Ri)),this.server.assertCanSetRequestHandler(Cr(Pi)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zi,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(Ri,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Pi,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new C(O.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 C(O.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Cr(Ii)),this.server.assertCanSetRequestHandler(Cr(Ci)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ii,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?bC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ci,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new C(O.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Dn(n.argsSchema),s=await li(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=di(c);throw new C(O.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:ln(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=ln(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 Xe?c._def?.innerType:c;return ep(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){tp(e);let l={title:r,description:n,inputSchema:fv(o),outputSchema:fv(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"&&tp(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=ln(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=ln(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(rp(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!rp(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()}},Ia=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new za(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},xC={type:"object",properties:{}};function mv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function hv(t){return"_def"in t||"_zod"in t||mv(t)}function rp(t){return typeof t!="object"||t===null||hv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(mv)}function fv(t){if(t){if(rp(t))return ln(t);if(!hv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function bC(t){let e=xr(t);return e?Object.entries(e).map(([r,n])=>{let o=Ah(n),s=Oh(n);return{name:r,description:o,required:!s}}):[]}function Cr(t){let r=xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ln(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function pv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var zs={completion:{values:[],hasMore:!1}};import yv from"node:process";wr();var wC=10*1024*1024,Ca=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??wC}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),$C(r)}clear(){this._buffer=void 0}};function $C(t){return Fo.parse(JSON.parse(t))}function gv(t){return JSON.stringify(t)+`
58
- `}var Aa=class{constructor(e=yv.stdin,r=yv.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 Ca({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=gv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};wr();function Oa(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=Oa(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 sp(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=Oa(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,l=Array.isArray(u)?u.filter(d=>d&&typeof d=="object"):void 0;if(l&&l.length>0){s="tool_call",i=l[0]?.function?.name??l[0]?.name;let d=l.map(m=>`[tool call: ${m.function?.name??m.name}] ${m.function?.arguments??JSON.stringify(m.input??{})}`).join(`
59
- `);a+=d,c=(c??"")+d}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function np(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 kC(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 op(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 d of o){let m=kC(d);s+=(s&&m.text?`
60
- `:"")+m.text,i||=m.hasBinary,m.kind&&(a=m.kind),c??=m.toolName,m.call&&(u+=m.call)}let l=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??l,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function SC(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}:Oa(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 sp(r,e)}function _v(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return np("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return np(t,l)}if(e===null||typeof e!="object")return np(t);if(Array.isArray(e)){let l=e.length===0||e.some(d=>d&&typeof d=="object"&&("role"in d||"parts"in d));return e.length>0&&e.every(d=>d&&typeof d=="object"&&Array.isArray(d.parts))?{sourceFormat:"gemini",messages:e.map((d,m)=>op(d,m))}:{sourceFormat:"array",parseWarning:l?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((d,m)=>sp(d,m))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let l=[],d=r.systemInstruction??r.system_instruction;if(d!=null){let m=typeof d=="string"?{text:d,hasBinary:!1}:op(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>op(m,p))),{sourceFormat:"gemini",messages:l,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let l=[];typeof r.instructions=="string"&&r.instructions&&l.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let d=typeof r.input=="string"?[r.input]:r.input;return l.push(...d.map((m,p)=>SC(m,p))),{sourceFormat:"responses",messages:l,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let l=Oa(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>sp(l,d)));let c=r.system!=null||s.some(l=>Array.isArray(l?.content)&&l.content.some(d=>d?.type==="tool_use"||d?.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 oA}from"node:crypto";var vv=[[/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]],Tq=Math.max(...vv.map(([,t])=>t));function Na(t){if(t){for(let[e,r]of vv)if(e.test(t))return r}}function Ar(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function TC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Rs={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 xv(t){return TC(t)>.08}function ip(t,e){let r=Rs[Ar(e)];return xv(t)?r.code:r.prose}function It(t,e){return typeof t!="string"&&(t=String(t??"")),t?EC(t.length,xv(t),e):0}function EC(t,e,r){if(!(t>0))return 0;let n=Rs[Ar(r)];return Math.ceil(t/(e?n.code:n.prose))}var ap=4;function R(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${R(-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 T=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Me(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 Ma=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],bv=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Q(t){return new RegExp(`(?<![\\w.-])${bv(t)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`,"i")}function Bt(t){return new RegExp(`(?<![\\w.-])${bv(t)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`,"i")}var We=!0,zC=[[Me("fable|mythos",5,1),T(10,50,.25)],[Me("fable|mythos",5),T(10,50,1)],[Me("opus",5,5),T(4,20,.2)],[Me("opus",5),T(5,25,.5)],[Me("opus",4,8),T(5,25,.5)],[Me("opus",4,7),T(5,25,.5)],[Me("opus",4,6),T(5,25,.5)],[Me("opus",4,5),T(5,25,.5)],[Me("opus",4,1),T(15,75,1.5)],[Me("opus",4),T(15,75,1.5)],[Me("sonnet",5,5),T(2,10,.1)],[Me("sonnet",5),T(2,10,.2)],[Me("haiku",5,5),T(.1,.5,.01)],[Me("haiku",4,5),T(1,5,.1)],[Me("sonnet",4,6),T(3,15,.3)],[Me("sonnet",4,5),T(3,15,.3)],[Me("sonnet",4),T(3,15,.3)],[/claude-3-opus/i,T(15,75,1.5)],[/claude-3-5-haiku/i,T(.8,4,.08)],[/claude-3-haiku/i,T(.25,1.25,.03)],[/claude-3-[57]-sonnet/i,T(3,15,.3)],[Ma[0],T(10,50,1),We],[Ma[1],T(5,25,.5),We],[Ma[2],T(3,15,.3),We],[Ma[3],T(1,5,.1),We],[Q("gpt-6-astra"),T(10,50,1)],[Q("gpt-6-astra-law"),T(10,50,1)],[Q("gpt-6.1-sol"),T(2,10,.1)],[Q("gpt-6.1-terra"),T(1,5,.05)],[Q("gpt-6-sol"),T(2,10,.2)],[Q("gpt-6-luna"),T(.1,.5,.01)],[Q("gpt-6-cyber"),T(20,100,2)],[Q("gpt-6-rosalind"),T(15,75,1.5)],[Q("gpt-rosalind-research"),T(5,25,.5)],[Q("gpt-rosalind-discovery"),T(5,25,.5)],[Q("gpt-5.6-sol"),T(4,20,.4)],[Q("gpt-5.6"),T(4,20,.4)],[Q("gpt-5.6-terra"),T(2,12,.2)],[Q("gpt-5.6-luna"),T(.2,1.2,.02)],[Q("gpt-5.6-cyber"),T(12.5,75,1.25)],[Q("gpt-5.5"),T(5,30,.5)],[Q("gpt-5.5-pro"),T(30,180,30)],[Q("gpt-5.5-cyber"),T(12.5,75,1.25)],[Q("gpt-5.4"),T(2.5,15,.25)],[Q("gpt-5.4-mini"),T(.75,4.5,.075)],[Q("gpt-5.4-nano"),T(.2,1.25,.02)],[Q("gpt-5.4-pro"),T(30,180,30)],[Q("gpt-5.3-codex"),T(1.75,14,.175)],[Q("gpt-5.2"),T(1.75,14,.175)],[Q("gpt-5.2-pro"),T(21,168,21)],[Q("gpt-5.1"),T(1.25,10,.125)],[Q("gpt-5"),T(1.25,10,.125)],[Q("gpt-5-mini"),T(.25,2,.025)],[Q("gpt-5-nano"),T(.05,.4,.005)],[Q("gpt-5-pro"),T(15,120,15)],[Q("gpt-4.1"),T(2,8,.5)],[Q("gpt-4.1-mini"),T(.4,1.6,.1)],[Q("gpt-4o"),T(2.5,10,1.25)],[Q("gpt-4o-mini"),T(.15,.6,.075)],[Q("o3"),T(2,8,.5)],[Q("o3-pro"),T(20,80,20)],[Q("chat-latest"),T(5,30,.5)],[/gpt-5.*(mini|nano)/i,T(.25,2,.025),We],[/gpt-5/i,T(1.25,10,.125),We],[/gpt-4o-mini/i,T(.15,.6,.075),We],[/gpt-4o|gpt-4\.1/i,T(2.5,10,1.25),We],[/gpt-4-turbo/i,T(10,30,10),We],[/o[13](-|$)/i,T(2,8,1),We],[Bt("gemini-4-argon"),T(2,10,.1)],[Bt("gemini-3.8-flash"),T(.75,3.75,.075)],[Bt("gemini-3.6-flash"),T(.75,3.75,.075)],[Bt("gemini-3.5-flash-lite"),T(.3,2.5,.03)],[Bt("gemini-3.1-flash-lite"),T(.25,1.5,.025)],[Bt("gemini-3.1-pro"),T(2,12,.2)],[Bt("gemini-3-flash"),T(.5,3,.05)],[Bt("gemini-2.5-pro"),T(1.25,10,.125)],[Bt("gemini-2.5-flash"),T(.3,2.5,.03)],[Bt("gemini-2.5-flash-lite"),T(.1,.4,.01)],[/gemini-3[.\d]*-flash-lite/i,T(.3,2.5,.03),We],[/gemini-3[.\d]*-flash/i,T(.75,3.75,.075),We],[/gemini-3[.\d]*-pro/i,T(2,12,.2),We],[/gemini.*flash/i,T(.1,.4,.025),We],[/gemini.*pro/i,T(1.25,5,.31),We]];function RC(t){if(t)return zC.find(([e])=>e.test(t))}function fo(t){return RC(t)?.[1]}function Or(t,e){return t/1e6*e.inputPerM}function cp(t){return t/25e3}function Vt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var wv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,PC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function $v(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 po(t){for(let e of t.matchAll(wv))if($v(e[0]))return!0;return!1}function up(t){return t.replace(wv,e=>$v(e)?PC:e)}import{mkdirSync as Dq,readFileSync as KC,writeFileSync as Lq}from"node:fs";import{dirname as GC,join as XC}from"node:path";import{appendFileSync as OC,existsSync as lp,mkdirSync as NC,readFileSync as MC,statSync as jC,writeFileSync as ZC}from"node:fs";import{homedir as Sv}from"node:os";import{dirname as Ev,join as mo}from"node:path";import{homedir as kv}from"node:os";import{join as IC,resolve as CC}from"node:path";function AC(t,e){if(t!==void 0&&t!==kv())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?CC(r):void 0}function Nr(t,e=process.env){return AC(t,e)??IC(t??kv(),".claude")}var DC={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function LC(t){let e={...DC},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 qC(){let t=process.env.XDG_STATE_HOME?.trim();return t?mo(t,"context-doctor"):process.platform==="win32"?mo(process.env.LOCALAPPDATA?.trim()||mo(Sv(),"AppData","Local"),"context-doctor"):mo(Sv(),".local","state","context-doctor")}function FC(){let t=qC();if(lp(t))return t;let e=Nr();return lp(e)?e:t}function dp(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??mo(FC(),".context-doctor-hook-state.json")}function UC(){return mo(Ev(dp()),".context-doctor-ledger.jsonl")}var Tv=100,HC=256*1024,BC=128*1024,VC=500,JC=4*1024;function WC(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>Tv?e.slice(0,Tv):e}function ja(t){let e=UC();try{if(NC(Ev(e),{recursive:!0}),lp(e)&&jC(e).size>HC){let n=MC(e,"utf8").trimEnd().split(`
62
- `),o=d=>{try{return[JSON.parse(d)]}catch{return[]}},s=new Set,i=0;for(let d=n.length-1;d>=0&&s.size<VC;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>JC)){if(i+m>BC)break;s.add(d),i+=m}}let a=n.filter((d,m)=>s.has(m)),c=n.filter((d,m)=>!s.has(m)).flatMap(o),u=LC(c),l={ts:Date.now(),ev:"rollup",carried:u};ZC(e,[JSON.stringify(l),...a].join(`
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 Ui(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]:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:U(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}=qi(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}=Li(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Fg(t,e){if(e.mapStrategy==="record")return Ui(t,e);let r=U(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Hg(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 Bg(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function Vg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var es={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wg(t,e){if(e.target==="openApi3")return Jg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in es&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=es[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 Jg(t,e)}var Jg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>U(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 Kg(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:es[t.innerType._def.typeName],nullable:!0}:{type:[es[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=U(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Gg(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",Gl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Xg(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=cE(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=U(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=aE(t,e);return i!==void 0&&(n.additionalProperties=i),n}function aE(t,e){if(t.catchall._def.typeName!=="ZodNever")return U(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 cE(t){try{return t.isOptional()}catch{return!0}}var Yg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return U(t.innerType._def,e);let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)};var Qg=(t,e)=>{if(e.pipeStrategy==="input")return U(t.in._def,e);if(e.pipeStrategy==="output")return U(t.out._def,e);let r=U(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=U(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function ey(t,e){return U(t.type._def,e)}function ty(t,e){let n={type:"array",uniqueItems:!0,items:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function ry(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:U(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ny(t){return{not:ke(t)}}function oy(t){return ke(t)}var sy=(t,e)=>U(t.innerType._def,e);var iy=(t,e,r)=>{switch(e){case S.ZodString:return qi(t,r);case S.ZodNumber:return Gg(t,r);case S.ZodObject:return Xg(t,r);case S.ZodBigInt:return Og(t,r);case S.ZodBoolean:return Ng();case S.ZodDate:return Xl(t,r);case S.ZodUndefined:return ny(r);case S.ZodNull:return Vg(r);case S.ZodArray:return Ag(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Wg(t,r);case S.ZodIntersection:return Lg(t,r);case S.ZodTuple:return ry(t,r);case S.ZodRecord:return Ui(t,r);case S.ZodLiteral:return qg(t,r);case S.ZodEnum:return Dg(t);case S.ZodNativeEnum:return Hg(t);case S.ZodNullable:return Kg(t,r);case S.ZodOptional:return Yg(t,r);case S.ZodMap:return Fg(t,r);case S.ZodSet:return ty(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return ey(t,r);case S.ZodNaN:case S.ZodNever:return Bg(r);case S.ZodEffects:return Zg(t,r);case S.ZodAny:return ke(r);case S.ZodUnknown:return oy(r);case S.ZodDefault:return jg(t,r);case S.ZodBranded:return Li(t,r);case S.ZodReadonly:return sy(t,r);case S.ZodCatch:return Mg(t,r);case S.ZodPipeline:return Qg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function U(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Pg)return a}if(n&&!r){let a=uE(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=iy(t,t.typeName,e),i=typeof s=="function"?U(s(),e):s;if(i&&lE(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var uE=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Di(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`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},lE=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ed=(t,e)=>{let r=Cg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:U(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=U(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(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 dE(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function td(t,e){return Ut(t)?vl(t,{target:dE(e?.target),io:e?.pipeStrategy??"input"}):ed(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function rd(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function nd(t,e){let r=wr(t,e);if(!r.success)throw r.error;return r.data}var fE=6e4,Fi=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(bi,r=>{this._oncancel(r)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler($i,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Si,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.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(!await this._taskStore.getTask(s,n.sessionId))throw new C(O.InvalidParams,`Task not found: ${s}`);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,m=new C(d.error.code,d.error.message,d.error.data);l(m)}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 C(O.InvalidParams,`Task not found: ${s}`);if(!Tr(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(Tr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[kr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(zi,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 C(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Pi,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tr(o.status))throw new C(O.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new C(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(O.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),C.fromError(O.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),or(s)||Jn(s)?this._onresponse(s):nr(s)?this._onrequest(s,i):vg(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=C.fromError(O.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?.[kr]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new C(O.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>o?.send(f)).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(f).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=gg(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(f,g)},sendRequest:async(f,g,h)=>{if(l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let v=_.relatedTask?.taskId??s;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(f,g,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let g={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async f=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:O.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&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),or(e))n(e);else{let i=new C(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(or(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),or(e))o(e);else{let i=C.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 C?i:new C(O.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Wn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Tr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new C(O.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(O.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 C?i:new C(O.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 m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[kr]:c}});let f=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof C?v:new C(O.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=wr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??fE,h=()=>f(C.fromError(O.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(m);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(m),l(y)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ti,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},bg,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||{},[kr]: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||{},[kr]: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||{},[kr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=rd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=nd(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=rd(e);this._notificationHandlers.set(n,o=>{let s=nd(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??this._transport?.sessionId,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"&&nr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(O.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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new C(O.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new C(O.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 C(O.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=Go.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Tr(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 C(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Tr(a.status))throw new C(O.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=Go.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function ay(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cy(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];ay(i)&&ay(s)?r[o]={...i,...s}:r[o]=s}return r}Sr();var lv=pc(Kf(),1),dv=pc(uv(),1);function SC(){let t=new lv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dv.default)(t),t}var za=class{constructor(e){this._ajv=e??SC()}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)}}};Sr();var Ra=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(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))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},Qo,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},Xn,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 fv(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 pv(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 Pa=class extends Fi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Yo.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 za,this.setRequestHandler(wi,n=>this._oninitialize(n)),this.setNotificationHandler(Ll,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Jl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Yo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ra(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=cy(this._capabilities,e)}setRequestHandler(e,r){let o=$r(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Hn(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=wr(Gn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new C(O.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=wr(Wn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new C(O.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=wr(ji,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new C(O.InvalidParams,`Invalid tools/call result: ${f}`)}return p.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){pv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&fv(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:Vn.includes(r)?r:Nl,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"},xi)}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},Wl,r):this.request({method:"sampling/createMessage",params:e},Qo,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},Xn,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},Xn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new C(O.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof C?i:new C(O.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},Kl,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"})}};Sr();var hv=Symbol.for("mcp.completable");function np(t){return!!t&&typeof t=="object"&&hv in t}function gv(t){return t[hv]?.complete}var mv;(function(t){t.Completable="McpCompletable"})(mv||(mv={}));var Ia=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("*"),l=this.getNames(a),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:c,names:l,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 l=Array.isArray(u)?u.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).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:l}of c)r+=u,n.push({name:l,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],l=s[a+1],d=c.replace("*","");u&&l.includes(",")?i[d]=l.split(","):i[d]=l}return i}};var TC=/^[A-Za-z0-9._-]{1,128}$/;function EC(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"),!TC.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 zC(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 op(t){let e=EC(t);return zC(t,e.warnings),e.isValid}var Ca=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)}};function RC(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function PC(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var Aa=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 Pa(e,r),this._maxToolInputElements=PC(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new Ca(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Mi)),this.server.assertCanSetRequestHandler(Nr(Gn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mi,()=>({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=Fn(r.inputSchema);return o?td(o,{strictUnions:!0,pipeStrategy:"input"}):IC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Fn(r.outputSchema);o&&(n.outputSchema=td(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new C(O.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new C(O.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 C(O.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new C(O.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 C&&n.code===O.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(this._maxToolInputElements!==void 0&&RC(r,this._maxToolInputElements)>this._maxToolInputElements)throw new C(O.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Fn(e.inputSchema)??e.inputSchema,i=await pi(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=mi(a);throw new C(O.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 C(O.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Fn(e.outputSchema),s=await pi(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=mi(i);throw new C(O.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(m=>setTimeout(m,l));let d=await n.taskStore.getTask(c);if(!d)throw new C(O.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Nr(Zi)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zi,async e=>{switch(e.params.ref.type){case"ref/prompt":return Eg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return zg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(O.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new C(O.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Is;let s=$r(n.argsSchema)?.[e.params.argument.name];if(!np(s))return Is;let i=gv(s);if(!i)return Is;let a=await i(e.params.argument.value,e.params.context);return _v(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 C(O.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 _v(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Ii)),this.server.assertCanSetRequestHandler(Nr(Ci)),this.server.assertCanSetRequestHandler(Nr(Ai)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ii,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(Ci,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ai,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new C(O.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 C(O.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Oi)),this.server.assertCanSetRequestHandler(Nr(Ni)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oi,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?CC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ni,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new C(O.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Fn(n.argsSchema),s=await pi(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=mi(c);throw new C(O.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:fn(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=fn(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 Ye?c._def?.innerType:c;return np(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){op(e);let l={title:r,description:n,inputSchema:yv(o),outputSchema:yv(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"&&op(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=fn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=fn(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(sp(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!sp(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()}},Oa=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Ia(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},IC={type:"object",properties:{}};function vv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function xv(t){return"_def"in t||"_zod"in t||vv(t)}function sp(t){return typeof t!="object"||t===null||xv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vv)}function yv(t){if(t){if(sp(t))return fn(t);if(!xv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function CC(t){let e=$r(t);return e?Object.entries(e).map(([r,n])=>{let o=Zh(n),s=Dh(n);return{name:r,description:o,required:!s}}):[]}function Nr(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function _v(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Is={completion:{values:[],hasMore:!1}};import wv from"node:process";Sr();var AC=10*1024*1024,Na=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??AC}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),OC(r)}clear(){this._buffer=void 0}};function OC(t){return Bo.parse(JSON.parse(t))}function bv(t){return JSON.stringify(t)+`
58
+ `}var Ma=class{constructor(e=wv.stdin,r=wv.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 Na({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=bv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};Sr();function ja(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=ja(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 cp(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ja(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,l=Array.isArray(u)?u.filter(d=>d&&typeof d=="object"):void 0;if(l&&l.length>0){s="tool_call",i=l[0]?.function?.name??l[0]?.name;let d=l.map(m=>`[tool call: ${m.function?.name??m.name}] ${m.function?.arguments??JSON.stringify(m.input??{})}`).join(`
59
+ `);a+=d,c=(c??"")+d}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function ip(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 NC(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 ap(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 d of o){let m=NC(d);s+=(s&&m.text?`
60
+ `:"")+m.text,i||=m.hasBinary,m.kind&&(a=m.kind),c??=m.toolName,m.call&&(u+=m.call)}let l=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??l,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function MC(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}:ja(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 cp(r,e)}function $v(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return ip("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return ip(t,l)}if(e===null||typeof e!="object")return ip(t);if(Array.isArray(e)){let l=e.length===0||e.some(d=>d&&typeof d=="object"&&("role"in d||"parts"in d));return e.length>0&&e.every(d=>d&&typeof d=="object"&&Array.isArray(d.parts))?{sourceFormat:"gemini",messages:e.map((d,m)=>ap(d,m))}:{sourceFormat:"array",parseWarning:l?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((d,m)=>cp(d,m))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let l=[],d=r.systemInstruction??r.system_instruction;if(d!=null){let m=typeof d=="string"?{text:d,hasBinary:!1}:ap(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>ap(m,p))),{sourceFormat:"gemini",messages:l,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let l=[];typeof r.instructions=="string"&&r.instructions&&l.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let d=typeof r.input=="string"?[r.input]:r.input;return l.push(...d.map((m,p)=>MC(m,p))),{sourceFormat:"responses",messages:l,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let l=ja(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>cp(l,d)));let c=r.system!=null||s.some(l=>Array.isArray(l?.content)&&l.content.some(d=>d?.type==="tool_use"||d?.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 pA}from"node:crypto";var kv=[[/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]],Mq=Math.max(...kv.map(([,t])=>t));function Za(t){if(t){for(let[e,r]of kv)if(e.test(t))return r}}function Mr(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function jC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Cs={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 Sv(t){return jC(t)>.08}function up(t,e){let r=Cs[Mr(e)];return Sv(t)?r.code:r.prose}function At(t,e){return typeof t!="string"&&(t=String(t??"")),t?ZC(t.length,Sv(t),e):0}function ZC(t,e,r){if(!(t>0))return 0;let n=Cs[Mr(r)];return Math.ceil(t/(e?n.code:n.prose))}var lp=4;function R(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${R(-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 T=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function je(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 Da=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],Tv=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Q(t){return new RegExp(`(?<![\\w.-])${Tv(t)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`,"i")}function Wt(t){return new RegExp(`(?<![\\w.-])${Tv(t)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`,"i")}var Ke={fallback:!0},Ot={geo:!0},dp=t=>({over:272e3,rates:T(t.inputPerM*2,t.outputPerM*1.5,t.cacheReadPerM*2)}),vt=(t,e,r)=>{let n=T(t,e,r);return[n,{long:dp(n)}]},DC=[[je("fable|mythos",5,1),T(10,50,.25),Ot],[je("fable|mythos",5),T(10,50,1),Ot],[je("opus",5,5),T(4,20,.2),{geo:!0,fast:T(8,40,.4)}],[je("opus",5),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[je("opus",4,8),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[je("opus",4,7),T(5,25,.5),Ot],[je("opus",4,6),T(5,25,.5),Ot],[je("opus",4,5),T(5,25,.5)],[je("opus",4,1),T(15,75,1.5)],[je("opus",4),T(15,75,1.5)],[je("sonnet",5,5),T(2,10,.1),Ot],[je("sonnet",5),T(2,10,.2),Ot],[je("haiku",5,5),T(.1,.5,.01),{geo:!0,long:{over:1e5,rates:T(.5,2.5,.05)}}],[je("haiku",4,5),T(1,5,.1)],[je("sonnet",4,6),T(3,15,.3),Ot],[je("sonnet",4,5),T(3,15,.3)],[je("sonnet",4),T(3,15,.3)],[/claude-3-opus/i,T(15,75,1.5)],[/claude-3-5-haiku/i,T(.8,4,.08)],[/claude-3-haiku/i,T(.25,1.25,.03)],[/claude-3-[57]-sonnet/i,T(3,15,.3)],[Da[0],T(10,50,1),{...Ke,...Ot}],[Da[1],T(5,25,.5),{...Ke,...Ot}],[Da[2],T(3,15,.3),{...Ke,...Ot}],[Da[3],T(1,5,.1),{...Ke,...Ot}],[Q("gpt-6-astra"),...vt(10,50,1)],[Q("gpt-6-astra-law"),T(10,50,1)],[Q("gpt-6.1-sol"),...vt(2,10,.1)],[Q("gpt-6.1-terra"),...vt(1,5,.05)],[Q("gpt-6-sol"),...vt(2,10,.2)],[Q("gpt-6-luna"),...vt(.1,.5,.01)],[Q("gpt-6-cyber"),T(20,100,2)],[Q("gpt-6-rosalind"),...vt(15,75,1.5)],[Q("gpt-rosalind-research"),T(5,25,.5)],[Q("gpt-rosalind-discovery"),T(5,25,.5)],[Q("gpt-5.6-sol"),T(4,20,.4),{long:dp(T(4,20,.4)),changes:"2026-12-01"}],[Q("gpt-5.6"),T(4,20,.4),{long:dp(T(4,20,.4)),changes:"2026-12-01"}],[Q("gpt-5.6-terra"),...vt(2,12,.2)],[Q("gpt-5.6-luna"),...vt(.2,1.2,.02)],[Q("gpt-5.6-cyber"),T(12.5,75,1.25)],[Q("gpt-5.5"),...vt(5,30,.5)],[Q("gpt-5.5-pro"),...vt(30,180,30)],[Q("gpt-5.5-cyber"),T(12.5,75,1.25)],[Q("gpt-5.4"),...vt(2.5,15,.25)],[Q("gpt-5.4-mini"),T(.75,4.5,.075)],[Q("gpt-5.4-nano"),T(.2,1.25,.02)],[Q("gpt-5.4-pro"),...vt(30,180,30)],[Q("gpt-5.3-codex"),T(1.75,14,.175)],[Q("gpt-5.2"),T(1.75,14,.175)],[Q("gpt-5.2-pro"),T(21,168,21)],[Q("gpt-5.1"),T(1.25,10,.125)],[Q("gpt-5"),T(1.25,10,.125)],[Q("gpt-5-mini"),T(.25,2,.025)],[Q("gpt-5-nano"),T(.05,.4,.005)],[Q("gpt-5-pro"),T(15,120,15)],[Q("gpt-4.1"),T(2,8,.5)],[Q("gpt-4.1-mini"),T(.4,1.6,.1)],[Q("gpt-4o"),T(2.5,10,1.25)],[Q("gpt-4o-mini"),T(.15,.6,.075)],[Q("o3"),T(2,8,.5)],[Q("o3-pro"),T(20,80,20)],[Q("chat-latest"),T(5,30,.5)],[/gpt-5.*(mini|nano)/i,T(.25,2,.025),Ke],[/gpt-5/i,T(1.25,10,.125),Ke],[/gpt-4o-mini/i,T(.15,.6,.075),Ke],[/gpt-4o|gpt-4\.1/i,T(2.5,10,1.25),Ke],[/gpt-4-turbo/i,T(10,30,10),Ke],[/o[13](-|$)/i,T(2,8,1),Ke],[Wt("gemini-4-argon"),T(2,10,.1),{changes:"2026-12-01",then:T(4,20,.2)}],[Wt("gemini-3.8-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Wt("gemini-3.6-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Wt("gemini-3.5-flash-lite"),T(.3,2.5,.03)],[Wt("gemini-3.1-flash-lite"),T(.25,1.5,.025)],[Wt("gemini-3.1-pro"),T(2,12,.2),{long:{over:2e5,rates:T(4,18,.4)}}],[Wt("gemini-3-flash"),T(.5,3,.05)],[Wt("gemini-2.5-pro"),T(1.25,10,.125),{long:{over:2e5,rates:T(2.5,15,.25)},changes:"2026-12-01",then:T(.75,3.75,.075)}],[Wt("gemini-2.5-flash"),T(.3,2.5,.03)],[Wt("gemini-2.5-flash-lite"),T(.1,.4,.01)],[/gemini-3[.\d]*-flash-lite/i,T(.3,2.5,.03),Ke],[/gemini-3[.\d]*-flash/i,T(.75,3.75,.075),Ke],[/gemini-3[.\d]*-pro/i,T(2,12,.2),Ke],[/gemini.*flash/i,T(.1,.4,.025),Ke],[/gemini.*pro/i,T(1.25,5,.31),Ke]];function LC(t){if(t)return DC.find(([e])=>e.test(t))}function go(t){return LC(t)?.[1]}function jr(t,e){return t/1e6*e.inputPerM}var Zq=10/1e3;var Dq=Object.freeze({fastUsd:0,geoUsd:0,longUsd:0,webSearchUsd:0,webSearches:0});function fp(t){return t/25e3}function Kt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var Ev=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,qC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function zv(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 yo(t){for(let e of t.matchAll(Ev))if(zv(e[0]))return!0;return!1}function pp(t){return t.replace(Ev,e=>zv(e)?qC:e)}import{mkdirSync as Xq,readFileSync as oA,writeFileSync as Yq}from"node:fs";import{dirname as sA,join as iA}from"node:path";import{appendFileSync as FC,existsSync as hp,mkdirSync as HC,readFileSync as BC,statSync as VC,writeFileSync as JC}from"node:fs";import{homedir as Cv}from"node:os";import{dirname as Ov,join as _o}from"node:path";import{homedir as mp}from"node:os";import{join as Rv,resolve as UC}from"node:path";function Pv(t,e){if(t!==void 0&&t!==mp())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?UC(r):void 0}function ur(t,e=process.env){return Pv(t,e)??Rv(t??mp(),".claude")}function Iv(t,e=process.env){return Rv(Pv(t,e)??t??mp(),".claude.json")}var WC={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function KC(t){let e={...WC},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 GC(){let t=process.env.XDG_STATE_HOME?.trim();return t?_o(t,"context-doctor"):process.platform==="win32"?_o(process.env.LOCALAPPDATA?.trim()||_o(Cv(),"AppData","Local"),"context-doctor"):_o(Cv(),".local","state","context-doctor")}function XC(){let t=GC();if(hp(t))return t;let e=ur();return hp(e)?e:t}function gp(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??_o(XC(),".context-doctor-hook-state.json")}function YC(){return _o(Ov(gp()),".context-doctor-ledger.jsonl")}var Av=100,QC=256*1024,eA=128*1024,tA=500,rA=4*1024;function nA(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>Av?e.slice(0,Av):e}function La(t){let e=YC();try{if(HC(Ov(e),{recursive:!0}),hp(e)&&VC(e).size>QC){let n=BC(e,"utf8").trimEnd().split(`
62
+ `),o=d=>{try{return[JSON.parse(d)]}catch{return[]}},s=new Set,i=0;for(let d=n.length-1;d>=0&&s.size<tA;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>rA)){if(i+m>eA)break;s.add(d),i+=m}}let a=n.filter((d,m)=>s.has(m)),c=n.filter((d,m)=>!s.has(m)).flatMap(o),u=KC(c),l={ts:Date.now(),ev:"rollup",carried:u};JC(e,[JSON.stringify(l),...a].join(`
63
63
  `)+`
64
- `)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=WC(r[n]);o===void 0?delete r[n]:r[n]=o}OC(e,JSON.stringify({ts:Date.now(),...r})+`
65
- `)}catch{}}var YC=2,QC=.5,eA=2;function tA(){return XC(GC(dp()),".context-doctor-calibration.json")}function rA(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 nA(){try{return JSON.parse(KC(tA(),"utf8"))}catch{return{}}}function zv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=nA()[rA(t)];if(!e||e.v!==YC||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<QC||r>eA?{factor:1,samples:0}:{factor:r,samples:e.samples}}function sA(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 iA(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 aA(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function Rv(t){return oA("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function cA(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 uA(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=cA(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var Pv=.6;function lA(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 Iv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function dA(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function fA(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;Iv.lastIndex=0;for(let n of e.matchAll(Iv)){let o=n[2].replace(/\\+$/,"");dA(o)&&r.add(o)}return[...r]}function Cv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=zv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(It(y.text,r)*n.factor)+ap})),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[sA(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 ~${R(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 ~${R(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=Rv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-ap,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${R(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(H=>H.msg.text.length>=300).sort((H,ve)=>ve.tokens-H.tokens).slice(0,150),x=y.map(H=>uA(H.msg.text)),$=x.map(H=>H.size),N=new Set(a.filter(H=>H.id==="duplicate_content").flatMap(H=>H.messages)),A=y.map((H,ve)=>ve),ce=H=>{for(;A[H]!==H;)H=A[H]=A[A[H]];return H},ue=y.map(()=>({sim:0,partnerTokens:0}));for(let H=0;H<y.length;H++)for(let ve=H+1;ve<y.length;ve++){let At=y[H],Dr=y[ve];if(N.has(At.msg.index)&&N.has(Dr.msg.index))continue;let js=Math.min($[H],$[ve]),Tn=Math.max($[H],$[ve]);if(Tn===0||js/Tn<Pv)continue;let xt=lA(x[H],x[ve]);xt<Pv||(A[ce(H)]=ce(ve),xt>ue[H].sim&&(ue[H]={sim:xt,partnerTokens:Dr.tokens}),xt>ue[ve].sim&&(ue[ve]={sim:xt,partnerTokens:At.tokens}))}let ze=new Map;y.forEach((H,ve)=>{if(ue[ve].sim===0)return;let At=ce(ve);ze.set(At,[...ze.get(At)??[],ve])});for(let H of ze.values()){if(H.length<2)continue;H.sort((bt,Lr)=>y[bt].msg.index-y[Lr].msg.index);let ve=H.slice(1),At=ve.reduce((bt,Lr)=>bt+Math.round(Math.min(y[Lr].tokens,ue[Lr].partnerTokens)*ue[Lr].sim*.9),0),Dr=H.map(bt=>ue[bt].sim),js=Math.round(Math.min(...Dr)*100),Tn=Math.round(Math.max(...Dr)*100),xt=H.map(bt=>y[bt].msg.index),em=js===Tn?`~${Tn}%`:`${js}-${Tn}%`,Jb=ve.reduce((bt,Lr)=>bt+y[Lr].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:At,message:H.length===2?`Messages #${xt[0]} and #${xt[1]} are ${em} similar (~${R(Math.min(y[H[0]].tokens,y[H[1]].tokens))} tokens repeated with different framing).`:`${H.length} messages are ${em} similar to each other (${xt.slice(0,6).map(bt=>`#${bt}`).join(", ")}${xt.length>6?", \u2026":""}): ~${R(Jb)} tokens in the ${ve.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:xt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=Rv(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let l=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((N,A)=>l(y[A])?.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 fA(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let N=o.filter(ce=>ce.msg.kind==="tool_result"&&$.some(ue=>ce.msg.index===ue+1)).reduce((ce,ue)=>ce+ue.tokens,0),A=Math.round(N*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:A>4e3?"high":"warn",estSavings:A,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 ~${R(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)po(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 (~${R(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 d=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,N)=>$+N.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${R(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 ~${R(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:[]}),(Ar(e)==="anthropic"||Ar(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 m=Na(e),p=m?s/m*100:void 0;p!==void 0&&p>70&&a.push({id:"near_window_limit",severity:p>90?"high":"warn",estSavings:0,message:`Context is at ~${p.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:aA(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),g={high:0,warn:1,info:2};a.sort((y,x)=>g[y.severity]-g[x.severity]||x.estSavings-y.estSavings);let h=iA(a,s),_=fo(e),v;if(_){let y=Or(s,_),x=Or(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:cp(s),ttftSavedSeconds:cp(h)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:h,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as pA}from"node:crypto";var Nv=10,Za={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:Nv};function mA(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 hA(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 Av(t,e,r){let n=Math.round(e*ip("",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 fp(t,e,r=Nv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function gA(t){return pA("sha1").update(t.trim()).digest("hex")}function ho(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"?ho(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
- `):JSON.stringify(t)}function pp(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(d=>d?.type==="text"&&typeof d.text=="string");if(a.length===0)return s;let c=a.map(d=>d.text).join(`
68
- `),u=e(c,i);if(u===c)return s;let l=!1;return s.map(d=>d?.type==="text"&&typeof d.text=="string"?l?null:(l=!0,{...d,text:u}):d).filter(d=>d!==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 mp(t){return typeof t=="string"?po(t)?up(t):t:Array.isArray(t)?t.map(mp):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,mp(r)])):t}function yA(t,e,r){let n=Math.round(e*ip(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 _A(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 Ov(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function Mv(t,e={}){let r={strategies:e.strategies??Za.strategies,keepRecent:e.keepRecent??Za.keepRecent,maxToolResultTokens:e.maxToolResultTokens??Za.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):Za.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 h=o.length-1;h>=0;h--)(!o[h]||typeof o[h]!="object")&&o.splice(h,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(h=>Array.isArray(h?.content)&&h.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=h=>It(h,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:ho(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=h=>{let _=a(ho(h.content));for(let v of Array.isArray(h.tool_calls)?h.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return h.function_call&&(_+=a(`${h.function_call.name??""} ${h.function_call.arguments??""}`)),_},l=c+o.reduce((h,_)=>h+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((h,_)=>{let v=ho(h.content);if(!po(v))return;let y=a(v),x=pp(h,N=>po(N)?up(N):N);Array.isArray(x)&&(x=x.map(N=>N?.type==="tool_use"&&N.input!=null?{...N,input:mp(N.input)}:N));let $=y-a(ho(x));$>50&&(h.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let h=fp(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,N=pp(v,A=>{if(A.length<300)return A;let ce=gA(A),ue=_.get(ce);if(ue===void 0)return _.set(ce,y),A;if(y>=h)return A;let ze=`[context-doctor: identical to message #${ue} \u2014 content removed]`;return x+=a(A)-a(ze),$??=ue,ze});x<=0||(v.content=N,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let h=fp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h||!Ov(_))return;let y=0,x=pp(_,($,N)=>{if(N!=="tool_result")return $;let A=a($);if(A<=r.maxToolResultTokens)return $;let ce=yA($,r.maxToolResultTokens,i),ue=a(ce);return ue>=A?$:(y+=A-ue,ce)});y<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:y,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let h=fp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h)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"||hA(o,v,mA(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let N=Av(x.input,r.maxToolResultTokens,i),A=a(JSON.stringify(N));A>=$||(x.input=N,y+=$-A)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let N=a($);if(N<=r.maxToolResultTokens)continue;let A;try{A=JSON.parse($)}catch{continue}if(!A||typeof A!="object"||Array.isArray(A))continue;let ce=JSON.stringify(Av(A,r.maxToolResultTokens,i)),ue=a(ce);ue>=N||(x.function.arguments=ce,y+=N-ue)}y>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:y,note:"Arguments of a completed tool call truncated"})})}let m,p=0;for(;p<o.length&&(o[p]?.role==="system"||o[p]?.role==="developer");)p++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-p>f*2){let h=o.length-f;for(;h<o.length&&Ov(o[h]);)h++;if(o.length-h>=2){_A(o.slice(h));let _=o.slice(p,h),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${ho(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(p,h-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let g=c+o.reduce((h,_)=>h+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:g,applied:d,prunedDigest:m}}var jv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},vA={high:"\u2716",warn:"\u25B2",info:"\u2139"};function xA(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function bA(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 Zv(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: ~${R(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 ${R(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Vt(n.cost.perCallUsd)} input per call \xB7 ~${Vt(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])=>jv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${jv[i].padEnd(s)} ${xA(c)} ${String(Math.round(c*100)).padStart(3)}% ~${R(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}] ~${R(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 l=a.get(u.id)??0;if(l>=i){let p=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:p.count+1,savings:p.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${R(u.estSavings)}]`:"";r.push(`${vA[u.severity]} ${e.redact?bA(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let m=c.get(u.id);l+1===i&&m===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,l]of c){if(l.count===0)continue;let d=Math.min(l.savings,n.totalEstSavings),m=d>0?`, up to ~${R(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${m}. 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,l=`Potential recovery: ~${R(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Vt(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(l),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 wA=2060,$A={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},kA=6.3,SA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},TA=1500,Dv=2e3,EA=30,hp=400,zA=1e4,RA=6;function PA(t,e){let r=Rs[Ar(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function IA(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):TA;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*$A[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*kA:SA[t.kind];return Math.round(r/PA(t.kind,e))}function gp(t){return Math.round(wA/Rs[Ar(t)].prose)}var Lv=60;function CA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Lv?e.slice(0,Lv-1)+"\u2026":e}function AA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:CA(_?.label)})),n=gp(t.model),o=e*n,s=r.map(_=>({block:_,tokens:IA(_,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 (~${R(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 (~${R(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>=Dv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Dv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${R(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 (~${R(_)}) 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>=EA){let _=RA*n+hp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${R(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${hp}-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 ~${R(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Na(t.model),d=l?Math.round(a/l*100):void 0;d!==void 0&&d>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${d}% of the ${R(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let m={high:0,warn:1,info:2};c.sort((_,v)=>m[_.severity]-m[v.severity]||v.estSavings-_.estSavings);let p=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),g=Math.min(a,Math.max(p,f)),h=fo(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:g,perTurnUsd:h?Or(a,h):void 0,perTurnCachedUsd:h?a/1e6*h.cacheReadPerM:void 0}}function qv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${R(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${R(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${R(t.baselineTokens)} plain conversation + ${R(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Vt(t.perTurnUsd)} at list price, ${Vt(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 ~${R(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?` [~${R(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>=zA&&e.push(`To recover the ~${R(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${hp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
73
- `))}function Fv(t,{record:e=!0}={}){let r=AA(t);return e&&ja({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as lx}from"node:child_process";import{existsSync as dx,lstatSync as YA,readdirSync as QA,readFileSync as eO,realpathSync as $p,statSync as tO}from"node:fs";import{homedir as rO}from"node:os";import{basename as kp,extname as Ba,isAbsolute as nO,join as Jt,relative as fx,resolve as oO,sep as sO}from"node:path";import{execFile as OA,spawnSync as Uv}from"node:child_process";import{existsSync as Hv,mkdtempSync as Bv,readFileSync as _p,rmSync as Vv}from"node:fs";import{tmpdir as Jv}from"node:os";import{dirname as Wv,extname as Kv,join as Da}from"node:path";var La=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),Gv={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function Ps(t,e){try{let r=Uv(t,e,Gv);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var Xv=["-convert","txt","-noload","-nostore","-stdout"],Yv='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function NA(t){let e=Ps("pdftotext",["-enc","UTF-8",t,"-"])??Ps("pdftotext",[t,"-"]);if(e)return e;let r=Da(Bv(Da(Jv(),"cd-pdf-")),"out.txt");try{Uv("pdftotext",[t,r],Gv);let n=Hv(r)?_p(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{Vv(Wv(r),{recursive:!0,force:!0})}}function MA(t,e){let r=Ps("unzip",["-p",t,...e]);return r?Qv(r):void 0}function Qv(t){return t.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
64
+ `)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=nA(r[n]);o===void 0?delete r[n]:r[n]=o}FC(e,JSON.stringify({ts:Date.now(),...r})+`
65
+ `)}catch{}}var aA=2,cA=.5,uA=2;function lA(){return iA(sA(gp()),".context-doctor-calibration.json")}function dA(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 fA(){try{return JSON.parse(oA(lA(),"utf8"))}catch{return{}}}function Nv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=fA()[dA(t)];if(!e||e.v!==aA||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<cA||r>uA?{factor:1,samples:0}:{factor:r,samples:e.samples}}function mA(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 hA(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 gA(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function Mv(t){return pA("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function yA(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 _A(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=yA(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var jv=.6;function vA(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 Zv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function xA(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function bA(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;Zv.lastIndex=0;for(let n of e.matchAll(Zv)){let o=n[2].replace(/\\+$/,"");xA(o)&&r.add(o)}return[...r]}function Dv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=Nv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(At(y.text,r)*n.factor)+lp})),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[mA(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 ~${R(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 ~${R(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=Mv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-lp,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${R(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(H=>H.msg.text.length>=300).sort((H,xe)=>xe.tokens-H.tokens).slice(0,150),x=y.map(H=>_A(H.msg.text)),$=x.map(H=>H.size),N=new Set(a.filter(H=>H.id==="duplicate_content").flatMap(H=>H.messages)),A=y.map((H,xe)=>xe),ae=H=>{for(;A[H]!==H;)H=A[H]=A[A[H]];return H},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let H=0;H<y.length;H++)for(let xe=H+1;xe<y.length;xe++){let Mt=y[H],qr=y[xe];if(N.has(Mt.msg.index)&&N.has(qr.msg.index))continue;let Ls=Math.min($[H],$[xe]),Pn=Math.max($[H],$[xe]);if(Pn===0||Ls/Pn<jv)continue;let wt=vA(x[H],x[xe]);wt<jv||(A[ae(H)]=ae(xe),wt>ce[H].sim&&(ce[H]={sim:wt,partnerTokens:qr.tokens}),wt>ce[xe].sim&&(ce[xe]={sim:wt,partnerTokens:Mt.tokens}))}let Re=new Map;y.forEach((H,xe)=>{if(ce[xe].sim===0)return;let Mt=ae(xe);Re.set(Mt,[...Re.get(Mt)??[],xe])});for(let H of Re.values()){if(H.length<2)continue;H.sort(($t,Ur)=>y[$t].msg.index-y[Ur].msg.index);let xe=H.slice(1),Mt=xe.reduce(($t,Ur)=>$t+Math.round(Math.min(y[Ur].tokens,ce[Ur].partnerTokens)*ce[Ur].sim*.9),0),qr=H.map($t=>ce[$t].sim),Ls=Math.round(Math.min(...qr)*100),Pn=Math.round(Math.max(...qr)*100),wt=H.map($t=>y[$t].msg.index),sm=Ls===Pn?`~${Pn}%`:`${Ls}-${Pn}%`,ow=xe.reduce(($t,Ur)=>$t+y[Ur].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Mt,message:H.length===2?`Messages #${wt[0]} and #${wt[1]} are ${sm} similar (~${R(Math.min(y[H[0]].tokens,y[H[1]].tokens))} tokens repeated with different framing).`:`${H.length} messages are ${sm} similar to each other (${wt.slice(0,6).map($t=>`#${$t}`).join(", ")}${wt.length>6?", \u2026":""}): ~${R(ow)} tokens in the ${xe.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:wt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=Mv(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let l=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((N,A)=>l(y[A])?.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 bA(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let N=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),A=Math.round(N*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:A>4e3?"high":"warn",estSavings:A,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 ~${R(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)yo(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 (~${R(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 d=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,N)=>$+N.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${R(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 ~${R(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:[]}),(Mr(e)==="anthropic"||Mr(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 m=Za(e),p=m?s/m*100:void 0;p!==void 0&&p>70&&a.push({id:"near_window_limit",severity:p>90?"high":"warn",estSavings:0,message:`Context is at ~${p.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:gA(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),g={high:0,warn:1,info:2};a.sort((y,x)=>g[y.severity]-g[x.severity]||x.estSavings-y.estSavings);let h=hA(a,s),_=go(e),v;if(_){let y=jr(s,_),x=jr(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:fp(s),ttftSavedSeconds:fp(h)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:h,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as wA}from"node:crypto";var Uv=10,qa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:Uv};function $A(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 kA(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 Lv(t,e,r){let n=Math.round(e*up("",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 yp(t,e,r=Uv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function SA(t){return wA("sha1").update(t.trim()).digest("hex")}function vo(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"?vo(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
+ `):JSON.stringify(t)}function _p(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(d=>d?.type==="text"&&typeof d.text=="string");if(a.length===0)return s;let c=a.map(d=>d.text).join(`
68
+ `),u=e(c,i);if(u===c)return s;let l=!1;return s.map(d=>d?.type==="text"&&typeof d.text=="string"?l?null:(l=!0,{...d,text:u}):d).filter(d=>d!==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 vp(t){return typeof t=="string"?yo(t)?pp(t):t:Array.isArray(t)?t.map(vp):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,vp(r)])):t}function TA(t,e,r){let n=Math.round(e*up(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 EA(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 qv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function Fv(t,e={}){let r={strategies:e.strategies??qa.strategies,keepRecent:e.keepRecent??qa.keepRecent,maxToolResultTokens:e.maxToolResultTokens??qa.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):qa.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 h=o.length-1;h>=0;h--)(!o[h]||typeof o[h]!="object")&&o.splice(h,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(h=>Array.isArray(h?.content)&&h.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=h=>At(h,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:vo(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=h=>{let _=a(vo(h.content));for(let v of Array.isArray(h.tool_calls)?h.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return h.function_call&&(_+=a(`${h.function_call.name??""} ${h.function_call.arguments??""}`)),_},l=c+o.reduce((h,_)=>h+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((h,_)=>{let v=vo(h.content);if(!yo(v))return;let y=a(v),x=_p(h,N=>yo(N)?pp(N):N);Array.isArray(x)&&(x=x.map(N=>N?.type==="tool_use"&&N.input!=null?{...N,input:vp(N.input)}:N));let $=y-a(vo(x));$>50&&(h.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,N=_p(v,A=>{if(A.length<300)return A;let ae=SA(A),ce=_.get(ae);if(ce===void 0)return _.set(ae,y),A;if(y>=h)return A;let Re=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(A)-a(Re),$??=ce,Re});x<=0||(v.content=N,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h||!qv(_))return;let y=0,x=_p(_,($,N)=>{if(N!=="tool_result")return $;let A=a($);if(A<=r.maxToolResultTokens)return $;let ae=TA($,r.maxToolResultTokens,i),ce=a(ae);return ce>=A?$:(y+=A-ce,ae)});y<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:y,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h)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"||kA(o,v,$A(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let N=Lv(x.input,r.maxToolResultTokens,i),A=a(JSON.stringify(N));A>=$||(x.input=N,y+=$-A)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let N=a($);if(N<=r.maxToolResultTokens)continue;let A;try{A=JSON.parse($)}catch{continue}if(!A||typeof A!="object"||Array.isArray(A))continue;let ae=JSON.stringify(Lv(A,r.maxToolResultTokens,i)),ce=a(ae);ce>=N||(x.function.arguments=ae,y+=N-ce)}y>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:y,note:"Arguments of a completed tool call truncated"})})}let m,p=0;for(;p<o.length&&(o[p]?.role==="system"||o[p]?.role==="developer");)p++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-p>f*2){let h=o.length-f;for(;h<o.length&&qv(o[h]);)h++;if(o.length-h>=2){EA(o.slice(h));let _=o.slice(p,h),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${vo(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(p,h-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let g=c+o.reduce((h,_)=>h+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:g,applied:d,prunedDigest:m}}var Hv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},zA={high:"\u2716",warn:"\u25B2",info:"\u2139"};function RA(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function PA(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 Bv(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: ~${R(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 ${R(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Kt(n.cost.perCallUsd)} input per call \xB7 ~${Kt(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])=>Hv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${Hv[i].padEnd(s)} ${RA(c)} ${String(Math.round(c*100)).padStart(3)}% ~${R(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}] ~${R(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 l=a.get(u.id)??0;if(l>=i){let p=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:p.count+1,savings:p.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${R(u.estSavings)}]`:"";r.push(`${zA[u.severity]} ${e.redact?PA(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let m=c.get(u.id);l+1===i&&m===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,l]of c){if(l.count===0)continue;let d=Math.min(l.savings,n.totalEstSavings),m=d>0?`, up to ~${R(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${m}. 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,l=`Potential recovery: ~${R(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Kt(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(l),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 IA=2060,CA={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},AA=6.3,OA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},NA=1500,Vv=2e3,MA=30,xp=400,jA=1e4,ZA=6;function DA(t,e){let r=Cs[Mr(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function LA(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):NA;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*CA[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*AA:OA[t.kind];return Math.round(r/DA(t.kind,e))}function bp(t){return Math.round(IA/Cs[Mr(t)].prose)}var Jv=60;function qA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Jv?e.slice(0,Jv-1)+"\u2026":e}function UA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:qA(_?.label)})),n=bp(t.model),o=e*n,s=r.map(_=>({block:_,tokens:LA(_,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 (~${R(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 (~${R(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>=Vv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Vv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${R(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 (~${R(_)}) 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>=MA){let _=ZA*n+xp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${R(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${xp}-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 ~${R(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Za(t.model),d=l?Math.round(a/l*100):void 0;d!==void 0&&d>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${d}% of the ${R(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let m={high:0,warn:1,info:2};c.sort((_,v)=>m[_.severity]-m[v.severity]||v.estSavings-_.estSavings);let p=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),g=Math.min(a,Math.max(p,f)),h=go(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:g,perTurnUsd:h?jr(a,h):void 0,perTurnCachedUsd:h?a/1e6*h.cacheReadPerM:void 0}}function Wv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${R(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${R(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${R(t.baselineTokens)} plain conversation + ${R(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Kt(t.perTurnUsd)} at list price, ${Kt(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 ~${R(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?` [~${R(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>=jA&&e.push(`To recover the ~${R(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${xp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
73
+ `))}function Kv(t,{record:e=!0}={}){let r=UA(t);return e&&La({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as vx}from"node:child_process";import{existsSync as xx,lstatSync as cO,readdirSync as uO,readFileSync as lO,realpathSync as zp,statSync as dO}from"node:fs";import{homedir as bx}from"node:os";import{basename as Rp,extname as Wa,isAbsolute as fO,join as pe,relative as wx,resolve as pO,sep as mO}from"node:path";import{execFile as FA,spawnSync as Gv}from"node:child_process";import{existsSync as Xv,mkdtempSync as Yv,readFileSync as $p,rmSync as Qv}from"node:fs";import{tmpdir as ex}from"node:os";import{dirname as tx,extname as rx,join as Ua,resolve as HA}from"node:path";var Fa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),nx={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function As(t,e){try{let r=Gv(t,e,nx);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var ox=["-convert","txt","-noload","-nostore","-stdout"],sx='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function BA(t){let e=As("pdftotext",["-enc","UTF-8",t,"-"])??As("pdftotext",[t,"-"]);if(e)return e;let r=Ua(Yv(Ua(ex(),"cd-pdf-")),"out.txt");try{Gv("pdftotext",[t,r],nx);let n=Xv(r)?$p(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{Qv(tx(r),{recursive:!0,force:!0})}}function VA(t,e){let r=As("unzip",["-p",t,...e]);return r?ix(r):void 0}function ix(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(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&").replace(/\n{3,}/g,`
76
76
 
77
- `).trim()}function ex(t){let e=Kv(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=NA(t)?.replace(/\f/g,`
77
+ `).trim()}function ax(t){return HA(t)}function cx(t){let e=ax(t),r=rx(e).toLowerCase(),n=process.platform==="darwin",o;if(r===".pdf"){if(o=BA(e)?.replace(/\f/g,`
78
78
 
79
- `),!n&&r&&(n=Ps("osascript",["-l","JavaScript","-e",Yv,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=Ps("textutil",[...Xv,t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=MA(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 Is=2e4,ut=()=>performance.now();function jA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function yp(t,e,r){let n=Math.ceil(r-ut());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(jA(n));return new Promise(s=>{let i=!1,a=l=>{i||(i=!0,clearTimeout(u),s(l))},c,u=setTimeout(()=>{c?.kill("SIGKILL"),a({timedOut:ut()>=r-50})},o);try{c=OA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:ut()>=r-50});a({out:typeof d=="string"&&d.trim()?d:void 0,timedOut:!1})}),c.on("error",()=>a({timedOut:!1})),c.stdin?.on("error",()=>{}),c.stdin?.end()}catch{a({timedOut:!1})}})}async function qa(t,e=ut()+Is){let r=Kv(t).toLowerCase(),n=process.platform==="darwin",o,s=!1,i=async(c,u)=>{if(o||s)return;let l=await yp(c,u,e);l.timedOut?s=!0:o=l.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=Da(Bv(Da(Jv(),"cd-pdf-")),"out.txt");try{(await yp("pdftotext",[t,c],e)).timedOut?s=!0:Hv(c)&&(o=_p(c,"utf8").trim()?_p(c,"utf8"):void 0)}finally{Vv(Wv(c),{recursive:!0,force:!0})}}return o=o?.replace(/\f/g,`
79
+ `),!o&&n&&(o=As("osascript",["-l","JavaScript","-e",sx,e])),!o)return{error:n?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(n&&r!==".pptx"&&(o=As("textutil",[...ox,e])),!o){let s=r===".docx"?["word/document.xml"]:r===".pptx"?["ppt/slides/*.xml"]:r===".odt"?["content.xml"]:[];s.length&&(o=VA(e,s))}if(!o)return{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:o}}var Os=2e4,lt=()=>performance.now();function JA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function wp(t,e,r){let n=Math.ceil(r-lt());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(JA(n));return new Promise(s=>{let i=!1,a=l=>{i||(i=!0,clearTimeout(u),s(l))},c,u=setTimeout(()=>{c?.kill("SIGKILL"),a({timedOut:lt()>=r-50})},o);try{c=FA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:lt()>=r-50});a({out:typeof d=="string"&&d.trim()?d:void 0,timedOut:!1})}),c.on("error",()=>a({timedOut:!1})),c.stdin?.on("error",()=>{}),c.stdin?.end()}catch{a({timedOut:!1})}})}async function Ha(t,e=lt()+Os){let r=ax(t),n=rx(r).toLowerCase(),o=process.platform==="darwin",s,i=!1,a=async(u,l)=>{if(s||i)return;let d=await wp(u,l,e);d.timedOut?i=!0:s=d.out},c=()=>({error:"not read: the time allowed for reading documents in this call ran out"});if(n===".pdf"){if(await a("pdftotext",["-enc","UTF-8",r,"-"]),await a("pdftotext",[r,"-"]),!s&&!i){let u=Ua(Yv(Ua(ex(),"cd-pdf-")),"out.txt");try{(await wp("pdftotext",[r,u],e)).timedOut?i=!0:Xv(u)&&(s=$p(u,"utf8").trim()?$p(u,"utf8"):void 0)}finally{Qv(tx(u),{recursive:!0,force:!0})}}return s=s?.replace(/\f/g,`
80
80
 
81
- `),!o&&n&&await i("osascript",["-l","JavaScript","-e",Yv,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",[...Xv,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 yp("unzip",["-p",t,...c],e);u.timedOut?s=!0:u.out&&(o=Qv(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)":""}`}}import{homedir as tx}from"node:os";import{join as ZA,resolve as DA}from"node:path";function go(t,e=process.env){if(t===void 0||t===tx()){let r=e.CODEX_HOME?.trim();if(r)return DA(r)}return ZA(t??tx(),".codex")}var iO=4e3,aO=400,cO="claude",uO=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"]),lO=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function dO(t,e){let r=Ba(t).toLowerCase();return lO.has(r)?"markdown":uO.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var fO=/^(?![\s})\]]|$)/,cx=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function pO(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,l)=>{u>s&&t.slice(s,u).some(d=>d.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=l};for(let u=0;u<t.length;u++){let l=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(l)&&(a=!a);let d=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l);if(d){c(u,!0);let m=d[1].length;n.length=m-1,n[m-1]=d[2],o=n.filter(Boolean).join(" > ");continue}!a&&!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&l.trim()&&fO.test(l)&&c(u,!1):!l.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 l=t.slice(u.start,u.end).map(p=>p.trim()).filter(Boolean),d=l.map(p=>p.replace(cx,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!cx.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var mO=t=>t>=55296&&t<=56319,hO=t=>t>=56320&&t<=57343;function px(t,e={}){let r=Math.max(50,e.maxChunkTokens??aO),n=e.model??cO,o=dO(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
81
+ `),!s&&o&&await a("osascript",["-l","JavaScript","-e",sx,r]),s?{text:s}:i?c():{error:o?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}if(o&&n!==".pptx"&&await a("textutil",[...ox,r]),!s&&!i){let u=n===".docx"?["word/document.xml"]:n===".pptx"?["ppt/slides/*.xml"]:n===".odt"?["content.xml"]:[];if(u.length){let l=await wp("unzip",["-p",r,...u],e);l.timedOut?i=!0:l.out&&(s=ix(l.out))}}return s?{text:s}:i?c():{error:o?"unreadable document":`needs unzip${n===".doc"||n===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}import{homedir as ux}from"node:os";import{join as WA,resolve as KA}from"node:path";function Sn(t,e=process.env){if(t===void 0||t===ux()){let r=e.CODEX_HOME?.trim();if(r)return KA(r)}return WA(t??ux(),".codex")}var hO=4e3,gO=400,yO="claude",_O=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"]),vO=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function xO(t,e){let r=Wa(t).toLowerCase();return vO.has(r)?"markdown":_O.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var bO=/^(?![\s})\]]|$)/,gx=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function wO(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,l)=>{u>s&&t.slice(s,u).some(d=>d.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=l};for(let u=0;u<t.length;u++){let l=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(l)&&(a=!a);let d=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l);if(d){c(u,!0);let m=d[1].length;n.length=m-1,n[m-1]=d[2],o=n.filter(Boolean).join(" > ");continue}!a&&!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&l.trim()&&bO.test(l)&&c(u,!1):!l.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 l=t.slice(u.start,u.end).map(p=>p.trim()).filter(Boolean),d=l.map(p=>p.replace(gx,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!gx.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var $O=t=>t>=55296&&t<=56319,kO=t=>t>=56320&&t<=57343;function $x(t,e={}){let r=Math.max(50,e.maxChunkTokens??gO),n=e.model??yO,o=xO(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
82
82
  `).split(`
83
- `).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;mO(m.charCodeAt(g-1))&&hO(m.charCodeAt(g))&&g--,s.push(m.slice(0,g)),i.push(p+1),m=m.slice(g)}s.push(m),i.push(p+1)});let c=[0];for(let m of s)c.push(c[c.length-1]+It(m+`
84
- `,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of pO(s,o)){if(u(m.start,m.end)<=r){l.push(m);continue}let p=m.start;for(let f=m.start+1;f<=m.end;f++)if(f===m.end||u(p,f+1)>r){let g=p===m.start;l.push({start:p,end:f,heading:g?m.heading:`${m.heading} (cont.)`,hard:g&&m.hard}),p=f}}let d=[];for(let m of l){let p=d[d.length-1];p&&!m.hard&&p.heading===m.heading&&u(p.start,m.end)<=r||p&&!m.hard&&o!=="markdown"&&u(p.start,m.end)<=r?p.end=m.end:d.push({...m})}return d.map((m,p)=>{let f=m.start,g=m.end;for(;f<g&&!s[f].trim();)f++;for(;g>f&&!s[g-1].trim();)g--;let h=s.slice(f,g).join(`
85
- `);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[g-1]??g,heading:m.heading,text:h,tokens:It(h,n),score:0}})}var gO=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 Ua(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||gO.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 mx(t,e){let r=[...new Set(Ua(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...Ua(i.text),...Ua(i.heading),...Ua(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,l)=>{let d=u.tf.get(i)??0;d&&(t[l].score+=c*(d*2.2/(d+1.2*(1-.75+.75*u.len/o))))})}}function hx(t,e={}){let r=t.map(o=>px(o,e)),n=e.query?.trim()||void 0;return n&&mx(r.flat(),n),yx(t,r,n,e)}async function gx(t,e={}){let r=t.map(s=>px(s,e)),n=e.query?.trim()||void 0,o;if(n&&(mx(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(ax(),ix));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...yx(t,r,n,e),semanticNote:o}}function yx(t,e,r,n){let o=Math.max(1,n.budget??iO),s=e.flat(),i=[],a=[],c=[],u=0,l=(p,f)=>{if(!i.includes(p)){if(u+p.tokens>o){c.some(g=>g.id===p.id)||c.push({id:p.id,tokens:p.tokens,requested:f});return}i.push(p),u+=p.tokens}},d="outline";if(n.ids?.length){d="ids";let p=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let g=p.get(f);g?l(g,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let p of[...s].filter(f=>f.score>0).sort((f,g)=>g.score-f.score))l(p,!1)}let m=new Map(s.map((p,f)=>[p,f]));return i.sort((p,f)=>m.get(p)-m.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((p,f)=>p+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((p,f)=>({name:p.name,tokens:e[f].reduce((g,h)=>g+h.tokens,0),chunks:e[f].length,selected:e[f].filter(g=>i.includes(g)).length}))}}function bp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${R(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function _x(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}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...bp(t.chunks,e)),r.join(`
86
- `);r.push(`PACKED ~${R(t.packedTokens)} of ~${R(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${R(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 ${R(t.budget)}: ${s.map(a=>`${a.id} (~${R(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 ${R(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${R(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...bp(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(...bp(t.chunks,e)),r.join(`
83
+ `).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;$O(m.charCodeAt(g-1))&&kO(m.charCodeAt(g))&&g--,s.push(m.slice(0,g)),i.push(p+1),m=m.slice(g)}s.push(m),i.push(p+1)});let c=[0];for(let m of s)c.push(c[c.length-1]+At(m+`
84
+ `,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of wO(s,o)){if(u(m.start,m.end)<=r){l.push(m);continue}let p=m.start;for(let f=m.start+1;f<=m.end;f++)if(f===m.end||u(p,f+1)>r){let g=p===m.start;l.push({start:p,end:f,heading:g?m.heading:`${m.heading} (cont.)`,hard:g&&m.hard}),p=f}}let d=[];for(let m of l){let p=d[d.length-1];p&&!m.hard&&p.heading===m.heading&&u(p.start,m.end)<=r||p&&!m.hard&&o!=="markdown"&&u(p.start,m.end)<=r?p.end=m.end:d.push({...m})}return d.map((m,p)=>{let f=m.start,g=m.end;for(;f<g&&!s[f].trim();)f++;for(;g>f&&!s[g-1].trim();)g--;let h=s.slice(f,g).join(`
85
+ `);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[g-1]??g,heading:m.heading,text:h,tokens:At(h,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 Va(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 kx(t,e){let r=[...new Set(Va(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...Va(i.text),...Va(i.heading),...Va(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,l)=>{let d=u.tf.get(i)??0;d&&(t[l].score+=c*(d*2.2/(d+1.2*(1-.75+.75*u.len/o))))})}}function Sx(t,e={}){let r=t.map(o=>$x(o,e)),n=e.query?.trim()||void 0;return n&&kx(r.flat(),n),Ex(t,r,n,e)}async function Tx(t,e={}){let r=t.map(s=>$x(s,e)),n=e.query?.trim()||void 0,o;if(n&&(kx(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(hx(),mx));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...Ex(t,r,n,e),semanticNote:o}}function Ex(t,e,r,n){let o=Math.max(1,n.budget??hO),s=e.flat(),i=[],a=[],c=[],u=0,l=(p,f)=>{if(!i.includes(p)){if(u+p.tokens>o){c.some(g=>g.id===p.id)||c.push({id:p.id,tokens:p.tokens,requested:f});return}i.push(p),u+=p.tokens}},d="outline";if(n.ids?.length){d="ids";let p=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let g=p.get(f);g?l(g,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let p of[...s].filter(f=>f.score>0).sort((f,g)=>g.score-f.score))l(p,!1)}let m=new Map(s.map((p,f)=>[p,f]));return i.sort((p,f)=>m.get(p)-m.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((p,f)=>p+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((p,f)=>({name:p.name,tokens:e[f].reduce((g,h)=>g+h.tokens,0),chunks:e[f].length,selected:e[f].filter(g=>i.includes(g)).length}))}}function Tp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${R(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function zx(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}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...Tp(t.chunks,e)),r.join(`
86
+ `);r.push(`PACKED ~${R(t.packedTokens)} of ~${R(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${R(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 ${R(t.budget)}: ${s.map(a=>`${a.id} (~${R(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 ${R(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${R(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...Tp(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(...Tp(t.chunks,e)),r.join(`
88
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 ~${R(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 yO=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Ha={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function _O(t){try{let e=lx("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&&dx(Jt(t,r))).sort()}catch{return}}function vO(t){let e=lx("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 vx(t,e){let r=fx(t,e);return r===""||r!==".."&&!r.startsWith(".."+sO)&&!nO(r)}var xO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd",".vault-token",".credentials.json","oauth_creds.json","credentials.tfrc.json"]),bO=[[".codex",["auth.json"]],[".cargo",["credentials","credentials.toml"]],[".gem",["credentials"]]],wO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function ux(t){let e=kp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(xO.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(wO.has(Ba(r)))return`a key or certificate store (${Ba(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials";let o=(n[n.length-2]??"").toLowerCase();if(bO.some(([s,i])=>s===o&&i.includes(r)))return`a credentials file (${o}/${e})`}function $O(){let t=rO(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",Jt(".config","gcloud"),Jt(".config","gh"),Jt(".config","github-copilot"),Jt("Library","Keychains"),".password-store"].map(n=>Jt(t,n)),Jt(Nr(),".credentials.json"),Jt(go(),"auth.json"),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"],r=e.map(n=>{try{return $p(n)}catch{return n}});return[...new Set([...e,...r])]}function kO(t,e){return e.find(r=>vx(r,t))}function wp(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 SO(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?[]:$O(),a=[],c=[],u=0,l=new Set,d="",m=0,p=!1,f=h=>{try{return $p(h)}catch{return oO(h)}},g=(h,_)=>{if(a.length>=Ha.files){(_||c.length<20)&&c.push(`${h}: over ${Ha.files} files`);return}let v;try{v=_?tO(h):YA(h)}catch(A){c.push(`${h}: ${wp(A)}`);return}if(v.isSymbolicLink()){let A;try{A=$p(h)}catch{return}vx(d,A)||c.push(`${h}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let A=kO(f(h),i);if(A){_&&c.push(`${h}: refused, ${A} holds credentials${s}`);return}}if(v.isDirectory()){let A=kp(h);if(!_&&yO.has(A))return;if(!_&&A.startsWith(".")){m++;return}let ce=_?_O(h):void 0;if(_&&(p=ce!==void 0),ce){ce.length===0&&vO(h)&&c.push(`${h}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let ze of ce)g(Jt(h,ze),!1);return}let ue;try{ue=QA(h).sort()}catch(ze){c.push(`${h}: ${wp(ze)}`);return}for(let ze of ue)g(Jt(h,ze),!1);return}if(!v.isFile()){_&&c.push(`${h}: not a regular file`);return}if(!o){let A=ux(h)??ux(f(h));if(A){c.push(`${h}: ${A}, likely holding secrets; not packed${s}`);return}}if(!_&&kp(h).startsWith(".")&&!p){m++;return}let y=f(h);if(l.has(y))return;if(v.size>Ha.fileBytes||u+v.size>Ha.totalBytes){c.push(`${h}: too large (${Math.round(v.size/1024)} KB)`);return}let x=fx(n,h),$=x&&!x.startsWith("..")?x:h;if(La.has(Ba(h).toLowerCase())){if(r.defer){u+=v.size,l.add(y),a.push({name:$,text:""}),r.defer.push({slot:a.length-1,path:h});return}let A=ex(h);"error"in A?c.push(`${h}: ${A.error}`):(u+=v.size,l.add(y),a.push({name:$,text:A.text}));return}let N;try{N=eO(h)}catch(A){c.push(`${h}: ${wp(A)}`);return}if(N.subarray(0,8e3).includes(0)){_&&c.push(`${h}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}u+=v.size,l.add(y),a.push({name:$,text:N.toString("utf8")})};for(let h of t){if(!dx(h)){c.push(`${h}: not found`);continue}d=f(h),m=0,p=!1,g(h,!0),m>0&&c.push(`${h}: ${m} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:a,skipped:c}}async function xx(t,e={}){let r=[],{sources:n,skipped:o}=SO(t,{...e,defer:r}),s=ut()+(e.budgetMs??Is),i=new Set;for(let a of r){let c=await qa(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 bx=`Context hygiene rules (always on):
89
+ `)}var TO=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Ja={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024},Rx=["-c","core.fsmonitor=false"];function EO(t){try{let e=vx("git",[...Rx,"-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&&xx(pe(t,r))).sort()}catch{return}}function zO(t){let e=vx("git",[...Rx,"-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 Px(t,e){let r=wx(t,e);return r===""||r!==".."&&!r.startsWith(".."+mO)&&!fO(r)}var RO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd",".vault-token",".credentials.json","oauth_creds.json","credentials.tfrc.json"]),PO=[[".codex",["auth.json"]],[".cargo",["credentials","credentials.toml"]],[".gem",["credentials"]]],IO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function yx(t){let e=Rp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(RO.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(IO.has(Wa(r)))return`a key or certificate store (${Wa(r)})`;let n=t.split(/[\\/]+/),o=(n[n.length-2]??"").toLowerCase();if(r==="credentials"&&o===".aws")return"AWS credentials";if(PO.some(([s,i])=>s===o&&i.includes(r)))return`a credentials file (${o}/${e})`}function CO(){let t=bx(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",pe(".config","gcloud"),pe(".config","gh"),pe(".config","github-copilot"),pe("Library","Keychains"),".password-store"].map(r=>pe(t,r)),pe(ur(),".credentials.json"),pe(Sn(),"auth.json"),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"];return[...new Set([...e,...e.map(Tn)])]}function AO(){let t=bx(),e=[Iv(),pe(t,".claude.json"),...[ur(),pe(t,".claude")].flatMap(r=>[pe(r,"settings.json"),pe(r,"settings.local.json")]),pe(t,".cursor","mcp.json"),pe(Sn(),"config.toml"),pe(t,".codex","config.toml"),pe(t,".gemini","settings.json"),pe(t,".gemini","config","mcp_config.json"),pe(t,".gemini","antigravity","mcp_config.json"),pe(t,"Library","Application Support","Claude","claude_desktop_config.json"),pe(process.env.APPDATA||pe(t,"AppData","Roaming"),"Claude","claude_desktop_config.json"),pe(t,".config","Claude","claude_desktop_config.json"),pe(process.env.COPILOT_HOME||pe(t,".copilot"),"mcp-config.json"),pe(t,".copilot","mcp-config.json")];return[...new Set([...e,...e.map(Tn)])]}function Tn(t){for(let e of[zp.native,zp])try{return e(t)}catch{}return pO(t)}function _x(t,e){let r=process.platform==="darwin"||process.platform==="win32"?n=>n.toLowerCase():n=>n;return e.find(n=>Px(r(n),r(t)))}function Ep(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 OO(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?[]:CO(),a=o?[]:AO(),c=[],u=[],l=0,d=new Set,m="",p=0,f=!1,g=(h,_)=>{if(c.length>=Ja.files){(_||u.length<20)&&u.push(`${h}: over ${Ja.files} files`);return}let v;try{v=_?dO(h):cO(h)}catch(A){u.push(`${h}: ${Ep(A)}`);return}if(v.isSymbolicLink()){let A;try{A=Tn(zp(h))}catch{return}Px(m,A)||u.push(`${h}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let A=Tn(h),ae=_x(A,i);if(ae){_&&u.push(`${h}: refused, ${ae} holds credentials${s}`);return}let ce=_x(A,a);if(ce){u.push(`${h}: refused, ${ce} can hold API keys (an MCP server's env)${s}`);return}}if(v.isDirectory()){let A=Rp(h);if(!_&&TO.has(A))return;if(!_&&A.startsWith(".")){p++;return}let ae=_?EO(h):void 0;if(_&&(f=ae!==void 0),ae){ae.length===0&&zO(h)&&u.push(`${h}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Re of ae)g(pe(h,Re),!1);return}let ce;try{ce=uO(h).sort()}catch(Re){u.push(`${h}: ${Ep(Re)}`);return}for(let Re of ce)g(pe(h,Re),!1);return}if(!v.isFile()){_&&u.push(`${h}: not a regular file`);return}if(!o){let A=yx(h)??yx(Tn(h));if(A){u.push(`${h}: ${A}, likely holding secrets; not packed${s}`);return}}if(!_&&Rp(h).startsWith(".")&&!f){p++;return}let y=Tn(h);if(d.has(y))return;if(v.size>Ja.fileBytes||l+v.size>Ja.totalBytes){u.push(`${h}: too large (${Math.round(v.size/1024)} KB)`);return}let x=wx(n,h),$=x&&!x.startsWith("..")?x:h;if(Fa.has(Wa(h).toLowerCase())){if(r.defer){l+=v.size,d.add(y),c.push({name:$,text:""}),r.defer.push({slot:c.length-1,path:h});return}let A=cx(h);"error"in A?u.push(`${h}: ${A.error}`):(l+=v.size,d.add(y),c.push({name:$,text:A.text}));return}let N;try{N=lO(h)}catch(A){u.push(`${h}: ${Ep(A)}`);return}if(N.subarray(0,8e3).includes(0)){_&&u.push(`${h}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}l+=v.size,d.add(y),c.push({name:$,text:N.toString("utf8")})};for(let h of t){if(!xx(h)){u.push(`${h}: not found`);continue}m=Tn(h),p=0,f=!1,g(h,!0),p>0&&u.push(`${h}: ${p} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:c,skipped:u}}async function Ix(t,e={}){let r=[],{sources:n,skipped:o}=OO(t,{...e,defer:r}),s=lt()+(e.budgetMs??Os),i=new Set;for(let a of r){let c=await Ha(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 Cx=`Context hygiene rules (always on):
90
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
91
  2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
92
92
  3. Summarize any paste or tool result over ~2k tokens into the points you need.
93
93
  4. Refer to earlier content by name; never re-quote it or inline base64.
94
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 TO=["openai/session","openai/subject"];function wx(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&TO.some(n=>typeof t[n]=="string")?"compact":"full"}var yo=t=>Math.round(t);function $x(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${R(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${R(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,yo(c)])),i={total_tokens:yo(t.totalTokens),messages:t.messageCount,recoverable_tokens:yo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${R(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:yo(a.tokens),preview:a.preview}))}}}function kx(t,e){let[r,...n]=t.findings,o=[`~${R(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${R(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?` ~${R(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 EO(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function zO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function Sx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=zO(d.heading),f=m[m.length-1];f&&f.heading===p?(f.last=d.id,f.tokens+=d.tokens):m.push({first:d.id,last:d.id,heading:p,tokens:d.tokens}),n.set(d.source,m)}let o=r,s=0,i=[...n.entries()].map(([d,m])=>{let p=m.slice(0,Math.max(0,o));o-=p.length,s+=m.length-p.length;let f=m.reduce((g,h)=>g+h.tokens,0);return{name:d,tokens:yo(f),sections:p.map(g=>`${EO(g.first,g.last)} ${g.heading} ~${R(g.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}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks, as sections in structuredContent. Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${c}).`,l={total_tokens:yo(t.totalTokens),chunks:t.chunks.length,sources:i};return s>0&&(l.sections_not_shown=s),{text:u,structured:l,meta:{"context-doctor/outline":e}}}import{existsSync as RO,lstatSync as cr,mkdirSync as Rx,readdirSync as PO,readFileSync as Sp,realpathSync as Va,rmSync as IO,writeFileSync as Tx}from"node:fs";import{homedir as vo}from"node:os";import{isAbsolute as CO,join as st,relative as AO,sep as OO}from"node:path";var vt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function Ep(t=vo()){return st(t,".context-doctor","handoffs")}var NO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function Px(t){return typeof t=="string"&&t.length<=80&&NO.test(t)}function MO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function jO(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 zp(t){let e=[],r=vt;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 _o="masked by context-doctor",Fe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${_o}]`:void 0}),ZO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),DO=[Fe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),Fe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),Fe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,ZO),Fe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),Fe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),Fe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),Fe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),Fe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),Fe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),Fe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),Fe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),Fe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),Fe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),Fe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),Fe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),Fe("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]}:[${_o}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${_o}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${_o}]`}],Ix="(?: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?)",LO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ix}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),qO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ix}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),FO=/^(?: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,UO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function Ex(t){return!(FO.test(t)||UO.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 Mr(t){let e=0,r=new Set,n=String(t??"");for(let o of DO)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(qO,(o,s,i,a)=>Ex(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${_o}]${i}`):o),n=n.replace(LO,(o,s,i)=>Ex(i)?(e++,r.add("a password or secret assignment"),`${s}[${_o}]`):o),{text:n,count:e,kinds:[...r]}}function HO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function Tp(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function BO(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=HO(s.text);o.push("",`### ${Tp(s.label,vt.labelChars)}`,"",i,s.text.replace(/\s+$/,""),i)}}return o.join(`
95
+ 6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var NO=["openai/session","openai/subject"];function Ax(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&NO.some(n=>typeof t[n]=="string")?"compact":"full"}var xo=t=>Math.round(t);function Ox(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${R(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${R(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,xo(c)])),i={total_tokens:xo(t.totalTokens),messages:t.messageCount,recoverable_tokens:xo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${R(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:xo(a.tokens),preview:a.preview}))}}}function Nx(t,e){let[r,...n]=t.findings,o=[`~${R(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${R(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?` ~${R(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 MO(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function jO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function Mx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=jO(d.heading),f=m[m.length-1];f&&f.heading===p?(f.last=d.id,f.tokens+=d.tokens):m.push({first:d.id,last:d.id,heading:p,tokens:d.tokens}),n.set(d.source,m)}let o=r,s=0,i=[...n.entries()].map(([d,m])=>{let p=m.slice(0,Math.max(0,o));o-=p.length,s+=m.length-p.length;let f=m.reduce((g,h)=>g+h.tokens,0);return{name:d,tokens:xo(f),sections:p.map(g=>`${MO(g.first,g.last)} ${g.heading} ~${R(g.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}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks, as sections in structuredContent. Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${c}).`,l={total_tokens:xo(t.totalTokens),chunks:t.chunks.length,sources:i};return s>0&&(l.sections_not_shown=s),{text:u,structured:l,meta:{"context-doctor/outline":e}}}import{existsSync as ZO,lstatSync as dr,mkdirSync as Lx,readdirSync as DO,readFileSync as Pp,realpathSync as Ka,rmSync as LO,writeFileSync as jx}from"node:fs";import{homedir as wo}from"node:os";import{isAbsolute as qO,join as it,relative as UO,sep as FO}from"node:path";var bt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function Cp(t=wo()){return it(t,".context-doctor","handoffs")}var HO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function qx(t){return typeof t=="string"&&t.length<=80&&HO.test(t)}function BO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function VO(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 Ap(t){let e=[],r=bt;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 bo="masked by context-doctor",Fe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${bo}]`:void 0}),JO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),WO=[Fe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),Fe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),Fe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,JO),Fe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),Fe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),Fe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),Fe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),Fe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),Fe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),Fe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),Fe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),Fe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),Fe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),Fe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),Fe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),Fe("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]}:[${bo}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${bo}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${bo}]`}],Ux="(?: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?)",KO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ux}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),GO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ux}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),XO=/^(?: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,YO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function Zx(t){return!(XO.test(t)||YO.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 Zr(t){let e=0,r=new Set,n=String(t??"");for(let o of WO)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(GO,(o,s,i,a)=>Zx(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${bo}]${i}`):o),n=n.replace(KO,(o,s,i)=>Zx(i)?(e++,r.add("a password or secret assignment"),`${s}[${bo}]`):o),{text:n,count:e,kinds:[...r]}}function QO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function Ip(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function eN(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=QO(s.text);o.push("",`### ${Ip(s.label,bt.labelChars)}`,"",i,s.text.replace(/\s+$/,""),i)}}return o.join(`
98
98
  `)+`
99
- `}function VO(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)*gp(e.model),r.nowSource="turns");let n=fo(e.model);return n&&(r.afterUsd=Or(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=Or(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function Cx(t){let e=(o,s)=>o!==void 0?` (${Vt(o)} at list price, ${Vt(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${R(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: ~${R(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${R(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${R(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
100
- `)}function Ja(t,e){let r=AO(t,e);return r===""||r!==".."&&!r.startsWith(".."+OO)&&!CO(r)}var $n=class extends Error{};function Wa(t,e){let r=i=>{if(e)throw new $n(i)},n;try{n=Va(t)}catch{return r("the home directory cannot be read")}let o=st(t,".context-doctor"),s=Ep(t);for(let i of[o,s]){let a;try{a=cr(i)}catch{if(!e)return;try{Rx(i,{mode:448}),a=cr(i)}catch(u){return r(`cannot create ${_t(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${_t(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${_t(i,t)} is not a folder`);let c;try{c=Va(i)}catch{return r(`${_t(i,t)} cannot be read`)}if(!Ja(n,c))return r(`${_t(i,t)} resolves outside the home directory`)}return s}function zx(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function JO(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>zx(n,t)-zx(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var WO=0;function Ka(t=vo()){let e=Wa(t,!1);if(!e)return[];let r;try{r=PO(e)}catch{return[]}let n=[];for(let o of r){if(!Px(o))continue;let s=st(e,o);try{if(!cr(s).isDirectory())continue;let i=st(s,"meta.json");if(!cr(i).isFile())continue;let a=JSON.parse(Sp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(JO(Date.now()))}function Rp(t,e=vo()){let r=t==="latest"?Ka(e)[0]?.id:t;if(!Px(r))return;let n=Wa(e,!1);if(!n)return;let o=st(n,r),s=st(o,"handoff.md");if(Ja(n,s))try{let i=cr(s);if(!i.isFile()||i.size>vt.readBytes||!cr(o).isDirectory()||!cr(st(o,"meta.json")).isFile())return;let a=JSON.parse(Sp(st(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:Sp(s,"utf8")}}catch{return}}function KO(t,e,r){let n=Wa(t,!1);if(!n)return 0;let o=Ka(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=st(n,i.id);try{if(!Ja(n,a)||!cr(a).isDirectory()||!cr(st(a,"meta.json")).isFile()||!Ja(Va(n),Va(a)))continue;IO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function ar(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 Ax(t,{home:e=vo(),now:r=new Date,store:n=!0}={}){let o=zp(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Mr(x);return i+=$.count,$.kinds.forEach(N=>s.add(N)),$.text},c=a(ar(t.brief)),u=Tp(t.title?.trim()?a(ar(t.title,{keepNewlines:!1})):c.split(`
102
- `).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",vt.titleChars),l=(t.verbatim??[]).map(x=>({label:Tp(a(ar(x.label,{keepNewlines:!1})),vt.labelChars),text:a(ar(x.text))})),d=t.model===void 0?void 0:a(ar(String(t.model),{keepNewlines:!1})).slice(0,vt.modelChars)||void 0,m=r.toISOString(),p=BO(u,m,c,l),f=`${jO(r)}-${MO(u)}`,g={id:f,title:u,created:m,model:d,tokens:It(p,d),briefTokens:It(c,d),blocks:l.map(x=>({label:x.label,tokens:It(x.text,d)})),masked:i,order:Date.now()*1e3+WO++%1e3},h=VO(g.tokens,{...t,model:d});if(!n)return{meta:g,markdown:p,maskedKinds:[...s],math:h,rotated:0};let _=Wa(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,N=st(_,$);try{Rx(N,{mode:448}),g.id=$,v=N;break}catch(A){if(A.code!=="EEXIST")throw new $n(`cannot create a handoff folder in ${_t(_,e)} (${A.code??"error"})`)}}if(!v)throw new $n(`too many handoffs saved in the same second in ${_t(_,e)}`);try{Tx(st(v,"handoff.md"),p,{mode:384,flag:"wx"}),Tx(st(v,"meta.json"),JSON.stringify(g,null,2)+`
103
- `,{mode:384,flag:"wx"})}catch(x){throw new $n(`cannot write the handoff in ${_t(v,e)} (${x.code??"error"})`)}let y=KO(e,vt.kept,g.id);if(!RO(st(v,"handoff.md")))throw new $n(`the handoff in ${_t(v,e)} is gone`);return{meta:g,markdown:p,dir:v,maskedKinds:[...s],math:h,rotated:y}}function _t(t,e=vo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Ox(t,e=vo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as GO}from"node:dns";import{request as XO}from"node:http";import{request as YO}from"node:https";import{isIP as Mx}from"node:net";import{mkdtempSync as QO,rmSync as eN,writeFileSync as tN}from"node:fs";import{tmpdir as rN}from"node:os";import{extname as nN,join as Nx}from"node:path";var Ke={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},oN={"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 jx(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function Pp(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 sN(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"").replace(/%.*$/,""),r=e.match(/(\d+\.\d+\.\d+\.\d+)$/);if(r){let[u,l,d,m]=r[1].split(".").map(Number);e=e.slice(0,-r[1].length)+`${(u<<8|l).toString(16)}:${(d<<8|m).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 Zx(t){let e=t.replace(/^\[|\]$/g,""),r=Mx(e);if(r===4)return Pp(e);if(r===6){let n=sN(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:Pp(`${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?Pp(`${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 Ip(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function iN(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=jx(e)&&Ip(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"}:Mx(n)&&Zx(n)?{error:"a private or loopback address"}:{url:r}}function aN(t){return(e,r,n)=>{GO(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>Zx(u.address)&&!(t&&Ip(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 cN(t,e,r,n){return new Promise(o=>{let s=jx(e)&&Ip(t.hostname),i=t.protocol==="https:"?YO:XO,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-ut()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:aN(s),timeout:u,headers:{accept:"*/*","user-agent":"context-doctor"}},m=>{let p=m.statusCode??0;if(p>=300&&p<400)return m.resume(),c({status:p,location:typeof m.headers.location=="string"?m.headers.location:void 0});if(p!==200)return m.resume(),c({status:p,error:`HTTP ${p}`});let f=n<Ke.bytes?`over the ${Ke.totalBytes/1024/1024} MB total for one call`:`too large (over ${Ke.bytes/1024/1024} MB)`,g=Number(m.headers["content-length"]);if(Number.isFinite(g)&&g>n)return d.destroy(),c({status:p,error:f});let h=[],_=0;m.on("data",v=>{if(_+=v.length,_>n){d.destroy(),c({status:p,error:f});return}h.push(v)}),m.on("end",()=>c({status:p,body:Buffer.concat(h)})),m.on("error",v=>c({status:p,error:v.message}))});d.on("timeout",()=>{d.destroy(),c({status:0,error:"timed out"})}),d.on("error",m=>c({status:0,error:m.code==="EPRIVATE"?"refused: the host resolves to a private address":m.message})),d.end()})}async function uN(t,e=process.env,{deadline:r,maxBytes:n=Ke.bytes}={}){let o=Math.min(ut()+Ke.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Ke.bytes)),i=t;for(let a=0;a<=Ke.redirects;a++){let c=iN(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(ut()>=o)return{error:"timed out"};let u=await cN(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 ${Ke.redirects} redirects`}}function lN(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function Dx(t,e=process.env){let r=[],n=[],o=0,s=ut()+Ke.callMs;for(let i of t.slice(0,Ke.files)){let a=lN(i);if(ut()>=s){n.push(`${a}: not read, the ${Ke.callMs/1e3} s allowed for one call ran out`);continue}let c=await uN(String(i.download_url??""),e,{deadline:s,maxBytes:Ke.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=nN(a).toLowerCase(),l=La.has(u)?u:oN[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=QO(Nx(rN(),"cd-file-"));try{let m=Nx(d,`upload${l}`);tN(m,c.body,{mode:384});let p=await qa(m,Math.min(ut()+Is,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{eN(d,{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>Ke.files&&n.push(`${t.length-Ke.files} more file(s): at most ${Ke.files} per call`),{sources:r,skipped:n}}var Lx={bodyBytes:10485760,bodyMs:3e4},dN=["https://chatgpt.com","https://chat.openai.com"],qx=["localhost","127.0.0.1","::1"];function Ga(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function Xa(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 Fx(t,e,r,n=process.env){let o=[...Ga(e),...Ga(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],s=new Set([...dN,...Ga(r),...Ga(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(c=>c.toLowerCase().replace(/\/+$/,"")));if(o.includes("*"))return{hosts:"*",origins:s};let i=Xa(t),a=new Set([...qx,...o.map(Xa)]);return i&&i!=="0.0.0.0"&&i!=="::"&&a.add(i),{hosts:a,origins:s}}function Ux(t,e){if(t.hosts!=="*"){let n=Xa(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=Xa(o.host);if(!(qx.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 Hx(t,e=Lx.bodyBytes,r=Lx.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=d=>{clearTimeout(s),n(d)},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=[],l=0;t.on("data",d=>{if(!o){if(l+=d.length,l>e)return o=!0,u.length=0,t.resume(),i(a);u.push(d)}}),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"}))})})}import{closeSync as _N,existsSync as Ya,openSync as vN,readdirSync as Qa,readSync as xN,statSync as Op}from"node:fs";import{homedir as Np}from"node:os";import{basename as Gx,dirname as bN,isAbsolute as wN,join as kn,resolve as Xx}from"node:path";import{readdirSync as oF,readFileSync as sF,statSync as iF,existsSync as aF,openSync as fN,readSync as pN,closeSync as mN}from"node:fs";import{StringDecoder as hN}from"node:string_decoder";import{homedir as gN}from"node:os";import{join as yN}from"node:path";function Bx(t,e=gN()){return yN(Nr(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function Cp(t,e){let r=fN(t,"r"),n=new hN("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=pN(r,o,0,o.length,null);if(i===0)break;s+=n.write(o.subarray(0,i));let a;for(;(a=s.indexOf(`
104
- `))!==-1;)e(s.slice(0,a)),s=s.slice(a+1)}s+=n.end(),s&&e(s)}finally{mN(r)}}var Cs=2e5,$N=8e6,Vx=16384;function Ap(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:e?.type==="image"||e?.type==="input_image"?"[image]":"").filter(Boolean).join(`
105
- `):""}function kN(t){if(t.length<=Cs)return{whole:t};let e=Cs/2;return{head:t.slice(0,e+Vx),tail:t.slice(-(e+Vx)),length:t.length}}var Jx=t=>"whole"in t?t.whole.length:Cs;function SN(t){if("whole"in t){let a=Mr(ar(t.whole));return{text:a.text,masked:a.count}}let e=Cs/2,r=Mr(ar(t.head)),n=ar(t.tail),o=0,s=/-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.exec(n);s&&!/-----BEGIN [A-Z0-9 ]*PRIVATE KEY/.test(n.slice(0,s.index))&&(n=`[private key masked by context-doctor]${n.slice(s.index+s[0].length)}`,o=1);let i=Mr(n);return{text:`${r.text.slice(0,e)}
106
- [\u2026 ${t.length-Cs} characters \u2026]
107
- ${i.text.slice(-e)}`,masked:r.count+i.count+o}}function Wx(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function TN(t,e=$N){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=kN(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=Jx(h);o>e&&n<r.length-1;)o-=Jx(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};Cp(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,Ap(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",Wx(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,Ap(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,Ap(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",Wx(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=SN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function EN(t){try{let e=vN(t,"r");try{let r=Buffer.alloc(65536),n=xN(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
108
- `)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{_N(e)}}catch{return}}function Kx(t){let e;try{for(let r of Qa(t)){if(!r.endsWith(".jsonl"))continue;let n=kn(t,r),o=Op(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function zN(t,e){let r=kn(go(e),"sessions");if(!Ya(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=Qa(i)}catch{return}for(let u of c){let l=kn(i,u),d;try{d=Op(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>EN(i.path)===Xx(t))}function Yx(t=process.env,e=process.cwd(),r=Np(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=RN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=Kx(bN(a));if(c&&c.path!==a&&c.at>Op(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${Gx(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=Kx(Bx(e,r)),i=zN(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function RN(t,e=Np()){if((wN(t)||t.includes("/")||t.includes("\\"))&&Ya(t))return Xx(t);if(!/^[\w.-]+$/.test(t))return;let r=kn(Nr(e),"projects"),n=[];try{n=Qa(r)}catch{}for(let a of n){let c=kn(r,a,`${t}.jsonl`);if(Ya(c))return c}let o=kn(go(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=Qa(a)}catch{return}for(let l of u){let d=kn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return Ya(o)&&i(o,0),s}function Qx(t,e,r={}){let n=TN(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=hx(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function eb(t,e=Np()){let r=Gx(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${R(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
99
+ `}function tN(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)*bp(e.model),r.nowSource="turns");let n=go(e.model);return n&&(r.afterUsd=jr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=jr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function Fx(t){let e=(o,s)=>o!==void 0?` (${Kt(o)} at list price, ${Kt(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${R(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: ~${R(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${R(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${R(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
100
+ `)}function Ga(t,e){let r=UO(t,e);return r===""||r!==".."&&!r.startsWith(".."+FO)&&!qO(r)}var En=class extends Error{};function Xa(t,e){let r=i=>{if(e)throw new En(i)},n;try{n=Ka(t)}catch{return r("the home directory cannot be read")}let o=it(t,".context-doctor"),s=Cp(t);for(let i of[o,s]){let a;try{a=dr(i)}catch{if(!e)return;try{Lx(i,{mode:448}),a=dr(i)}catch(u){return r(`cannot create ${xt(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${xt(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${xt(i,t)} is not a folder`);let c;try{c=Ka(i)}catch{return r(`${xt(i,t)} cannot be read`)}if(!Ga(n,c))return r(`${xt(i,t)} resolves outside the home directory`)}return s}function Dx(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function rN(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>Dx(n,t)-Dx(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var nN=0;function Ya(t=wo()){let e=Xa(t,!1);if(!e)return[];let r;try{r=DO(e)}catch{return[]}let n=[];for(let o of r){if(!qx(o))continue;let s=it(e,o);try{if(!dr(s).isDirectory())continue;let i=it(s,"meta.json");if(!dr(i).isFile())continue;let a=JSON.parse(Pp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(rN(Date.now()))}function Op(t,e=wo()){let r=t==="latest"?Ya(e)[0]?.id:t;if(!qx(r))return;let n=Xa(e,!1);if(!n)return;let o=it(n,r),s=it(o,"handoff.md");if(Ga(n,s))try{let i=dr(s);if(!i.isFile()||i.size>bt.readBytes||!dr(o).isDirectory()||!dr(it(o,"meta.json")).isFile())return;let a=JSON.parse(Pp(it(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:Pp(s,"utf8")}}catch{return}}function oN(t,e,r){let n=Xa(t,!1);if(!n)return 0;let o=Ya(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=it(n,i.id);try{if(!Ga(n,a)||!dr(a).isDirectory()||!dr(it(a,"meta.json")).isFile()||!Ga(Ka(n),Ka(a)))continue;LO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function lr(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 Hx(t,{home:e=wo(),now:r=new Date,store:n=!0}={}){let o=Ap(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Zr(x);return i+=$.count,$.kinds.forEach(N=>s.add(N)),$.text},c=a(lr(t.brief)),u=Ip(t.title?.trim()?a(lr(t.title,{keepNewlines:!1})):c.split(`
102
+ `).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",bt.titleChars),l=(t.verbatim??[]).map(x=>({label:Ip(a(lr(x.label,{keepNewlines:!1})),bt.labelChars),text:a(lr(x.text))})),d=t.model===void 0?void 0:a(lr(String(t.model),{keepNewlines:!1})).slice(0,bt.modelChars)||void 0,m=r.toISOString(),p=eN(u,m,c,l),f=`${VO(r)}-${BO(u)}`,g={id:f,title:u,created:m,model:d,tokens:At(p,d),briefTokens:At(c,d),blocks:l.map(x=>({label:x.label,tokens:At(x.text,d)})),masked:i,order:Date.now()*1e3+nN++%1e3},h=tN(g.tokens,{...t,model:d});if(!n)return{meta:g,markdown:p,maskedKinds:[...s],math:h,rotated:0};let _=Xa(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,N=it(_,$);try{Lx(N,{mode:448}),g.id=$,v=N;break}catch(A){if(A.code!=="EEXIST")throw new En(`cannot create a handoff folder in ${xt(_,e)} (${A.code??"error"})`)}}if(!v)throw new En(`too many handoffs saved in the same second in ${xt(_,e)}`);try{jx(it(v,"handoff.md"),p,{mode:384,flag:"wx"}),jx(it(v,"meta.json"),JSON.stringify(g,null,2)+`
103
+ `,{mode:384,flag:"wx"})}catch(x){throw new En(`cannot write the handoff in ${xt(v,e)} (${x.code??"error"})`)}let y=oN(e,bt.kept,g.id);if(!ZO(it(v,"handoff.md")))throw new En(`the handoff in ${xt(v,e)} is gone`);return{meta:g,markdown:p,dir:v,maskedKinds:[...s],math:h,rotated:y}}function xt(t,e=wo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Bx(t,e=wo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as sN}from"node:dns";import{request as iN}from"node:http";import{request as aN}from"node:https";import{isIP as Jx}from"node:net";import{mkdtempSync as cN,rmSync as uN,writeFileSync as lN}from"node:fs";import{tmpdir as dN}from"node:os";import{extname as fN,join as Vx}from"node:path";var Ge={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},pN={"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 Wx(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function Np(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 mN(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"").replace(/%.*$/,""),r=e.match(/(\d+\.\d+\.\d+\.\d+)$/);if(r){let[u,l,d,m]=r[1].split(".").map(Number);e=e.slice(0,-r[1].length)+`${(u<<8|l).toString(16)}:${(d<<8|m).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 Kx(t){let e=t.replace(/^\[|\]$/g,""),r=Jx(e);if(r===4)return Np(e);if(r===6){let n=mN(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:Np(`${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?Np(`${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 Mp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function hN(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=Wx(e)&&Mp(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"}:Jx(n)&&Kx(n)?{error:"a private or loopback address"}:{url:r}}function gN(t){return(e,r,n)=>{sN(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>Kx(u.address)&&!(t&&Mp(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 yN(t,e,r,n){return new Promise(o=>{let s=Wx(e)&&Mp(t.hostname),i=t.protocol==="https:"?aN:iN,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-lt()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:gN(s),timeout:u,headers:{accept:"*/*","user-agent":"context-doctor"}},m=>{let p=m.statusCode??0;if(p>=300&&p<400)return m.resume(),c({status:p,location:typeof m.headers.location=="string"?m.headers.location:void 0});if(p!==200)return m.resume(),c({status:p,error:`HTTP ${p}`});let f=n<Ge.bytes?`over the ${Ge.totalBytes/1024/1024} MB total for one call`:`too large (over ${Ge.bytes/1024/1024} MB)`,g=Number(m.headers["content-length"]);if(Number.isFinite(g)&&g>n)return d.destroy(),c({status:p,error:f});let h=[],_=0;m.on("data",v=>{if(_+=v.length,_>n){d.destroy(),c({status:p,error:f});return}h.push(v)}),m.on("end",()=>c({status:p,body:Buffer.concat(h)})),m.on("error",v=>c({status:p,error:v.message}))});d.on("timeout",()=>{d.destroy(),c({status:0,error:"timed out"})}),d.on("error",m=>c({status:0,error:m.code==="EPRIVATE"?"refused: the host resolves to a private address":m.message})),d.end()})}async function _N(t,e=process.env,{deadline:r,maxBytes:n=Ge.bytes}={}){let o=Math.min(lt()+Ge.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Ge.bytes)),i=t;for(let a=0;a<=Ge.redirects;a++){let c=hN(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(lt()>=o)return{error:"timed out"};let u=await yN(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 ${Ge.redirects} redirects`}}function vN(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function Gx(t,e=process.env){let r=[],n=[],o=0,s=lt()+Ge.callMs;for(let i of t.slice(0,Ge.files)){let a=vN(i);if(lt()>=s){n.push(`${a}: not read, the ${Ge.callMs/1e3} s allowed for one call ran out`);continue}let c=await _N(String(i.download_url??""),e,{deadline:s,maxBytes:Ge.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=fN(a).toLowerCase(),l=Fa.has(u)?u:pN[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=cN(Vx(dN(),"cd-file-"));try{let m=Vx(d,`upload${l}`);lN(m,c.body,{mode:384});let p=await Ha(m,Math.min(lt()+Os,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{uN(d,{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>Ge.files&&n.push(`${t.length-Ge.files} more file(s): at most ${Ge.files} per call`),{sources:r,skipped:n}}import{isIP as xN}from"node:net";var Xx={bodyBytes:10*1024*1024,bodyMs:3e4},bN=["https://chatgpt.com","https://chat.openai.com"],Yx=["localhost","127.0.0.1","::1"];function Qa(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function ec(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 Qx(t,e,r,n=process.env,o={}){let s=[...Qa(e),...Qa(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],i=new Set([...bN,...Qa(r),...Qa(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(u=>u.toLowerCase().replace(/\/+$/,"")));if(s.includes("*"))return{hosts:"*",origins:i,ipLiterals:o.ipLiterals};let a=ec(t),c=new Set([...Yx,...s.map(ec)]);return a&&a!=="0.0.0.0"&&a!=="::"&&c.add(a),{hosts:c,origins:i,ipLiterals:o.ipLiterals}}function eb(t,e){if(t.hosts!=="*"){let n=ec(String(e.host??""));if(!n)return"the request has no Host header";if(!t.hosts.has(n)&&!(t.ipLiterals&&xN(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=ec(o.host);if(!(Yx.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 tb(t,e=Xx.bodyBytes,r=Xx.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=d=>{clearTimeout(s),n(d)},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=[],l=0;t.on("data",d=>{if(!o){if(l+=d.length,l>e)return o=!0,u.length=0,t.resume(),i(a);u.push(d)}}),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"}))})})}import{closeSync as zN,existsSync as tc,openSync as RN,readdirSync as rc,readSync as PN,statSync as Dp}from"node:fs";import{homedir as Lp}from"node:os";import{basename as ab,dirname as IN,isAbsolute as CN,join as zn,resolve as cb}from"node:path";import{readdirSync as yU,readFileSync as _U,statSync as vU,existsSync as xU,openSync as wN,readSync as $N,closeSync as kN}from"node:fs";import{StringDecoder as SN}from"node:string_decoder";import{homedir as TN}from"node:os";import{join as EN}from"node:path";function rb(t,e=TN()){return EN(ur(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function jp(t,e){let r=wN(t,"r"),n=new SN("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=$N(r,o,0,o.length,null);if(i===0)break;s+=n.write(o.subarray(0,i));let a;for(;(a=s.indexOf(`
104
+ `))!==-1;)e(s.slice(0,a)),s=s.slice(a+1)}s+=n.end(),s&&e(s)}finally{kN(r)}}var Ns=2e5,AN=8e6,nb=16384;function Zp(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:e?.type==="image"||e?.type==="input_image"?"[image]":"").filter(Boolean).join(`
105
+ `):""}function ON(t){if(t.length<=Ns)return{whole:t};let e=Ns/2;return{head:t.slice(0,e+nb),tail:t.slice(-(e+nb)),length:t.length}}var ob=t=>"whole"in t?t.whole.length:Ns;function NN(t){if("whole"in t){let a=Zr(lr(t.whole));return{text:a.text,masked:a.count}}let e=Ns/2,r=Zr(lr(t.head)),n=lr(t.tail),o=0,s=/-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.exec(n);s&&!/-----BEGIN [A-Z0-9 ]*PRIVATE KEY/.test(n.slice(0,s.index))&&(n=`[private key masked by context-doctor]${n.slice(s.index+s[0].length)}`,o=1);let i=Zr(n);return{text:`${r.text.slice(0,e)}
106
+ [\u2026 ${t.length-Ns} characters \u2026]
107
+ ${i.text.slice(-e)}`,masked:r.count+i.count+o}}function sb(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function MN(t,e=AN){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=ON(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=ob(h);o>e&&n<r.length-1;)o-=ob(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};jp(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,Zp(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",sb(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,Zp(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,Zp(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",sb(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=NN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function jN(t){try{let e=RN(t,"r");try{let r=Buffer.alloc(65536),n=PN(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
108
+ `)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{zN(e)}}catch{return}}function ib(t){let e;try{for(let r of rc(t)){if(!r.endsWith(".jsonl"))continue;let n=zn(t,r),o=Dp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function ZN(t,e){let r=zn(Sn(e),"sessions");if(!tc(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=rc(i)}catch{return}for(let u of c){let l=zn(i,u),d;try{d=Dp(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>jN(i.path)===cb(t))}function ub(t=process.env,e=process.cwd(),r=Lp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=DN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=ib(IN(a));if(c&&c.path!==a&&c.at>Dp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${ab(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=ib(rb(e,r)),i=ZN(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function DN(t,e=Lp()){if((CN(t)||t.includes("/")||t.includes("\\"))&&tc(t))return cb(t);if(!/^[\w.-]+$/.test(t))return;let r=zn(ur(e),"projects"),n=[];try{n=rc(r)}catch{}for(let a of n){let c=zn(r,a,`${t}.jsonl`);if(tc(c))return c}let o=zn(Sn(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=rc(a)}catch{return}for(let l of u){let d=zn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return tc(o)&&i(o,0),s}function lb(t,e,r={}){let n=MN(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=Sx(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function db(t,e=Lp()){let r=ab(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${R(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
109
109
  `);n.push(`Best ${t.hits.length} excerpt${t.hits.length===1?"":"s"} for "${t.query}", best first${t.more?` (${t.more} more matched; a narrower query or a larger max_tokens gets them)`:""}:`),t.masked&&n.push(`${t.masked} secret-looking string${t.masked===1?"":"s"} masked.`),t.leftOut&&n.push(`The oldest ${t.leftOut} entries were not searched: the transcript is that large.`);for(let o of t.hits){let s=o.at?o.at.slice(0,16).replace("T"," ")+" UTC":"time not recorded";n.push("",`\u2500\u2500 entry ${o.n} of ${t.entries} \xB7 ${s} \xB7 ${o.kind} \xB7 ${o.where} \xB7 ~${R(o.tokens)}`,o.text)}return n.join(`
110
- `).replaceAll(e,"~")}var kM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],SM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Qp(t,e,r){if(wx(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 Hb(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 C&&n.code===O.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 Bb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new Pa({name:"context-doctor",version:"0.44.0"},{instructions:bx,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. 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:D.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:D.object({turns:D.number().int().nonnegative().describe("Exchanges so far"),model:D.string().optional(),blocks:D.array(D.object({turn:D.number().int().positive(),kind:D.enum(["paste","code","tool_result","image","base64","text"]),label:D.string().describe("Short name"),approx_tokens:D.number().optional(),approx_lines:D.number().optional(),approx_words:D.number().optional(),approx_chars:D.number().optional(),repeated:D.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:D.boolean().optional().describe("Acted on, no longer needed")})).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 for logs."),model:D.string().optional().describe("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){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(SM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. 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":"",f=Fv({...a,model:a.model??c},{record:!t}),g=p+qv(f);return Qp(u?._meta,g,()=>{let h=kx(f,g);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 l=Cv(_v(i),c),d=Zv(l);return Qp(u?._meta,d,()=>$x(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:D.string().describe("Conversation JSON"),strategies:D.array(D.enum(kM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:D.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:D.number().int().positive().optional().describe("Per trimmed 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 l="";if(a?.includes("prune-history")){let _=await Hb(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"),l=`
111
- prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=Mv(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&ja({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${R(m)} tokens (${R(d.tokensBefore)} \u2192 ${R(d.tokensAfter)}) via ${d.applied.length} change(s):
110
+ `).replaceAll(e,"~")}var OM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],NM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function om(t,e,r){if(Ax(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 tw(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 C&&n.code===O.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 rw({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new Aa({name:"context-doctor",version:"0.45.0"},{instructions:Cx,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. 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:D.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:D.object({turns:D.number().int().nonnegative().describe("Exchanges so far"),model:D.string().optional(),blocks:D.array(D.object({turn:D.number().int().positive(),kind:D.enum(["paste","code","tool_result","image","base64","text"]),label:D.string().describe("Short name"),approx_tokens:D.number().optional(),approx_lines:D.number().optional(),approx_words:D.number().optional(),approx_chars:D.number().optional(),repeated:D.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:D.boolean().optional().describe("Acted on, no longer needed")})).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 for logs."),model:D.string().optional().describe("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){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(NM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. 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":"",f=Kv({...a,model:a.model??c},{record:!t}),g=p+Wv(f);return om(u?._meta,g,()=>{let h=Nx(f,g);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 l=Dv($v(i),c),d=Bv(l);return om(u?._meta,d,()=>Ox(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:D.string().describe("Conversation JSON"),strategies:D.array(D.enum(OM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:D.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:D.number().int().positive().optional().describe("Per trimmed 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 l="";if(a?.includes("prune-history")){let _=await tw(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"),l=`
111
+ prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=Fv(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&La({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${R(m)} tokens (${R(d.tokensBefore)} \u2192 ${R(d.tokensAfter)}) via ${d.applied.length} change(s):
112
112
  `+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${R(_.tokensSaved)})`).join(`
113
113
  `)+l,f=1e5,g=JSON.stringify(d.conversation),h=[{type:"text",text:p},g.length<=f?{type:"text",text:g}:{type:"text",text:`[optimized conversation is ${g.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 d.prunedDigest&&h.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.
114
114
 
115
115
  PRUNED TURNS DIGEST:
116
- `+d.prunedDigest}),{content:h}});let o=D.object({download_url:D.string(),file_id:D.string(),mime_type:D.string().optional(),file_name:D.string().optional()}).strict(),s={...t?{}:{paths:D.array(D.string()).optional().describe("Files or folders, absolute paths")},text:D.string().optional().describe("Raw text to pack instead of files"),query:D.string().optional().describe("The question; omit for an outline"),max_tokens:D.number().int().positive().optional().describe("Budget, default 4000"),ids:D.array(D.string()).optional().describe("Chunk ids, e.g. docs/guide.md#4"),model:D.string().optional().describe("Model to count for"),...t?{files:D.array(o).optional().describe("Files the user uploaded")}:{semantic:D.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: the chunks that best match `query` within `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:l,max_tokens:d,ids:m,model:p,semantic:f,files:g}=i,h=N=>({content:[{type:"text",text:N}],isError:!0});if((c?.length??0)>50)return h(`${c.length} paths; pass at most 50 (a folder counts as one).`);if((m?.length??0)>200)return h(`${m.length} ids; ask for at most 200.`);if(d!==void 0&&d>2e5)return h(`max_tokens ${d}; the most is 200000.`);if(c?.length&&!r)return h("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 xx(c):{sources:[],skipped:[]};if(t&&g?.length){let N=await Dx(g);_.push(...N.sources),v.push(...N.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return h(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 gx(_,{query:l,budget:d,ids:m,model:p,semantic:t?void 0:f}),x=v.length?`
117
- Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=_x(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:Qp(a?._meta,$,()=>{let N=Sx(y,$);return{...N,text:N.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:D.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 ${vt.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:D.string().max(1e3).describe("Absolute path to the file or folder"),question:D.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}
116
+ `+d.prunedDigest}),{content:h}});let o=D.object({download_url:D.string(),file_id:D.string(),mime_type:D.string().optional(),file_name:D.string().optional()}).strict(),s={...t?{}:{paths:D.array(D.string()).optional().describe("Files or folders, absolute paths")},text:D.string().optional().describe("Raw text to pack instead of files"),query:D.string().optional().describe("The question; omit for an outline"),max_tokens:D.number().int().positive().optional().describe("Budget, default 4000"),ids:D.array(D.string()).optional().describe("Chunk ids, e.g. docs/guide.md#4"),model:D.string().optional().describe("Model to count for"),...t?{files:D.array(o).optional().describe("Files the user uploaded")}:{semantic:D.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: the chunks that best match `query` within `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:l,max_tokens:d,ids:m,model:p,semantic:f,files:g}=i,h=N=>({content:[{type:"text",text:N}],isError:!0});if((c?.length??0)>50)return h(`${c.length} paths; pass at most 50 (a folder counts as one).`);if((m?.length??0)>200)return h(`${m.length} ids; ask for at most 200.`);if(d!==void 0&&d>2e5)return h(`max_tokens ${d}; the most is 200000.`);if(c?.length&&!r)return h("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 Ix(c):{sources:[],skipped:[]};if(t&&g?.length){let N=await Gx(g);_.push(...N.sources),v.push(...N.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return h(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 Tx(_,{query:l,budget:d,ids:m,model:p,semantic:t?void 0:f}),x=v.length?`
117
+ Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=zx(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:om(a?._meta,$,()=>{let N=Mx(y,$);return{...N,text:N.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:D.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 ${bt.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:D.string().max(1e3).describe("Absolute path to the file or folder"),question:D.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}
118
118
 
119
- 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${vt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:D.string(),verbatim:D.array(D.object({label:D.string(),text:D.string()})).optional().describe("Code, config, figures"),title:D.string().optional(),chat_tokens:D.number().optional().describe("Chat size, from profile_context"),turns:D.number().optional(),model:D.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:l,model:d})=>{let m={brief:i,verbatim:a,title:c,model:d,chatTokens:u,turns:l},p=zp(m);if(p.length)return{isError:!0,content:[{type:"text",text:`Not saved: ${p.join(" ")}`}]};let f=a;if(e){let y=a?.length??0,x=await Hb(n,`Save a handoff of this chat on this computer (${_t(Ep())}) to start a new chat from? "${Mr(c??i.split(`
120
- `)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Mr(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 g;try{g=Ax({...m,verbatim:f},{store:e})}catch(y){let x=Ox(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let h=g.meta,_=`brief ~${R(h.briefTokens)}${h.blocks.length?`, ${h.blocks.length} verbatim block(s) ~${R(h.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[g.dir?`Handoff saved: ${h.id} (~${R(h.tokens)} tokens: ${_}) in ${_t(g.dir)}.`:`Handoff ready (~${R(h.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return h.masked>0&&v.push(`Masked ${h.masked} secret-looking string(s) (${g.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),h.briefTokens>vt.briefTargetTokens&&v.push(`The brief is ~${h.briefTokens} tokens; the target is \u2264${vt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(Cx(g.math)),g.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(`
121
- `)}]}}),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:Rp("latest")?.markdown??i}]})),n.registerResource("handoff",new Ia("handoff://{id}",{list:async()=>({resources:Ka().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${R(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=Rp(String(Array.isArray(c)?c[0]:c));if(!u)throw new C(O.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 r&&n.registerTool("recall",{description:"Search this session's transcript on disk (compacted turns, cleared tool output) for `query`: best excerpts with time and position. Use before asking the user again.",inputSchema:{query:D.string(),max_tokens:D.number().optional()},annotations:{title:"Recall",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({query:i,max_tokens:a})=>{let c=Yx(process.env,process.cwd(),void 0,{envMayBeStale:!0});if(!c)return{isError:!0,content:[{type:"text",text:"No transcript of this session on disk (Claude Code and Codex keep one; chat apps do not)."}]};let u=Math.min(2e4,Math.max(200,Math.floor(Number(a)||2e3))),l=Qx(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:eb(l)}]}}),n.tool("context_best_practices","Checklist for keeping context lean and prompts cacheable, optionally per provider.",{provider:D.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:[...Vb.general,...i&&i!=="general"?Vb[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
122
- `)}]})),TM(n),n}function TM(t){let e=t.server._requestHandlers,r=e?.get("tools/list");!e||!r||e.set("tools/list",async(n,o)=>{let s=await r(n,o);for(let i of s?.tools??[])i.inputSchema&&delete i.inputSchema.$schema;return s})}var Vb={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 EM(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 cc=process.argv.slice(2);if(cc.includes("--http")){let t=a=>{let c=cc.indexOf(a);return c>=0?cc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=cc.includes("--store-handoffs"),o=Fx(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(Ub(),Fb));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 l=(_,v,y)=>{let x=()=>{c.writableEnded||(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())};if(_===413&&a.headers["content-length"]===void 0&&!a.complete){a.resume();let $=setTimeout(x,5e3);$.unref(),a.once("end",()=>{clearTimeout($),x()}),a.once("error",()=>{clearTimeout($),x()});return}x()},d=Ux(o,a.headers);if(d)return l(403,-32e3,`Forbidden: ${d}.`);if(a.method!=="POST"){c.statusCode=405,c.setHeader("allow","POST"),c.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let m=await Hx(a);if(!("value"in m))return l(m.status,m.code,m.message);let p=String(a.headers.accept??""),f=p.includes("text/event-stream");(!f||!p.includes("application/json"))&&EM(a,"accept","application/json, text/event-stream");let g=Bb({http:!0,storeHandoffs:n}),h=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{h.close(),g.close()}),await g.connect(h),await h.handleRequest(a,c,m.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 Aa;await Bb().connect(t)}
119
+ 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${bt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:D.string(),verbatim:D.array(D.object({label:D.string(),text:D.string()})).optional().describe("Code, config, figures"),title:D.string().optional(),chat_tokens:D.number().optional().describe("Chat size, from profile_context"),turns:D.number().optional(),model:D.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:l,model:d})=>{let m={brief:i,verbatim:a,title:c,model:d,chatTokens:u,turns:l},p=Ap(m);if(p.length)return{isError:!0,content:[{type:"text",text:`Not saved: ${p.join(" ")}`}]};let f=a;if(e){let y=a?.length??0,x=await tw(n,`Save a handoff of this chat on this computer (${xt(Cp())}) to start a new chat from? "${Zr(c??i.split(`
120
+ `)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Zr(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 g;try{g=Hx({...m,verbatim:f},{store:e})}catch(y){let x=Bx(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let h=g.meta,_=`brief ~${R(h.briefTokens)}${h.blocks.length?`, ${h.blocks.length} verbatim block(s) ~${R(h.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[g.dir?`Handoff saved: ${h.id} (~${R(h.tokens)} tokens: ${_}) in ${xt(g.dir)}.`:`Handoff ready (~${R(h.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return h.masked>0&&v.push(`Masked ${h.masked} secret-looking string(s) (${g.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),h.briefTokens>bt.briefTargetTokens&&v.push(`The brief is ~${h.briefTokens} tokens; the target is \u2264${bt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(Fx(g.math)),g.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(`
121
+ `)}]}}),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:Op("latest")?.markdown??i}]})),n.registerResource("handoff",new Oa("handoff://{id}",{list:async()=>({resources:Ya().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${R(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=Op(String(Array.isArray(c)?c[0]:c));if(!u)throw new C(O.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 r&&n.registerTool("recall",{description:"Search this session's transcript on disk (compacted turns, cleared tool output) for `query`: best excerpts with time and position. Use before asking the user again.",inputSchema:{query:D.string(),max_tokens:D.number().optional()},annotations:{title:"Recall",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({query:i,max_tokens:a})=>{let c=ub(process.env,process.cwd(),void 0,{envMayBeStale:!0});if(!c)return{isError:!0,content:[{type:"text",text:"No transcript of this session on disk (Claude Code and Codex keep one; chat apps do not)."}]};let u=Math.min(2e4,Math.max(200,Math.floor(Number(a)||2e3))),l=lb(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:db(l)}]}}),n.tool("context_best_practices","Checklist for keeping context lean and prompts cacheable, optionally per provider.",{provider:D.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:[...nw.general,...i&&i!=="general"?nw[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
122
+ `)}]})),MM(n),n}function MM(t){let e=t.server._requestHandlers,r=e?.get("tools/list");!e||!r||e.set("tools/list",async(n,o)=>{let s=await r(n,o);for(let i of s?.tools??[])i.inputSchema&&delete i.inputSchema.$schema;return s})}var nw={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 jM(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 dc=process.argv.slice(2);if(dc.includes("--http")){let t=a=>{let c=dc.indexOf(a);return c>=0?dc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=dc.includes("--store-handoffs"),o=Qx(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(ew(),Qb));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 l=(_,v,y)=>{let x=()=>{c.writableEnded||(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())};if(_===413&&a.headers["content-length"]===void 0&&!a.complete){a.resume();let $=setTimeout(x,5e3);$.unref(),a.once("end",()=>{clearTimeout($),x()}),a.once("error",()=>{clearTimeout($),x()});return}x()},d=eb(o,a.headers);if(d)return l(403,-32e3,`Forbidden: ${d}.`);if(a.method!=="POST"){c.statusCode=405,c.setHeader("allow","POST"),c.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let m=await tb(a);if(!("value"in m))return l(m.status,m.code,m.message);let p=String(a.headers.accept??""),f=p.includes("text/event-stream");(!f||!p.includes("application/json"))&&jM(a,"accept","application/json, text/event-stream");let g=rw({http:!0,storeHandoffs:n}),h=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{h.close(),g.close()}),await g.connect(h),await h.handleRequest(a,c,m.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 Ma;await rw().connect(t)}