context-doctor 0.42.0 → 0.44.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.
Files changed (48) hide show
  1. package/README.md +6 -3
  2. package/dist/budget.d.ts +52 -0
  3. package/dist/budget.js +209 -59
  4. package/dist/cachettl.d.ts +5 -1
  5. package/dist/cachettl.js +10 -25
  6. package/dist/cli.js +33 -15
  7. package/dist/codexcompact.d.ts +137 -0
  8. package/dist/codexcompact.js +581 -0
  9. package/dist/compactwindow.js +2 -2
  10. package/dist/cursor.d.ts +10 -0
  11. package/dist/cursor.js +20 -0
  12. package/dist/doctor.d.ts +9 -0
  13. package/dist/doctor.js +55 -0
  14. package/dist/fanout.js +4 -2
  15. package/dist/fix.d.ts +38 -4
  16. package/dist/fix.js +249 -21
  17. package/dist/hook.js +65 -16
  18. package/dist/install.js +56 -19
  19. package/dist/ledger.d.ts +2 -1
  20. package/dist/ledger.js +1 -0
  21. package/dist/limits.d.ts +6 -2
  22. package/dist/limits.js +19 -16
  23. package/dist/mcp.js +63 -63
  24. package/dist/mcpclient.js +19 -19
  25. package/dist/mcpschema.js +5 -9
  26. package/dist/overhead.d.ts +7 -2
  27. package/dist/overhead.js +11 -3
  28. package/dist/pack.js +23 -3
  29. package/dist/pricing.d.ts +25 -5
  30. package/dist/pricing.js +157 -48
  31. package/dist/proxy.d.ts +15 -1
  32. package/dist/proxy.js +33 -5
  33. package/dist/prune.d.ts +8 -0
  34. package/dist/prune.js +20 -9
  35. package/dist/savings.js +2 -1
  36. package/dist/sessionprice.d.ts +77 -0
  37. package/dist/sessionprice.js +267 -0
  38. package/dist/settingsedit.js +3 -2
  39. package/dist/spend.d.ts +25 -3
  40. package/dist/spend.js +67 -19
  41. package/dist/subagentmodel.js +11 -1
  42. package/dist/subagentpay.d.ts +17 -0
  43. package/dist/subagentpay.js +41 -2
  44. package/dist/subagents.d.ts +24 -0
  45. package/dist/subagents.js +82 -17
  46. package/dist/tooloutput.d.ts +120 -0
  47. package/dist/tooloutput.js +357 -0
  48. package/package.json +1 -1
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 Pb=Object.create;var nc=Object.defineProperty;var Ib=Object.getOwnPropertyDescriptor;var Cb=Object.getOwnPropertyNames;var Ab=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),vo=(t,e)=>{for(var r in e)nc(t,r,{get:e[r],enumerable:!0})},Nb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cb(e))!Ob.call(t,o)&&o!==r&&nc(t,o,{get:()=>e[o],enumerable:!(n=Ib(e,o))||n.enumerable});return t};var oc=(t,e,r)=>(r=t!=null?Pb(Ab(t)):{},Nb(e||!t||!t.__esModule?nc(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 ot(t){return t&&Object.assign(Ds,t),Ds}var Bw,Vw,Gt,Ds,Rn=G(()=>{Bw=Object.freeze({status:"aborted"});Vw=Symbol("zod_brand"),Gt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ds={}});var Y={};vo(Y,{BIGINT_FORMAT_RANGES:()=>om,Class:()=>lc,NUMBER_FORMAT_RANGES:()=>yc,aborted:()=>Qr,allowsEval:()=>mc,assert:()=>Xw,assertEqual:()=>Jw,assertIs:()=>Kw,assertNever:()=>Gw,assertNotEqual:()=>Ww,assignProp:()=>pc,cached:()=>So,captureStackTrace:()=>qs,cleanEnum:()=>l$,cleanRegex:()=>Eo,clone:()=>st,createTransparentProxy:()=>n$,defineLazy:()=>fe,esc:()=>Yr,escapeRegex:()=>fr,extend:()=>i$,finalizeIssue:()=>bt,floatSafeRemainder:()=>fc,getElementAtPath:()=>Yw,getEnumValues:()=>ko,getLengthableOrigin:()=>zo,getParsedType:()=>r$,getSizableOrigin:()=>sm,isObject:()=>Pn,isPlainObject:()=>In,issue:()=>_c,joinValues:()=>Ls,jsonStringifyReplacer:()=>dc,merge:()=>a$,normalizeParams:()=>L,nullish:()=>To,numKeys:()=>t$,omit:()=>s$,optionalKeys:()=>gc,partial:()=>c$,pick:()=>o$,prefixIssues:()=>Ot,primitiveTypes:()=>nm,promiseAllObject:()=>Qw,propertyKeyTypes:()=>hc,randomString:()=>e$,required:()=>u$,stringifyPrimitive:()=>Us,unwrapMessage:()=>$o});function Jw(t){return t}function Ww(t){return t}function Kw(t){}function Gw(t){throw new Error}function Xw(t){}function ko(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 Ls(t,e="|"){return t.map(r=>Us(r)).join(e)}function dc(t,e){return typeof e=="bigint"?e.toString():e}function So(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function To(t){return t==null}function Eo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function fe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function pc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Yw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Qw(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 e$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Yr(t){return JSON.stringify(t)}function Pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function In(t){if(Pn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Pn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function t$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function fr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function L(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function n$(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 Us(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function o$(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return st(t,{...t._zod.def,shape:r,checks:[]})}function s$(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return st(t,{...t._zod.def,shape:r,checks:[]})}function i$(t,e){if(!In(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 pc(this,"shape",n),n},checks:[]};return st(t,r)}function a$(t,e){return st(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return pc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function c$(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return st(e,{...e._zod.def,shape:o,checks:[]})}function u$(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return st(e,{...e._zod.def,shape:o,checks:[]})}function Qr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Ot(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $o(t){return typeof t=="string"?t:t?.message}function bt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=$o(t.inst?._zod.def?.error?.(t))??$o(e?.error?.(t))??$o(r.customError?.(t))??$o(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function sm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function zo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _c(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function l$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var qs,mc,r$,hc,nm,yc,om,lc,Nt=G(()=>{qs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};mc=So(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});r$=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}`)}},hc=new Set(["string","number","symbol"]),nm=new Set(["string","number","bigint","boolean","symbol","undefined"]);yc={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]},om={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};lc=class{constructor(...e){}}});function vc(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 xc(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 im,Fs,Ro,bc=G(()=>{Rn();Nt();im=(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,dc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fs=w("$ZodError",im),Ro=w("$ZodError",im,{Parent:Error})});var wc,$c,kc,Sc,Tc,en,Ec,tn,zc=G(()=>{Rn();bc();Nt();wc=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 Gt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>bt(c,s,ot())));throw qs(a,o?.callee),a}return i.value},$c=wc(Ro),kc=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=>bt(c,s,ot())));throw qs(a,o?.callee),a}return i.value},Sc=kc(Ro),Tc=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 Gt;return s.issues.length?{success:!1,error:new(t??Fs)(s.issues.map(i=>bt(i,o,ot())))}:{success:!0,data:s.value}},en=Tc(Ro),Ec=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=>bt(i,o,ot())))}:{success:!0,data:s.value}},tn=Ec(Ro)});function gm(){return new RegExp(f$,"u")}function Tm(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 Em(t){return new RegExp(`^${Tm(t)}$`)}function zm(t){let e=Tm({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(`^${km}T(?:${n})$`)}var am,cm,um,lm,dm,fm,pm,mm,Rc,hm,f$,ym,_m,vm,xm,bm,Pc,wm,$m,km,Sm,Rm,Pm,Im,Cm,Am,Om,Nm,Bs=G(()=>{am=/^[cC][^\s-]{8,}$/,cm=/^[0-9a-z]+$/,um=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lm=/^[0-9a-vA-V]{20}$/,dm=/^[A-Za-z0-9]{27}$/,fm=/^[a-zA-Z0-9_-]{21}$/,pm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mm=/^([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})$/,Rc=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)$/,hm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,f$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ym=/^(?:(?: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])$/,_m=/^(([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})$/,vm=/^((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])$/,xm=/^(([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])$/,bm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pc=/^[A-Za-z0-9_-]*$/,wm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$m=/^\+(?:[0-9]){6,14}[0-9]$/,km="(?:(?:\\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])))",Sm=new RegExp(`^${km}$`);Rm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Pm=/^\d+$/,Im=/^-?\d+(?:\.\d+)?/i,Cm=/true|false/i,Am=/null/i,Om=/^[^A-Z]*$/,Nm=/^[^a-z]*$/});var Pe,Mm,Ic,Cc,jm,Zm,Dm,Lm,qm,Po,Um,Fm,Hm,Bm,Vm,Jm,Wm,Vs=G(()=>{Rn();Bs();Nt();Pe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Mm={number:"number",bigint:"bigint",object:"date"},Ic=w("$ZodCheckLessThan",(t,e)=>{Pe.init(t,e);let r=Mm[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})}}),Cc=w("$ZodCheckGreaterThan",(t,e)=>{Pe.init(t,e);let r=Mm[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})}}),jm=w("$ZodCheckMultipleOf",(t,e)=>{Pe.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):fc(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})}}),Zm=w("$ZodCheckNumberFormat",(t,e)=>{Pe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=yc[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=Pm)}),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})}}),Dm=w("$ZodCheckMaxLength",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!To(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=zo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Lm=w("$ZodCheckMinLength",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!To(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=zo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qm=w("$ZodCheckLengthEquals",(t,e)=>{var r;Pe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!To(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=zo(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})}}),Po=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Pe.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=()=>{})}),Um=w("$ZodCheckRegex",(t,e)=>{Po.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})}}),Fm=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Om),Po.init(t,e)}),Hm=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Nm),Po.init(t,e)}),Bm=w("$ZodCheckIncludes",(t,e)=>{Pe.init(t,e);let r=fr(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})}}),Vm=w("$ZodCheckStartsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`^${fr(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})}}),Jm=w("$ZodCheckEndsWith",(t,e)=>{Pe.init(t,e);let r=new RegExp(`.*${fr(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})}}),Wm=w("$ZodCheckOverwrite",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Js,Ac=G(()=>{Js=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 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(`
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 Gm,Oc=G(()=>{Gm={major:4,minor:0,patch:0}});function lh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function p$(t){if(!Pc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lh(r)}function m$(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 Xm(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function Ws(t,e,r){t.issues.length&&e.issues.push(...Ot(r,t.issues)),e.value[r]=t.value}function Ym(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Ot(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Qm(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=>bt(s,n,ot())))}),e}function Nc(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(In(t)&&In(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=Nc(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=Nc(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 eh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Qr(t))return t;let n=Nc(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 th(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function rh(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 nh(t,e,r){return Qr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function oh(t){return t.value=Object.freeze(t.value),t}function sh(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(_c(o))}}var ue,Io,pe,Mc,jc,Zc,Dc,Lc,qc,Uc,Fc,Hc,Bc,Vc,ih,ah,ch,uh,Jc,Wc,Kc,Gc,Xc,Yc,Qc,eu,Ks,tu,ru,nu,ou,su,iu,Gs,Xs,au,cu,uu,lu,du,fu,pu,mu,hu,gu,yu,_u,vu,xu,bu,dh=G(()=>{Vs();Rn();Ac();zc();Bs();Nt();Oc();Nt();ue=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Gm;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=Qr(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 Gt;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=Qr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Qr(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 Gt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=en(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return tn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Io=w("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Rm(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),pe=w("$ZodStringFormat",(t,e)=>{Po.init(t,e),Io.init(t,e)}),Mc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=mm),pe.init(t,e)}),jc=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=Rc(n))}else e.pattern??(e.pattern=Rc());pe.init(t,e)}),Zc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=hm),pe.init(t,e)}),Dc=w("$ZodURL",(t,e)=>{pe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:wm.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})}}}),Lc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=gm()),pe.init(t,e)}),qc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=fm),pe.init(t,e)}),Uc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=am),pe.init(t,e)}),Fc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=cm),pe.init(t,e)}),Hc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=um),pe.init(t,e)}),Bc=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=lm),pe.init(t,e)}),Vc=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=dm),pe.init(t,e)}),ih=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=zm(e)),pe.init(t,e)}),ah=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sm),pe.init(t,e)}),ch=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Em(e)),pe.init(t,e)}),uh=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=pm),pe.init(t,e)}),Jc=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ym),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Wc=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=_m),pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Kc=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=vm),pe.init(t,e)}),Gc=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=xm),pe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Xc=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=bm),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Yc=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Pc),pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{p$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Qc=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$m),pe.init(t,e)});eu=w("$ZodJWT",(t,e)=>{pe.init(t,e),t._zod.check=r=>{m$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ks=w("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??Im,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}}),tu=w("$ZodNumber",(t,e)=>{Zm.init(t,e),Ks.init(t,e)}),ru=w("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=Cm,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}}),nu=w("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=Am,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}}),ou=w("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),su=w("$ZodNever",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});iu=w("$ZodArray",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Xm(u,r,i))):Xm(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Gs=w("$ZodObject",(t,e)=>{ue.init(t,e);let r=So(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof ue))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=gc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});fe(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 Js(["shape","payload","ctx"]),p=r.value,f=v=>{let y=Yr(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=Yr(v);m.write(`
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(`
6
6
  if (${y}.issues.length) {
7
7
  if (input[${x}] === undefined) {
8
8
  if (${x} in input) {
@@ -24,18 +24,18 @@ var Pb=Object.create;var nc=Object.defineProperty;var Ib=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 ? [${Yr(v)}, ...iss.path] : [${Yr(v)}]
28
- })));`),m.write(`newResult[${Yr(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Pn,i=!Ds.jitless,c=i&&mc.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],O=$._zod.run({value:p[x],issues:[]},m),C=$._zod.optin==="optional"&&$._zod.optout==="optional";O instanceof Promise?f.push(O.then(ae=>C?Ym(ae,d,x,p):Ws(ae,d,x))):C?Ym(O,d,x,p):Ws(O,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($=>Ws($,d,y))):Ws(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}});Xs=w("$ZodUnion",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),fe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Eo(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=>Qm(i,r,t,n)):Qm(s,r,t,n)}}),au=w("$ZodDiscriminatedUnion",(t,e)=>{Xs.init(t,e);let r=t._zod.parse;fe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=So(()=>{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(!Pn(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)}}),cu=w("$ZodIntersection",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>eh(r,c,u)):eh(r,s,i)}});uu=w("$ZodRecord",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!In(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(...Ot(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Ot(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>bt(u,n,ot())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Ot(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Ot(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),lu=w("$ZodEnum",(t,e)=>{ue.init(t,e);let r=ko(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>hc.has(typeof n)).map(n=>typeof n=="string"?fr(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}}),du=w("$ZodLiteral",(t,e)=>{ue.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?fr(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}}),fu=w("$ZodTransform",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Gt;return r.value=o,r}}),pu=w("$ZodOptional",(t,e)=>{ue.init(t,e),t._zod.optin="optional",t._zod.optout="optional",fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(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)}),mu=w("$ZodNullable",(t,e)=>{ue.init(t,e),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Eo(r.source)}|null)$`):void 0}),fe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),hu=w("$ZodDefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>th(s,e)):th(o,e)}});gu=w("$ZodPrefault",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),yu=w("$ZodNonOptional",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rh(s,t)):rh(o,t)}});_u=w("$ZodCatch",(t,e)=>{ue.init(t,e),t._zod.optin="optional",fe(t._zod,"optout",()=>e.innerType._zod.optout),fe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>bt(i,n,ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>bt(s,n,ot()))},input:r.value}),r.issues=[]),r)}}),vu=w("$ZodPipe",(t,e)=>{ue.init(t,e),fe(t._zod,"values",()=>e.in._zod.values),fe(t._zod,"optin",()=>e.in._zod.optin),fe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>nh(s,e,n)):nh(o,e,n)}});xu=w("$ZodReadonly",(t,e)=>{ue.init(t,e),fe(t._zod,"propValues",()=>e.innerType._zod.propValues),fe(t._zod,"values",()=>e.innerType._zod.values),fe(t._zod,"optin",()=>e.innerType._zod.optin),fe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(oh):oh(o)}});bu=w("$ZodCustom",(t,e)=>{Pe.init(t,e),ue.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>sh(s,r,n,t));sh(o,r,n,t)}})});function fh(){return{localeError:g$()}}var h$,g$,ph=G(()=>{Nt();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},g$=()=>{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 ${Us(n.values[0])}`:`Invalid option: expected one of ${Ls(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":""}: ${Ls(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 Ys=G(()=>{});function mh(){return new Co}var y$,_$,Co,pr,$u=G(()=>{y$=Symbol("ZodOutput"),_$=Symbol("ZodInput"),Co=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)}};pr=mh()});function ku(t,e){return new t({type:"string",...L(e)})}function Su(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...L(e)})}function Qs(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...L(e)})}function Tu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...L(e)})}function Eu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(e)})}function zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(e)})}function Ru(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(e)})}function Pu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...L(e)})}function Iu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...L(e)})}function Cu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(e)})}function Au(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...L(e)})}function Ou(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(e)})}function Nu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...L(e)})}function Mu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...L(e)})}function ju(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(e)})}function Zu(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(e)})}function Du(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(e)})}function Lu(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(e)})}function qu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(e)})}function Uu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...L(e)})}function Fu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...L(e)})}function Hu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...L(e)})}function Bu(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...L(e)})}function hh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(e)})}function gh(t,e){return new t({type:"string",format:"date",check:"string_format",...L(e)})}function yh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...L(e)})}function _h(t,e){return new t({type:"string",format:"duration",check:"string_format",...L(e)})}function Vu(t,e){return new t({type:"number",checks:[],...L(e)})}function Ju(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...L(e)})}function Wu(t,e){return new t({type:"boolean",...L(e)})}function Ku(t,e){return new t({type:"null",...L(e)})}function Gu(t){return new t({type:"unknown"})}function Xu(t,e){return new t({type:"never",...L(e)})}function ei(t,e){return new Ic({check:"less_than",...L(e),value:t,inclusive:!1})}function Ao(t,e){return new Ic({check:"less_than",...L(e),value:t,inclusive:!0})}function ti(t,e){return new Cc({check:"greater_than",...L(e),value:t,inclusive:!1})}function Oo(t,e){return new Cc({check:"greater_than",...L(e),value:t,inclusive:!0})}function ri(t,e){return new jm({check:"multiple_of",...L(e),value:t})}function ni(t,e){return new Dm({check:"max_length",...L(e),maximum:t})}function Cn(t,e){return new Lm({check:"min_length",...L(e),minimum:t})}function oi(t,e){return new qm({check:"length_equals",...L(e),length:t})}function Yu(t,e){return new Um({check:"string_format",format:"regex",...L(e),pattern:t})}function Qu(t){return new Fm({check:"string_format",format:"lowercase",...L(t)})}function el(t){return new Hm({check:"string_format",format:"uppercase",...L(t)})}function tl(t,e){return new Bm({check:"string_format",format:"includes",...L(e),includes:t})}function rl(t,e){return new Vm({check:"string_format",format:"starts_with",...L(e),prefix:t})}function nl(t,e){return new Jm({check:"string_format",format:"ends_with",...L(e),suffix:t})}function rn(t){return new Wm({check:"overwrite",tx:t})}function ol(t){return rn(e=>e.normalize(t))}function sl(){return rn(t=>t.trim())}function il(){return rn(t=>t.toLowerCase())}function al(){return rn(t=>t.toUpperCase())}function vh(t,e,r){return new t({type:"array",element:e,...L(r)})}function cl(t,e,r){let n=L(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ul(t,e,r){return new t({type:"custom",check:"custom",fn:e,...L(r)})}var xh=G(()=>{Vs();Nt()});var bh=G(()=>{});function ll(t,e){if(t instanceof Co){let n=new si(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 si(e);return r.process(t),r.emit(t,e)}function Se(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Se(o.element,r);case"object":{for(let s in o.shape)if(Se(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Se(s,r))return!0;return!1}case"intersection":return Se(o.left,r)||Se(o.right,r);case"tuple":{for(let s of o.items)if(Se(s,r))return!0;return!!(o.rest&&Se(o.rest,r))}case"record":return Se(o.keyType,r)||Se(o.valueType,r);case"map":return Se(o.keyType,r)||Se(o.valueType,r);case"set":return Se(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Se(o.innerType,r);case"lazy":return Se(o.getter(),r);case"default":return Se(o.innerType,r);case"prefault":return Se(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Se(o.in,r)||Se(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var si,wh=G(()=>{$u();Nt();si=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??pr,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=ko(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"&&Se(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let 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 ? [${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>
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 $h=G(()=>{});var Ue=G(()=>{Rn();zc();bc();dh();Vs();Oc();Nt();Bs();Ys();$u();Ac();bh();xh();wh();$h()});var fl=G(()=>{Ue()});var No={};vo(No,{ZodISODate:()=>Eh,ZodISODateTime:()=>Th,ZodISODuration:()=>Rh,ZodISOTime:()=>zh,date:()=>ml,datetime:()=>pl,duration:()=>gl,time:()=>hl});function pl(t){return hh(Th,t)}function ml(t){return gh(Eh,t)}function hl(t){return yh(zh,t)}function gl(t){return _h(Rh,t)}var Th,Eh,zh,Rh,yl=G(()=>{Ue();_l();Th=w("ZodISODateTime",(t,e)=>{ih.init(t,e),ve.init(t,e)});Eh=w("ZodISODate",(t,e)=>{ah.init(t,e),ve.init(t,e)});zh=w("ZodISOTime",(t,e)=>{ch.init(t,e),ve.init(t,e)});Rh=w("ZodISODuration",(t,e)=>{uh.init(t,e),ve.init(t,e)})});var Ph,Oj,Mo,vl=G(()=>{Ue();Ue();Ph=(t,e)=>{Fs.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xc(t,r)},flatten:{value:r=>vc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Oj=w("ZodError",Ph),Mo=w("ZodError",Ph,{Parent:Error})});var Ih,Ch,Ah,Oh,xl=G(()=>{Ue();vl();Ih=wc(Mo),Ch=kc(Mo),Ah=Tc(Mo),Oh=Ec(Mo)});function b(t){return ku(lk,t)}function se(t){return Vu(Dh,t)}function Mh(t){return Ju(zk,t)}function ze(t){return Wu(Rk,t)}function Lh(t){return Ku(Pk,t)}function xe(){return Gu(Ik)}function Ak(t){return Xu(Ck,t)}function Q(t,e){return vh(Ok,t,e)}function P(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new qh(r)}function Fe(t,e){return new qh({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:xe(),...Y.normalizeParams(e)})}function he(t,e){return new Uh({type:"union",options:t,...Y.normalizeParams(e)})}function $l(t,e,r){return new Nk({type:"union",options:e,discriminator:t,...Y.normalizeParams(r)})}function ui(t,e){return new Mk({type:"intersection",left:t,right:e})}function me(t,e,r){return new jk({type:"record",keyType:t,valueType:e,...Y.normalizeParams(r)})}function Xe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new bl({type:"enum",entries:r,...Y.normalizeParams(e)})}function M(t,e){return new Zk({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}function Fh(t){return new Dk({type:"transform",transform:t})}function be(t){return new Hh({type:"optional",innerType:t})}function jh(t){return new Lk({type:"nullable",innerType:t})}function Uk(t,e){return new qk({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Hk(t,e){return new Fk({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Bk(t,e){return new Bh({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}function Jk(t,e){return new Vk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function wl(t,e){return new Wk({type:"pipe",in:t,out:e})}function Gk(t){return new Kk({type:"readonly",innerType:t})}function Xk(t){let e=new Pe({check:"custom"});return e._zod.check=t,e}function Jh(t,e){return cl(Vh,t??(()=>!0),e)}function Yk(t,e={}){return ul(Vh,t,e)}function Qk(t){let e=Xk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Y.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(Y.issue(o))}},t(r.value,r)));return e}function kl(t,e){return wl(Fh(t),e)}var $e,Zh,lk,ve,dk,Nh,ci,fk,pk,mk,hk,gk,yk,_k,vk,xk,bk,wk,$k,kk,Sk,Tk,Ek,Dh,zk,Rk,Pk,Ik,Ck,Ok,qh,Uh,Nk,Mk,jk,bl,Zk,Dk,Hh,Lk,qk,Fk,Bh,Vk,Wk,Kk,Vh,_l=G(()=>{Ue();Ue();fl();yl();xl();$e=w("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Ih(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ah(t,r,n),t.parseAsync=async(r,n)=>Ch(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Oh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Yk(r,n)),t.superRefine=r=>t.check(Qk(r)),t.overwrite=r=>t.check(rn(r)),t.optional=()=>be(t),t.nullable=()=>jh(t),t.nullish=()=>be(jh(t)),t.nonoptional=r=>Bk(t,r),t.array=()=>Q(t),t.or=r=>he([t,r]),t.and=r=>ui(t,r),t.transform=r=>wl(t,Fh(r)),t.default=r=>Uk(t,r),t.prefault=r=>Hk(t,r),t.catch=r=>Jk(t,r),t.pipe=r=>wl(t,r),t.readonly=()=>Gk(t),t.describe=r=>{let n=t.clone();return pr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return pr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return pr.get(t);let n=t.clone();return pr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Zh=w("_ZodString",(t,e)=>{Io.init(t,e),$e.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Yu(...n)),t.includes=(...n)=>t.check(tl(...n)),t.startsWith=(...n)=>t.check(rl(...n)),t.endsWith=(...n)=>t.check(nl(...n)),t.min=(...n)=>t.check(Cn(...n)),t.max=(...n)=>t.check(ni(...n)),t.length=(...n)=>t.check(oi(...n)),t.nonempty=(...n)=>t.check(Cn(1,...n)),t.lowercase=n=>t.check(Qu(n)),t.uppercase=n=>t.check(el(n)),t.trim=()=>t.check(sl()),t.normalize=(...n)=>t.check(ol(...n)),t.toLowerCase=()=>t.check(il()),t.toUpperCase=()=>t.check(al())}),lk=w("ZodString",(t,e)=>{Io.init(t,e),Zh.init(t,e),t.email=r=>t.check(Su(dk,r)),t.url=r=>t.check(Pu(fk,r)),t.jwt=r=>t.check(Bu(Ek,r)),t.emoji=r=>t.check(Iu(pk,r)),t.guid=r=>t.check(Qs(Nh,r)),t.uuid=r=>t.check(Tu(ci,r)),t.uuidv4=r=>t.check(Eu(ci,r)),t.uuidv6=r=>t.check(zu(ci,r)),t.uuidv7=r=>t.check(Ru(ci,r)),t.nanoid=r=>t.check(Cu(mk,r)),t.guid=r=>t.check(Qs(Nh,r)),t.cuid=r=>t.check(Au(hk,r)),t.cuid2=r=>t.check(Ou(gk,r)),t.ulid=r=>t.check(Nu(yk,r)),t.base64=r=>t.check(Uu(kk,r)),t.base64url=r=>t.check(Fu(Sk,r)),t.xid=r=>t.check(Mu(_k,r)),t.ksuid=r=>t.check(ju(vk,r)),t.ipv4=r=>t.check(Zu(xk,r)),t.ipv6=r=>t.check(Du(bk,r)),t.cidrv4=r=>t.check(Lu(wk,r)),t.cidrv6=r=>t.check(qu($k,r)),t.e164=r=>t.check(Hu(Tk,r)),t.datetime=r=>t.check(pl(r)),t.date=r=>t.check(ml(r)),t.time=r=>t.check(hl(r)),t.duration=r=>t.check(gl(r))});ve=w("ZodStringFormat",(t,e)=>{pe.init(t,e),Zh.init(t,e)}),dk=w("ZodEmail",(t,e)=>{Zc.init(t,e),ve.init(t,e)}),Nh=w("ZodGUID",(t,e)=>{Mc.init(t,e),ve.init(t,e)}),ci=w("ZodUUID",(t,e)=>{jc.init(t,e),ve.init(t,e)}),fk=w("ZodURL",(t,e)=>{Dc.init(t,e),ve.init(t,e)}),pk=w("ZodEmoji",(t,e)=>{Lc.init(t,e),ve.init(t,e)}),mk=w("ZodNanoID",(t,e)=>{qc.init(t,e),ve.init(t,e)}),hk=w("ZodCUID",(t,e)=>{Uc.init(t,e),ve.init(t,e)}),gk=w("ZodCUID2",(t,e)=>{Fc.init(t,e),ve.init(t,e)}),yk=w("ZodULID",(t,e)=>{Hc.init(t,e),ve.init(t,e)}),_k=w("ZodXID",(t,e)=>{Bc.init(t,e),ve.init(t,e)}),vk=w("ZodKSUID",(t,e)=>{Vc.init(t,e),ve.init(t,e)}),xk=w("ZodIPv4",(t,e)=>{Jc.init(t,e),ve.init(t,e)}),bk=w("ZodIPv6",(t,e)=>{Wc.init(t,e),ve.init(t,e)}),wk=w("ZodCIDRv4",(t,e)=>{Kc.init(t,e),ve.init(t,e)}),$k=w("ZodCIDRv6",(t,e)=>{Gc.init(t,e),ve.init(t,e)}),kk=w("ZodBase64",(t,e)=>{Xc.init(t,e),ve.init(t,e)}),Sk=w("ZodBase64URL",(t,e)=>{Yc.init(t,e),ve.init(t,e)}),Tk=w("ZodE164",(t,e)=>{Qc.init(t,e),ve.init(t,e)}),Ek=w("ZodJWT",(t,e)=>{eu.init(t,e),ve.init(t,e)}),Dh=w("ZodNumber",(t,e)=>{Ks.init(t,e),$e.init(t,e),t.gt=(n,o)=>t.check(ti(n,o)),t.gte=(n,o)=>t.check(Oo(n,o)),t.min=(n,o)=>t.check(Oo(n,o)),t.lt=(n,o)=>t.check(ei(n,o)),t.lte=(n,o)=>t.check(Ao(n,o)),t.max=(n,o)=>t.check(Ao(n,o)),t.int=n=>t.check(Mh(n)),t.safe=n=>t.check(Mh(n)),t.positive=n=>t.check(ti(0,n)),t.nonnegative=n=>t.check(Oo(0,n)),t.negative=n=>t.check(ei(0,n)),t.nonpositive=n=>t.check(Ao(0,n)),t.multipleOf=(n,o)=>t.check(ri(n,o)),t.step=(n,o)=>t.check(ri(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});zk=w("ZodNumberFormat",(t,e)=>{tu.init(t,e),Dh.init(t,e)});Rk=w("ZodBoolean",(t,e)=>{ru.init(t,e),$e.init(t,e)});Pk=w("ZodNull",(t,e)=>{nu.init(t,e),$e.init(t,e)});Ik=w("ZodUnknown",(t,e)=>{ou.init(t,e),$e.init(t,e)});Ck=w("ZodNever",(t,e)=>{su.init(t,e),$e.init(t,e)});Ok=w("ZodArray",(t,e)=>{iu.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Cn(r,n)),t.nonempty=r=>t.check(Cn(1,r)),t.max=(r,n)=>t.check(ni(r,n)),t.length=(r,n)=>t.check(oi(r,n)),t.unwrap=()=>t.element});qh=w("ZodObject",(t,e)=>{Gs.init(t,e),$e.init(t,e),Y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Xe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xe()}),t.loose=()=>t.clone({...t._zod.def,catchall:xe()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ak()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Y.extend(t,r),t.merge=r=>Y.merge(t,r),t.pick=r=>Y.pick(t,r),t.omit=r=>Y.omit(t,r),t.partial=(...r)=>Y.partial(Hh,t,r[0]),t.required=(...r)=>Y.required(Bh,t,r[0])});Uh=w("ZodUnion",(t,e)=>{Xs.init(t,e),$e.init(t,e),t.options=e.options});Nk=w("ZodDiscriminatedUnion",(t,e)=>{Uh.init(t,e),au.init(t,e)});Mk=w("ZodIntersection",(t,e)=>{cu.init(t,e),$e.init(t,e)});jk=w("ZodRecord",(t,e)=>{uu.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});bl=w("ZodEnum",(t,e)=>{lu.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new bl({...e,checks:[],...Y.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new bl({...e,checks:[],...Y.normalizeParams(o),entries:s})}});Zk=w("ZodLiteral",(t,e)=>{du.init(t,e),$e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Dk=w("ZodTransform",(t,e)=>{fu.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(Y.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Hh=w("ZodOptional",(t,e)=>{pu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Lk=w("ZodNullable",(t,e)=>{mu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});qk=w("ZodDefault",(t,e)=>{hu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Fk=w("ZodPrefault",(t,e)=>{gu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Bh=w("ZodNonOptional",(t,e)=>{yu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});Vk=w("ZodCatch",(t,e)=>{_u.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Wk=w("ZodPipe",(t,e)=>{vu.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});Kk=w("ZodReadonly",(t,e)=>{xu.init(t,e),$e.init(t,e)});Vh=w("ZodCustom",(t,e)=>{bu.init(t,e),$e.init(t,e)})});var Wh=G(()=>{});var Kh=G(()=>{});var Gh=G(()=>{Ue();_l();fl();vl();xl();Wh();Ue();ph();Ys();yl();Kh();ot(fh())});var Xh=G(()=>{Gh()});var Yh=G(()=>{Xh()});function pg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function mg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Tl,Qh,Mn,gr,di,Te,eg,tg,Gj,rS,nS,El,it,jo,rg,Ie,lt,dt,Ce,fi,ng,Xt,og,sg,zl,Yt,A,Rl,jn,Zo,Xj,pi,oS,mi,sS,Do,Nn,ig,iS,aS,cS,uS,lS,dS,hi,Pl,fS,pS,Il,gi,mS,hS,yi,gS,Lo,qo,yS,Uo,Zn,_S,Fo,_i,vi,xi,Yj,bi,wi,$i,ag,cg,ug,Cl,lg,Ho,Dn,dg,vS,ki,xS,Si,bS,Al,wS,Ti,$S,kS,SS,TS,ES,zS,RS,PS,IS,CS,Ei,AS,OS,zi,Ol,Nl,Ml,NS,MS,jS,jl,ZS,DS,LS,qS,US,fg,Ri,FS,Pi,Qj,HS,Ln,BS,eZ,Bo,VS,Zl,JS,WS,KS,GS,XS,YS,QS,li,eT,tT,rT,Vo,Dl,nT,oT,sT,iT,aT,cT,uT,lT,dT,fT,pT,mT,hT,gT,yT,_T,vT,xT,qn,bT,wT,$T,Ii,kT,ST,TT,Ll,ET,tZ,rZ,nZ,oZ,sZ,iZ,I,Sl,yr=G(()=>{Yh();Tl="2025-11-25",Qh="2025-03-26",Mn=[Tl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",di="2.0",Te=Jh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),eg=he([b(),se().int()]),tg=b(),Gj=Fe({ttl:se().optional(),pollInterval:se().optional()}),rS=P({ttl:se().optional()}),nS=P({taskId:b()}),El=Fe({progressToken:eg.optional(),[gr]:nS.optional()}),it=P({_meta:El.optional()}),jo=it.extend({task:rS.optional()}),rg=t=>jo.safeParse(t).success,Ie=P({method:b(),params:it.loose().optional()}),lt=P({_meta:El.optional()}),dt=P({method:b(),params:lt.loose().optional()}),Ce=Fe({_meta:El.optional()}),fi=he([b(),se().int()]),ng=P({jsonrpc:M(di),id:fi,...Ie.shape}).strict(),Xt=t=>ng.safeParse(t).success,og=P({jsonrpc:M(di),...dt.shape}).strict(),sg=t=>og.safeParse(t).success,zl=P({jsonrpc:M(di),id:fi,result:Ce}).strict(),Yt=t=>zl.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"})(A||(A={}));Rl=P({jsonrpc:M(di),id:fi.optional(),error:P({code:se().int(),message:b(),data:xe().optional()})}).strict(),jn=t=>Rl.safeParse(t).success,Zo=he([ng,og,zl,Rl]),Xj=he([zl,Rl]),pi=Ce.strict(),oS=lt.extend({requestId:fi.optional(),reason:b().optional()}),mi=dt.extend({method:M("notifications/cancelled"),params:oS}),sS=P({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Xe(["light","dark"]).optional()}),Do=P({icons:Q(sS).optional()}),Nn=P({name:b(),title:b().optional()}),ig=Nn.extend({...Nn.shape,...Do.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),iS=ui(P({applyDefaults:ze().optional()}),me(b(),xe())),aS=kl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ui(P({form:iS.optional(),url:Te.optional()}),me(b(),xe()).optional())),cS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({sampling:Fe({createMessage:Te.optional()}).optional(),elicitation:Fe({create:Te.optional()}).optional()}).optional()}),uS=Fe({list:Te.optional(),cancel:Te.optional(),requests:Fe({tools:Fe({call:Te.optional()}).optional()}).optional()}),lS=P({experimental:me(b(),Te).optional(),sampling:P({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:aS.optional(),roots:P({listChanged:ze().optional()}).optional(),tasks:cS.optional(),extensions:me(b(),Te).optional()}),dS=it.extend({protocolVersion:b(),capabilities:lS,clientInfo:ig}),hi=Ie.extend({method:M("initialize"),params:dS}),Pl=t=>hi.safeParse(t).success,fS=P({experimental:me(b(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:P({listChanged:ze().optional()}).optional(),resources:P({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:P({listChanged:ze().optional()}).optional(),tasks:uS.optional(),extensions:me(b(),Te).optional()}),pS=Ce.extend({protocolVersion:b(),capabilities:fS,serverInfo:ig,instructions:b().optional()}),Il=dt.extend({method:M("notifications/initialized"),params:lt.optional()}),gi=Ie.extend({method:M("ping"),params:it.optional()}),mS=P({progress:se(),total:be(se()),message:be(b())}),hS=P({...lt.shape,...mS.shape,progressToken:eg}),yi=dt.extend({method:M("notifications/progress"),params:hS}),gS=it.extend({cursor:tg.optional()}),Lo=Ie.extend({params:gS.optional()}),qo=Ce.extend({nextCursor:tg.optional()}),yS=Xe(["working","input_required","completed","failed","cancelled"]),Uo=P({taskId:b(),status:yS,ttl:he([se(),Lh()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:be(se()),statusMessage:be(b())}),Zn=Ce.extend({task:Uo}),_S=lt.merge(Uo),Fo=dt.extend({method:M("notifications/tasks/status"),params:_S}),_i=Ie.extend({method:M("tasks/get"),params:it.extend({taskId:b()})}),vi=Ce.merge(Uo),xi=Ie.extend({method:M("tasks/result"),params:it.extend({taskId:b()})}),Yj=Ce.loose(),bi=Lo.extend({method:M("tasks/list")}),wi=qo.extend({tasks:Q(Uo)}),$i=Ie.extend({method:M("tasks/cancel"),params:it.extend({taskId:b()})}),ag=Ce.merge(Uo),cg=P({uri:b(),mimeType:be(b()),_meta:me(b(),xe()).optional()}),ug=cg.extend({text:b()}),Cl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lg=cg.extend({blob:Cl}),Ho=Xe(["user","assistant"]),Dn=P({audience:Q(Ho).optional(),priority:se().min(0).max(1).optional(),lastModified:No.datetime({offset:!0}).optional()}),dg=P({...Nn.shape,...Do.shape,uri:b(),description:be(b()),mimeType:be(b()),size:be(se()),annotations:Dn.optional(),_meta:be(Fe({}))}),vS=P({...Nn.shape,...Do.shape,uriTemplate:b(),description:be(b()),mimeType:be(b()),annotations:Dn.optional(),_meta:be(Fe({}))}),ki=Lo.extend({method:M("resources/list")}),xS=qo.extend({resources:Q(dg)}),Si=Lo.extend({method:M("resources/templates/list")}),bS=qo.extend({resourceTemplates:Q(vS)}),Al=it.extend({uri:b()}),wS=Al,Ti=Ie.extend({method:M("resources/read"),params:wS}),$S=Ce.extend({contents:Q(he([ug,lg]))}),kS=dt.extend({method:M("notifications/resources/list_changed"),params:lt.optional()}),SS=Al,TS=Ie.extend({method:M("resources/subscribe"),params:SS}),ES=Al,zS=Ie.extend({method:M("resources/unsubscribe"),params:ES}),RS=lt.extend({uri:b()}),PS=dt.extend({method:M("notifications/resources/updated"),params:RS}),IS=P({name:b(),description:be(b()),required:be(ze())}),CS=P({...Nn.shape,...Do.shape,description:be(b()),arguments:be(Q(IS)),_meta:be(Fe({}))}),Ei=Lo.extend({method:M("prompts/list")}),AS=qo.extend({prompts:Q(CS)}),OS=it.extend({name:b(),arguments:me(b(),b()).optional()}),zi=Ie.extend({method:M("prompts/get"),params:OS}),Ol=P({type:M("text"),text:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),Nl=P({type:M("image"),data:Cl,mimeType:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),Ml=P({type:M("audio"),data:Cl,mimeType:b(),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),NS=P({type:M("tool_use"),name:b(),id:b(),input:me(b(),xe()),_meta:me(b(),xe()).optional()}),MS=P({type:M("resource"),resource:he([ug,lg]),annotations:Dn.optional(),_meta:me(b(),xe()).optional()}),jS=dg.extend({type:M("resource_link")}),jl=he([Ol,Nl,Ml,jS,MS]),ZS=P({role:Ho,content:jl}),DS=Ce.extend({description:b().optional(),messages:Q(ZS)}),LS=dt.extend({method:M("notifications/prompts/list_changed"),params:lt.optional()}),qS=P({title:b().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),US=P({taskSupport:Xe(["required","optional","forbidden"]).optional()}),fg=P({...Nn.shape,...Do.shape,description:b().optional(),inputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()),outputSchema:P({type:M("object"),properties:me(b(),Te).optional(),required:Q(b()).optional()}).catchall(xe()).optional(),annotations:qS.optional(),execution:US.optional(),_meta:me(b(),xe()).optional()}),Ri=Lo.extend({method:M("tools/list")}),FS=qo.extend({tools:Q(fg)}),Pi=Ce.extend({content:Q(jl).default([]),structuredContent:me(b(),xe()).optional(),isError:ze().optional()}),Qj=Pi.or(Ce.extend({toolResult:xe()})),HS=jo.extend({name:b(),arguments:me(b(),xe()).optional()}),Ln=Ie.extend({method:M("tools/call"),params:HS}),BS=dt.extend({method:M("notifications/tools/list_changed"),params:lt.optional()}),eZ=P({autoRefresh:ze().default(!0),debounceMs:se().int().nonnegative().default(300)}),Bo=Xe(["debug","info","notice","warning","error","critical","alert","emergency"]),VS=it.extend({level:Bo}),Zl=Ie.extend({method:M("logging/setLevel"),params:VS}),JS=lt.extend({level:Bo,logger:b().optional(),data:xe()}),WS=dt.extend({method:M("notifications/message"),params:JS}),KS=P({name:b().optional()}),GS=P({hints:Q(KS).optional(),costPriority:se().min(0).max(1).optional(),speedPriority:se().min(0).max(1).optional(),intelligencePriority:se().min(0).max(1).optional()}),XS=P({mode:Xe(["auto","required","none"]).optional()}),YS=P({type:M("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(jl).default([]),structuredContent:P({}).loose().optional(),isError:ze().optional(),_meta:me(b(),xe()).optional()}),QS=$l("type",[Ol,Nl,Ml]),li=$l("type",[Ol,Nl,Ml,NS,YS]),eT=P({role:Ho,content:he([li,Q(li)]),_meta:me(b(),xe()).optional()}),tT=jo.extend({messages:Q(eT),modelPreferences:GS.optional(),systemPrompt:b().optional(),includeContext:Xe(["none","thisServer","allServers"]).optional(),temperature:se().optional(),maxTokens:se().int(),stopSequences:Q(b()).optional(),metadata:Te.optional(),tools:Q(fg).optional(),toolChoice:XS.optional()}),rT=Ie.extend({method:M("sampling/createMessage"),params:tT}),Vo=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens"]).or(b())),role:Ho,content:QS}),Dl=Ce.extend({model:b(),stopReason:be(Xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Ho,content:he([li,Q(li)])}),nT=P({type:M("boolean"),title:b().optional(),description:b().optional(),default:ze().optional()}),oT=P({type:M("string"),title:b().optional(),description:b().optional(),minLength:se().optional(),maxLength:se().optional(),format:Xe(["email","uri","date","date-time"]).optional(),default:b().optional()}),sT=P({type:Xe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:se().optional(),maximum:se().optional(),default:se().optional()}),iT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),aT=P({type:M("string"),title:b().optional(),description:b().optional(),oneOf:Q(P({const:b(),title:b()})),default:b().optional()}),cT=P({type:M("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),uT=he([iT,aT]),lT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({type:M("string"),enum:Q(b())}),default:Q(b()).optional()}),dT=P({type:M("array"),title:b().optional(),description:b().optional(),minItems:se().optional(),maxItems:se().optional(),items:P({anyOf:Q(P({const:b(),title:b()}))}),default:Q(b()).optional()}),fT=he([lT,dT]),pT=he([cT,uT,fT]),mT=he([pT,nT,oT,sT]),hT=jo.extend({mode:M("form").optional(),message:b(),requestedSchema:P({type:M("object"),properties:me(b(),mT),required:Q(b()).optional()})}),gT=jo.extend({mode:M("url"),message:b(),elicitationId:b(),url:b().url()}),yT=he([hT,gT]),_T=Ie.extend({method:M("elicitation/create"),params:yT}),vT=lt.extend({elicitationId:b()}),xT=dt.extend({method:M("notifications/elicitation/complete"),params:vT}),qn=Ce.extend({action:Xe(["accept","decline","cancel"]),content:kl(t=>t===null?void 0:t,me(b(),he([b(),se(),ze(),Q(b())])).optional())}),bT=P({type:M("ref/resource"),uri:b()}),wT=P({type:M("ref/prompt"),name:b()}),$T=it.extend({ref:he([wT,bT]),argument:P({name:b(),value:b()}),context:P({arguments:me(b(),b()).optional()}).optional()}),Ii=Ie.extend({method:M("completion/complete"),params:$T});kT=Ce.extend({completion:Fe({values:Q(b()).max(100),total:be(se().int()),hasMore:be(ze())})}),ST=P({uri:b().startsWith("file://"),name:b().optional(),_meta:me(b(),xe()).optional()}),TT=Ie.extend({method:M("roots/list"),params:it.optional()}),Ll=Ce.extend({roots:Q(ST)}),ET=dt.extend({method:M("notifications/roots/list_changed"),params:lt.optional()}),tZ=he([gi,hi,Ii,Zl,zi,Ei,ki,Si,Ti,TS,zS,Ln,Ri,_i,xi,bi,$i]),rZ=he([mi,yi,Il,ET,Fo]),nZ=he([pi,Vo,Dl,qn,Ll,vi,wi,Zn]),oZ=he([gi,rT,_T,TT,_i,xi,bi,$i]),sZ=he([mi,yi,WS,PS,kS,BS,LS,Fo,xT]),iZ=he([pi,pS,kT,DS,AS,xS,bS,$S,Pi,FS,vi,wi,Zn]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Sl(o.elicitations,r)}return new t(e,r,n)}},Sl=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Go=E(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var Wo=class{};oe._CodeOrName=Wo;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var sn=class extends Wo{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=sn;var ft=class extends Wo{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 sn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=ft;oe.nil=new ft("");function Kg(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Gl(r,e[n]),r.push(t[++n]);return new ft(r)}oe._=Kg;var Kl=new ft("+");function Gg(t,...e){let r=[Ko(t[0])],n=0;for(;n<e.length;)r.push(Kl),Gl(r,e[n]),r.push(Kl,Ko(t[++n]));return ZT(r),new ft(r)}oe.str=Gg;function Gl(t,e){e instanceof ft?t.push(...e._items):e instanceof sn?t.push(e):t.push(qT(e))}oe.addCodeArg=Gl;function ZT(t){let e=1;for(;e<t.length-1;){if(t[e]===Kl){let r=DT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function DT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof sn||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 sn))return`"${t}${e.slice(1)}`}function LT(t,e){return e.emptyStr()?t:t.emptyStr()?e:Gg`${t}${e}`}oe.strConcat=LT;function qT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ko(Array.isArray(t)?t.join(","):t)}function UT(t){return new ft(Ko(t))}oe.stringify=UT;function Ko(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=Ko;function FT(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new ft(`.${t}`):Kg`[${t}]`}oe.getProperty=FT;function HT(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new ft(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=HT;function BT(t){return new ft(t.toString())}oe.regexpCode=BT});var Ql=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=Go(),Xl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ji;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ji||(Qe.UsedValueState=ji={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Zi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=Zi;var Di=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=Di;var VT=(0,Ye._)`\n`,Yl=class extends Zi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?VT:Ye.nil}}get(){return this._scope}name(e){return new Di(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,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ji.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new Xl(u);c.set(u,ji.Completed)})}return s}};Qe.ValueScope=Yl});var J=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=Go(),kt=Ql(),vr=Go();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return vr.Name}});var Fi=Ql();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return Fi.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return Fi.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return Fi.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return Fi.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Qt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ed=class extends Qt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?kt.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=Fn(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Li=class extends Qt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Fn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Ui(e,this.rhs)}},td=class extends Li{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},rd=class extends Qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},nd=class extends Qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},od=class extends Qt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},sd=class extends Qt{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=Fn(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Xo=class extends Qt{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)||(JT(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>un(e,r.names),{})}},er=class extends Xo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},id=class extends Xo{},Un=class extends er{};Un.kind="else";var an=class t extends er{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 Un(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Xg(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=Fn(this.condition,e,r),this}get names(){let e=super.names;return Ui(e,this.condition),this.else&&un(e,this.else.names),e}};an.kind="if";var cn=class extends er{};cn.kind="for";var ad=class extends cn{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=Fn(this.iteration,e,r),this}get names(){return un(super.names,this.iteration.names)}},cd=class extends cn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.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=Ui(super.names,this.from);return Ui(e,this.to)}},qi=class extends cn{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=Fn(this.iterable,e,r),this}get names(){return un(super.names,this.iterable.names)}},Yo=class extends er{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)}};Yo.kind="func";var Qo=class extends Xo{render(e){return"return "+super.render(e)}};Qo.kind="return";var ud=class extends er{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&&un(e,this.catch.names),this.finally&&un(e,this.finally.names),e}},es=class extends er{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};es.kind="catch";var ts=class extends er{render(e){return"finally"+super.render(e)}};ts.kind="finally";var ld=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
- `:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new id]}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 ed(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Li(e,r,n))}add(e,r){return this._leafNode(new td(e,W.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new sd(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new an(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 an(e))}else(){return this._elseNode(new Un)}endIf(){return this._endBlockNode(an,Un)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ad(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new cd(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new qi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new qi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(cn)}label(e){return this._leafNode(new rd(e))}break(e){return this._leafNode(new nd(e))}return(e){let r=new Qo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Qo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ud;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new es(s),r(s)}return n&&(this._currNode=o.finally=new ts,this.code(n)),this._endBlockNode(es,ts)}throw(e){return this._leafNode(new od(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new Yo(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Yo)}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 an))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}};W.CodeGen=ld;function un(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ui(t,e){return e instanceof te._CodeOrName?un(t,e.names):t}function Fn(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function JT(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Xg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${dd(t)}`}W.not=Xg;var WT=Yg(W.operators.AND);function KT(...t){return t.reduce(WT)}W.and=KT;var GT=Yg(W.operators.OR);function XT(...t){return t.reduce(GT)}W.or=XT;function Yg(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${dd(e)} ${t} ${dd(r)}`}function dd(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;var de=J(),YT=Go();function QT(t){let e={};for(let r of t)e[r]=!0;return e}K.toHash=QT;function eE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ty(t,e),!ry(e,t.self.RULES.all))}K.alwaysValidSchema=eE;function ty(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]||sy(t,`unknown keyword: "${s}"`)}K.checkUnknownRules=ty;function ry(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}K.schemaHasRules=ry;function tE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}K.schemaHasRulesButRef=tE;function rE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}K.schemaRefOrVal=rE;function nE(t){return ny(decodeURIComponent(t))}K.unescapeFragment=nE;function oE(t){return encodeURIComponent(pd(t))}K.escapeFragment=oE;function pd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=pd;function ny(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=ny;function sE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}K.eachItem=sE;function Qg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof de.Name?(s instanceof de.Name?t(o,s,i):e(o,s,i),i):s instanceof de.Name?(e(o,i,s),s):r(s,i);return a===de.Name&&!(c instanceof de.Name)?n(o,c):c}}K.mergeEvaluated={props:Qg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),md(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:oy}),items:Qg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function oy(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&md(t,r,e),r}K.evaluatedPropsToName=oy;function md(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}K.setEvaluated=md;var ey={};function iE(t,e){return t.scopeValue("func",{ref:e,code:ey[e.code]||(ey[e.code]=new YT._Code(e.code))})}K.useFunc=iE;var fd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(fd||(K.Type=fd={}));function aE(t,e,r){if(t instanceof de.Name){let n=e===fd.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+pd(t)}K.getErrorPath=aE;function sy(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}K.checkStrictMode=sy});var tr=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var je=J(),cE={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};hd.default=cE});var rs=E(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var ne=J(),Hi=re(),Be=tr();Ze.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function uE(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=cy(t,e,r);n??(i||a)?iy(s,c):ay(o,(0,ne._)`[${c}]`)}Ze.reportError=uE;function lE(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=cy(t,e,r);iy(o,a),s||i||ay(n,Be.default.vErrors)}Ze.reportExtraError=lE;function dE(t,e){t.assign(Be.default.errors,e),t.if((0,ne._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ze.resetErrorsCount=dE;function fE({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,ne._)`${Be.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ze.extendErrors=fE;function iy(t,e){let r=t.const("err",e);t.if((0,ne._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Be.default.vErrors}.push(${r})`),t.code((0,ne._)`${Be.default.errors}++`)}function ay(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var ln={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function cy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:pE(t,e,r)}function pE(t,e,r={}){let{gen:n,it:o}=t,s=[mE(o,r),hE(t,r)];return gE(t,e,s),n.object(...s)}function mE({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,Hi.getErrorPath)(e,Hi.Type.Str)}`:t;return[Be.default.instancePath,(0,ne.strConcat)(Be.default.instancePath,r)]}function hE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,Hi.getErrorPath)(r,Hi.Type.Str)}`),[ln.schemaPath,o]}function gE(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([ln.keyword,o],[ln.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([ln.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ln.schema,i],[ln.parentSchema,(0,ne._)`${l}${d}`],[Be.default.data,s]),u&&n.push([ln.propertyName,u])}});var ly=E(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.boolOrEmptySchema=Hn.topBoolOrEmptySchema=void 0;var yE=rs(),_E=J(),vE=tr(),xE={message:"boolean schema is false"};function bE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?uy(t,!1):typeof r=="object"&&r.$async===!0?e.return(vE.default.data):(e.assign((0,_E._)`${n}.errors`,null),e.return(!0))}Hn.topBoolOrEmptySchema=bE;function wE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),uy(t)):r.var(e,!0)}Hn.boolOrEmptySchema=wE;function uy(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,yE.reportError)(o,xE,void 0,e)}});var gd=E(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getRules=Bn.isJSONType=void 0;var $E=["string","number","integer","boolean","null","object","array"],kE=new Set($E);function SE(t){return typeof t=="string"&&kE.has(t)}Bn.isJSONType=SE;function TE(){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:{}}}Bn.getRules=TE});var yd=E(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.shouldUseRule=xr.shouldUseGroup=xr.schemaHasRulesForType=void 0;function EE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&dy(t,n)}xr.schemaHasRulesForType=EE;function dy(t,e){return e.rules.some(r=>fy(t,r))}xr.shouldUseGroup=dy;function fy(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))}xr.shouldUseRule=fy});var ns=E(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var zE=gd(),RE=yd(),PE=rs(),B=J(),py=re(),Vn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Vn||(De.DataType=Vn={}));function IE(t){let e=my(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}De.getSchemaTypes=IE;function my(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=my;function CE(t,e){let{gen:r,data:n,opts:o}=t,s=AE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,RE.schemaHasRulesForType)(t,e[0]));if(i){let a=vd(e,n,o.strictNumbers,Vn.Wrong);r.if(a,()=>{s.length?OE(t,e,s):xd(t)})}return i}De.coerceAndCheckDataType=CE;var hy=new Set(["string","number","integer","boolean","null"]);function AE(t,e){return e?t.filter(r=>hy.has(r)||e==="array"&&r==="array"):[]}function OE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,B._)`typeof ${o}`),a=n.let("coerced",(0,B._)`undefined`);s.coerceTypes==="array"&&n.if((0,B._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,B._)`${o}[0]`).assign(i,(0,B._)`typeof ${o}`).if(vd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,B._)`${a} !== undefined`);for(let u of r)(hy.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),xd(t),n.endIf(),n.if((0,B._)`${a} !== undefined`,()=>{n.assign(o,a),NE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,B._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,B._)`"" + ${o}`).elseIf((0,B._)`${o} === null`).assign(a,(0,B._)`""`);return;case"number":n.elseIf((0,B._)`${i} == "boolean" || ${o} === null
32
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,B._)`+${o}`);return;case"integer":n.elseIf((0,B._)`${i} === "boolean" || ${o} === null
33
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,B._)`+${o}`);return;case"boolean":n.elseIf((0,B._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,B._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,B._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,B._)`${i} === "string" || ${i} === "number"
34
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,B._)`[${o}]`)}}}function NE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,B._)`${e} !== undefined`,()=>t.assign((0,B._)`${e}[${r}]`,n))}function _d(t,e,r,n=Vn.Correct){let o=n===Vn.Correct?B.operators.EQ:B.operators.NEQ,s;switch(t){case"null":return(0,B._)`${e} ${o} null`;case"array":s=(0,B._)`Array.isArray(${e})`;break;case"object":s=(0,B._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,B._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,B._)`typeof ${e} ${o} ${t}`}return n===Vn.Correct?s:(0,B.not)(s);function i(a=B.nil){return(0,B.and)((0,B._)`typeof ${e} == "number"`,a,r?(0,B._)`isFinite(${e})`:B.nil)}}De.checkDataType=_d;function vd(t,e,r,n){if(t.length===1)return _d(t[0],e,r,n);let o,s=(0,py.toHash)(t);if(s.array&&s.object){let i=(0,B._)`typeof ${e} != "object"`;o=s.null?i:(0,B._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=B.nil;s.number&&delete s.integer;for(let i in s)o=(0,B.and)(o,_d(i,e,r,n));return o}De.checkDataTypes=vd;var ME={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,B._)`{type: ${t}}`:(0,B._)`{type: ${e}}`};function xd(t){let e=jE(t);(0,PE.reportError)(e,ME)}De.reportTypeError=xd;function jE(t){let{gen:e,data:r,schema:n}=t,o=(0,py.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var yy=E(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.assignDefaults=void 0;var Jn=J(),ZE=re();function DE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)gy(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>gy(t,s,o.default))}Bi.assignDefaults=DE;function gy(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Jn._)`${s}${(0,Jn.getProperty)(e)}`;if(o){(0,ZE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Jn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Jn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Jn._)`${a} = ${(0,Jn.stringify)(r)}`)}});var pt=E(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ge=J(),bd=re(),br=tr(),LE=re();function qE(t,e){let{gen:r,data:n,it:o}=t;r.if($d(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}le.checkReportMissingProp=qE;function UE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)($d(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}le.checkMissingProp=UE;function FE(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=FE;function _y(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=_y;function wd(t,e,r){return(0,ge._)`${_y(t)}.call(${e}, ${r})`}le.isOwnProperty=wd;function HE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${wd(t,e,r)}`:o}le.propertyInData=HE;function $d(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(wd(t,e,r))):o}le.noPropertyInData=$d;function vy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=vy;function BE(t,e){return vy(e).filter(r=>!(0,bd.alwaysValidSchema)(t,e[r]))}le.schemaProperties=BE;function VE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let m=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${m})`:(0,ge._)`${a}(${m})`}le.callValidateCode=VE;var JE=(0,ge._)`new RegExp`;function WE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?JE:(0,LE.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=WE;function KE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:bd.Type.Num},s),e.if((0,ge.not)(s),a)})}}le.validateArray=KE;function GE(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,bd.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}le.validateUnion=GE});var wy=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.validateKeywordUsage=jt.validSchemaType=jt.funcKeywordCode=jt.macroKeywordCode=void 0;var Ve=J(),dn=tr(),XE=pt(),YE=rs();function QE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=by(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}jt.macroKeywordCode=QE;function ez(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;rz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=by(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&&xy(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&xy(t),h(()=>tz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Ve._)`await `),v=>n.assign(d,!1).if((0,Ve._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ve._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,Ve._)`${l}.errors`;return n.assign(_,null),g(Ve.nil),_}function g(_=e.async?(0,Ve._)`await `:Ve.nil){let v=c.opts.passContext?dn.default.this:dn.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ve._)`${_}${(0,XE.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,Ve.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}jt.funcKeywordCode=ez;function xy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function tz(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(dn.default.vErrors,(0,Ve._)`${dn.default.vErrors} === null ? ${e} : ${dn.default.vErrors}.concat(${e})`).assign(dn.default.errors,(0,Ve._)`${dn.default.vErrors}.length`),(0,YE.extendErrors)(t)},()=>t.error())}function rz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function by(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function nz(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")}jt.validSchemaType=nz;function oz({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)}}jt.validateKeywordUsage=oz});var ky=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var Zt=J(),$y=re();function sz(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,Zt._)`${t.schemaPath}${(0,Zt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Zt._)`${t.schemaPath}${(0,Zt.getProperty)(e)}${(0,Zt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$y.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')}wr.getSubschema=sz;function iz(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,Zt._)`${e.data}${(0,Zt.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Zt.str)`${u}${(0,$y.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Zt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Zt.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]}}wr.extendSubschemaData=iz;function az(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}wr.extendSubschemaMode=az});var kd=E((w4,Sy)=>{"use strict";Sy.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 Ey=E(($4,Ty)=>{"use strict";var $r=Ty.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(){};Vi(e,n,o,t,"",t)};$r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};$r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};$r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};$r.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 Vi(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 $r.arrayKeywords)for(var m=0;m<d.length;m++)Vi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in $r.propsKeywords){if(d&&typeof d=="object")for(var p in d)Vi(t,e,r,d[p],o+"/"+l+"/"+cz(p),s,o,l,n,p)}else(l in $r.keywords||t.allKeys&&!(l in $r.skipKeywords))&&Vi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function cz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var os=E(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var uz=re(),lz=kd(),dz=Ey(),fz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function pz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Sd(t):e?zy(t)<=e:!1}et.inlineRef=pz;var mz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Sd(t){for(let e in t){if(mz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Sd)||typeof r=="object"&&Sd(r))return!0}return!1}function zy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!fz.has(r)&&(typeof t[r]=="object"&&(0,uz.eachItem)(t[r],n=>e+=zy(n)),e===1/0))return 1/0}return e}function Ry(t,e="",r){r!==!1&&(e=Wn(e));let n=t.parse(e);return Py(t,n)}et.getFullPath=Ry;function Py(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=Py;var hz=/#\/?$/;function Wn(t){return t?t.replace(hz,""):""}et.normalizeId=Wn;function gz(t,e,r){return r=Wn(r),t.resolve(e,r)}et.resolveUrl=gz;var yz=/^[a-z_][-a-z0-9._]*$/i;function _z(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Wn(t[r]||e),s={"":o},i=Ry(n,o,!1),a={},c=new Set;return dz(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=Wn(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!==Wn(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!yz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!lz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}et.getSchemaRefs=_z});var as=E(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.getData=kr.KeywordCxt=kr.validateFunctionCode=void 0;var Ny=ly(),Iy=ns(),Ed=yd(),Ji=ns(),vz=yy(),is=wy(),Td=ky(),j=J(),U=tr(),xz=os(),rr=re(),ss=rs();function bz(t){if(Zy(t)&&(Dy(t),jy(t))){kz(t);return}My(t,()=>(0,Ny.topBoolOrEmptySchema)(t))}kr.validateFunctionCode=bz;function My({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${Cy(r,o)}`),$z(t,o),t.code(s)}):t.func(e,(0,j._)`${U.default.data}, ${wz(o)}`,n.$async,()=>t.code(Cy(r,o)).code(s))}function wz(t){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function $z(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,j._)`""`),t.var(U.default.parentData,(0,j._)`undefined`),t.var(U.default.parentDataProperty,(0,j._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function kz(t){let{schema:e,opts:r,gen:n}=t;My(t,()=>{r.$comment&&e.$comment&&qy(t),Rz(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&Sz(t),Ly(t),Cz(t)})}function Sz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function Cy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function Tz(t,e){if(Zy(t)&&(Dy(t),jy(t))){Ez(t,e);return}(0,Ny.boolOrEmptySchema)(t,e)}function jy({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 Zy(t){return typeof t.schema!="boolean"}function Ez(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&qy(t),Pz(t),Iz(t);let s=n.const("_errs",U.default.errors);Ly(t,s),n.var(e,(0,j._)`${s} === ${U.default.errors}`)}function Dy(t){(0,rr.checkUnknownRules)(t),zz(t)}function Ly(t,e){if(t.opts.jtd)return Ay(t,[],!1,e);let r=(0,Iy.getSchemaTypes)(t.schema),n=(0,Iy.coerceAndCheckDataType)(t,r);Ay(t,r,!n,e)}function zz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,rr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Rz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,rr.checkStrictMode)(t,"default is ignored in the schema root")}function Pz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,xz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Iz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,j._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${U.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Cz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),s.unevaluated&&Az(t),e.return((0,j._)`${U.default.errors} === 0`))}function Az({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function Ay(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,rr.schemaHasRulesButRef)(s,l))){o.block(()=>Fy(t,"$ref",l.all.$ref.definition));return}c.jtd||Oz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ed.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Ji.checkDataType)(m.type,i,c.strictNumbers)),Oy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Ji.reportTypeError)(t)),o.endIf()):Oy(t,m),a||o.if((0,j._)`${U.default.errors} === ${n||0}`))}}function Oy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,vz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ed.shouldUseRule)(n,s)&&Fy(t,s.keyword,s.definition,e.type)})}function Oz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Nz(t,e),t.opts.allowUnionTypes||Mz(t,e),jz(t,t.dataTypes))}function Nz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Uy(t.dataTypes,r)||zd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dz(t,e)}}function Mz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zd(t,"use allowUnionTypes to allow union type keyword")}function jz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ed.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Zz(e,i))&&zd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Zz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Uy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dz(t,e){let r=[];for(let n of t.dataTypes)Uy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,rr.checkStrictMode)(t,e,t.opts.strictTypes)}var Wi=class{constructor(e,r,n){if((0,is.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,rr.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",Hy(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,is.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,j.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,j.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,j._)`${r} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ss.reportExtraError:ss.reportError)(this,this.def.error,r)}$dataError(){(0,ss.reportError)(this,this.def.$dataError||ss.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ss.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,j.or)((0,j._)`${o} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ji.checkDataTypes)(c,r,s.opts.strictNumbers,Ji.DataType.Wrong)}`}return j.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,Td.getSubschema)(this.it,e);(0,Td.extendSubschemaData)(n,this.it,e),(0,Td.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Tz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=rr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=rr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,j.Name)),!0}};kr.KeywordCxt=Wi;function Fy(t,e,r,n){let o=new Wi(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,is.funcKeywordCode)(o,r):"macro"in r?(0,is.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,is.funcKeywordCode)(o,r)}var Lz=/^\/(?:[^~]|~0|~1)*$/,qz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Hy(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!Lz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.default.rootData}else{let u=qz.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,j._)`${s}${(0,j.getProperty)((0,rr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}kr.getData=Hy});var Ki=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Rd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Pd.default=Rd});var cs=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Id=os(),Cd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Id.resolveUrl)(e,r,n),this.missingSchema=(0,Id.normalizeId)((0,Id.getFullPath)(e,this.missingRef))}};Ad.default=Cd});var Xi=E(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.resolveSchema=mt.getCompilingSchema=mt.resolveRef=mt.compileSchema=mt.SchemaEnv=void 0;var St=J(),Uz=Ki(),fn=tr(),Tt=os(),By=re(),Fz=as(),Kn=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,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};mt.SchemaEnv=Kn;function Nd(t){let e=Vy.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new St.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Uz.default,code:(0,St._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:fn.default.data,parentData:fn.default.parentData,parentDataProperty:fn.default.parentDataProperty,dataNames:[fn.default.data],dataPathArr:[St.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,St.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:St.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,St._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Fz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(fn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${fn.default.self}`,`${fn.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 St.Name?void 0:f,items:g instanceof St.Name?void 0:g,dynamicProps:f instanceof St.Name,dynamicItems:g instanceof St.Name},p.source&&(p.source.evaluated=(0,St.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)}}mt.compileSchema=Nd;function Hz(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Jz.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 Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Bz.call(this,s)}mt.resolveRef=Hz;function Bz(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Nd.call(this,t)}function Vy(t){for(let e of this._compilations)if(Vz(e,t))return e}mt.getCompilingSchema=Vy;function Vz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Jz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Gi.call(this,t,e)}function Gi(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Od.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Gi.call(this,t,i);return typeof a?.schema!="object"?void 0:Od.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Nd.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new Kn({schema:a,schemaId:c,root:t,baseId:o})}return Od.call(this,r,i)}}mt.resolveSchema=Gi;var Wz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Od(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,By.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Wz.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,By.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Gi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Kn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Jy=E((R4,Kz)=>{Kz.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 qd=E((P4,e_)=>{"use strict";var Gz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jd=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),Xz=RegExp.prototype.test.bind(/^\d*$/u),pn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ky=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Dd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Yz=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)tt[e]="%"+t[e>>4]+t[e&15]}function Le(t){return t<2048?tt[192|t>>6]+tt[128|t&63]:t<65536?tt[224|t>>12]+tt[128|t>>6&63]+tt[128|t&63]:tt[240|t>>18]+tt[128|t>>12&63]+tt[128|t>>6&63]+tt[128|t&63]}function Qz(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 eR=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),tR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),rR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),nR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function oR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!rR(t[e])){if(t[e]==="%"&&e+2<t.length&&pn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Wy(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 sR(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||!jd(c))return;s+=2;continue}if(!eR(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:Wy(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 Wy(i)}function Md(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&&tR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(iR(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),!oR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=sR(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function iR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function aR(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var cR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},uR=/[@/?#:]/g,lR=/[@/?#]/g;function Gy(t,e){let r=e?lR:uR;return r.lastIndex=0,t.replace(r,n=>cR[n])}function Xy(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Zd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function dR(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Zd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Ky(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Qy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function fR(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(pn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),Ky(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=Le(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Le(65536+(i-55296<<10)+(a-56320)),o++):r+=Le(65533)}else r+=Le(65533)}}return r}function Ld(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(pn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=Le(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Le(65536+(s-55296<<10)+(i-56320)),n++):r+=Le(65533)}else r+=Le(65533)}}return r}function Yy(t){return Ld(t,Yz)}function pR(t){return Ld(t,Dd)}function mR(t){return Ld(t,Dd)}function Qy(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(pn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Zd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Dd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=Qy(o)?n:tt[o];else if(o<55296||o>57343)e+=Le(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Le(65536+(o-55296<<10)+(s-56320)),r++):e+=Le(65533)}else e+=Le(65533)}}return e}function gR(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(pn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function yR(t){let e=[];if(t.userinfo!==void 0&&(e.push(Yy(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!jd(r)){let n=Md(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=Xy(r,!0),n=Md(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Gy(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!Xz(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}e_.exports={nonSimpleDomain:nR,recomposeAuthority:yR,reescapeHostDelimiters:Gy,normalizePercentEncoding:Xy,normalizePathEncoding:dR,serializePathEncoding:fR,normalizeQueryFragmentEncoding:hR,encodeUserinfo:Yy,encodeQuery:pR,encodeFragment:mR,escapePreservingEscapes:gR,removeDotSegments:aR,isIPv4:jd,isUUID:Gz,normalizeIPv6:Md,stringArrayToHexStripped:Qz}});var s_=E((I4,o_)=>{"use strict";var{isUUID:_R}=qd(),vR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,xR=["http","https","ws","wss","urn","urn:uuid"];function bR(t){return xR.indexOf(t)!==-1}function Ud(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function t_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function r_(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 wR(t){return t.secure=Ud(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function $R(t){if((t.port===(Ud(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function kR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(vR);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=Fd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function SR(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=Fd(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 TR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!_R(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function ER(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var n_={scheme:"http",domainHost:!0,parse:t_,serialize:r_},zR={scheme:"https",domainHost:n_.domainHost,parse:t_,serialize:r_},Yi={scheme:"ws",domainHost:!0,parse:wR,serialize:$R},RR={scheme:"wss",domainHost:Yi.domainHost,parse:Yi.parse,serialize:Yi.serialize},PR={scheme:"urn",parse:kR,serialize:SR,skipNormalize:!0},IR={scheme:"urn:uuid",parse:TR,serialize:ER,skipNormalize:!0},Qi={http:n_,https:zR,ws:Yi,wss:RR,urn:PR,"urn:uuid":IR};Object.setPrototypeOf(Qi,null);function Fd(t){return t&&(Qi[t]||Qi[t.toLowerCase()])||void 0}o_.exports={wsIsSecure:Ud,SCHEMES:Qi,isValidSchemeName:bR,getSchemeHandler:Fd}});var __=E((C4,ra)=>{"use strict";var{normalizeIPv6:l_,removeDotSegments:ls,recomposeAuthority:CR,normalizePercentEncoding:Hd,normalizePathEncoding:AR,serializePathEncoding:i_,normalizeQueryFragmentEncoding:a_,encodeQuery:OR,encodeFragment:NR,reescapeHostDelimiters:MR,isIPv4:d_,nonSimpleDomain:jR}=qd(),{SCHEMES:f_,getSchemeHandler:Bd}=s_(),p_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,m_="URI scheme is malformed.";function c_(t){let e=unescape(String(t));if(!p_.test(e))throw new TypeError(m_);return e}function ZR(t,e){return typeof t=="string"?t=VR(t,e):typeof t=="object"&&(t=ta(mn(t,e),e)),t}function DR(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}=ea(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=ea(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=h_(o,l,n,!0),_=Bd(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(d_(v)||l_(v).isIPV6);g_(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,mn(h,n)}function h_(t,e,r,n){let o={};return n||(t=ta(mn(t,r),r),e=ta(mn(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=ls(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ls(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ls(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ls(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function LR(t,e,r){let n=u_(t,r),o=u_(e,r);return n!==void 0&&o!==void 0&&n===o}function mn(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=c_(r.scheme));let s=Bd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=Hd(r.path):r.path=i_(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=c_(r.scheme),o.push(r.scheme,":"));let c=CR(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=ls(u)),a&&(u=i_(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",OR(r.query)),r.fragment!==void 0&&o.push("#",NR(r.fragment)),o.join("")}var qR=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,UR=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,FR=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function HR(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 us(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 Vd(t){return t[0]==="["&&t[t.length-1]==="]"}function BR(t){let e=t[4];return us(t[3])||e!==void 0&&!Vd(e)&&us(e)||us(t[6])||us(t[7])||us(t[8])}function g_(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!Vd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&jR(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function ea(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(UR);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(FR);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(qR);if(p){if(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){let h=unescape(n.scheme);p_.test(h)?n.scheme=h.toLowerCase():(n.error=n.error||m_,u=!0)}s=BR(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=HR(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(d_(n.host)===!1){let _=Vd(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=l_(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||"URI host is malformed.",o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let g=Bd(r.scheme||n.scheme);if(c||(a=g_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Hd(n.host,!0);l||(h=Hd(h.toLowerCase())),n.host=MR(h,l)}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=AR(n.path)),n.query&&(n.query=a_(n.query)),n.fragment&&(n.fragment=a_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===f_.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 ta(t,e){return ea(t,e).parsed}function VR(t,e){return y_(t,e).normalized}function y_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=ea(t,e);return{normalized:n||o||s||i||a?t:mn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function u_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:mn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=y_(r,e);return o||s||i||a||c?void 0:n}var Jd={SCHEMES:f_,normalize:ZR,resolve:DR,resolveComponent:h_,equal:LR,serialize:mn,parse:ta};ra.exports=Jd;ra.exports.default=Jd;ra.exports.fastUri=Jd});var x_=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var v_=__();v_.code='require("ajv/dist/runtime/uri").default';Wd.default=v_});var z_=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var JR=as();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return JR.KeywordCxt}});var Gn=J();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var WR=Ki(),S_=cs(),KR=gd(),ds=Xi(),GR=J(),fs=os(),na=ns(),Gd=re(),b_=Jy(),XR=x_(),T_=(t,e)=>new RegExp(t,e);T_.code="new RegExp";var YR=["removeAdditional","useDefaults","coerceTypes"],QR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),eP={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."},tP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w_=200;function rP(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,O,C,ae,ce;let Ee=t.strict,F=(e=t.code)===null||e===void 0?void 0:e.optimize,_e=F===!0||F===void 0?1:F||0,Pt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:T_,Or=(o=t.uriResolver)!==null&&o!==void 0?o:XR.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ee)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ee)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Ee)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Ee)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Ee)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:_e,regExp:Pt}:{optimize:_e,regExp:Pt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:w_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:w_,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:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(C=t.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:Or}}var ps=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,...rP(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new GR.ValueScope({scope:{},prefixes:QR,es5:r,lines:n}),this.logger=cP(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,KR.getRules)(),$_.call(this,eP,e,"NOT SUPPORTED"),$_.call(this,tP,e,"DEPRECATED","warn"),this._metaOpts=iP.call(this),e.formats&&oP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&sP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),nP.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=b_;n==="id"&&(o={...b_},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 S_.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,fs.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=k_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ds.SchemaEnv({schema:{},schemaId:n});if(r=ds.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=k_.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,fs.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(lP.call(this,n,r),!r)return(0,Gd.eachItem)(n,s=>Kd.call(this,s)),this;fP.call(this,r);let o={...r,type:(0,na.getJSONTypes)(r.type),schemaType:(0,na.getJSONTypes)(r.schemaType)};return(0,Gd.eachItem)(n,o.type.length===0?s=>Kd.call(this,s,o):s=>o.type.forEach(i=>Kd.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]=E_(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,fs.normalizeId)(i||n);let u=fs.getSchemaRefs.call(this,e,n);return c=new ds.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):ds.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{ds.compileSchema.call(this,e)}finally{this.opts=r}}};ps.ValidationError=WR.default;ps.MissingRefError=S_.default;Ae.default=ps;function $_(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 k_(t){return t=(0,fs.normalizeId)(t),this.schemas[t]||this.refs[t]}function nP(){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 oP(){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 iP(){let t={...this.opts};for(let e of YR)delete t[e];return t}var aP={log(){},warn(){},error(){}};function cP(t){if(t===!1)return aP;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 uP=/^[a-z_$][a-z0-9_$:-]*$/i;function lP(t,e){let{RULES:r}=this;if((0,Gd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!uP.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 Kd(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,na.getJSONTypes)(e.type),schemaType:(0,na.getJSONTypes)(e.schemaType)}};e.before?dP.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 dP(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 fP(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=E_(e)),t.validateSchema=this.compile(e,!0))}var pP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function E_(t){return{anyOf:[t,pP]}}});var R_=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var mP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xd.default=mP});var A_=E(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.callRef=hn.getValidate=void 0;var hP=cs(),P_=pt(),rt=J(),Xn=tr(),I_=Xi(),oa=re(),gP={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=I_.resolveRef.call(c,u,o,r);if(l===void 0)throw new hP.default(n.opts.uriResolver,o,r);if(l instanceof I_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return sa(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return sa(t,(0,rt._)`${f}.validate`,u,u.$async)}function m(f){let g=C_(t,f);sa(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,rt.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:rt.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function C_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}hn.getValidate=C_;function sa(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Xn.default.this:rt.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,rt._)`await ${(0,P_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,rt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,P_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,rt._)`${f}.errors`;o.assign(Xn.default.vErrors,(0,rt._)`${Xn.default.vErrors} === null ? ${g} : ${Xn.default.vErrors}.concat(${g})`),o.assign(Xn.default.errors,(0,rt._)`${Xn.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=oa.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,rt._)`${f}.evaluated.props`);s.props=oa.mergeEvaluated.props(o,_,s.props,rt.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=oa.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,rt._)`${f}.evaluated.items`);s.items=oa.mergeEvaluated.items(o,_,s.items,rt.Name)}}}hn.callRef=sa;hn.default=gP});var O_=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var yP=R_(),_P=A_(),vP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",yP.default,_P.default];Yd.default=vP});var N_=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var ia=J(),Sr=ia.operators,aa={maximum:{okStr:"<=",ok:Sr.LTE,fail:Sr.GT},minimum:{okStr:">=",ok:Sr.GTE,fail:Sr.LT},exclusiveMaximum:{okStr:"<",ok:Sr.LT,fail:Sr.GTE},exclusiveMinimum:{okStr:">",ok:Sr.GT,fail:Sr.LTE}},xP={message:({keyword:t,schemaCode:e})=>(0,ia.str)`must be ${aa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ia._)`{comparison: ${aa[t].okStr}, limit: ${e}}`},bP={keyword:Object.keys(aa),type:"number",schemaType:"number",$data:!0,error:xP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ia._)`${r} ${aa[e].fail} ${n} || isNaN(${r})`)}};Qd.default=bP});var M_=E(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var ms=J(),wP={message:({schemaCode:t})=>(0,ms.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ms._)`{multipleOf: ${t}}`},$P={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ms._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ms._)`${i} !== parseInt(${i})`;t.fail$data((0,ms._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ef.default=$P});var Z_=E(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});function j_(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}tf.default=j_;j_.code='require("ajv/dist/runtime/ucs2length").default'});var D_=E(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var gn=J(),kP=re(),SP=Z_(),TP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,gn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,gn._)`{limit: ${t}}`},EP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?gn.operators.GT:gn.operators.LT,i=o.opts.unicode===!1?(0,gn._)`${r}.length`:(0,gn._)`${(0,kP.useFunc)(t.gen,SP.default)}(${r})`;t.fail$data((0,gn._)`${i} ${s} ${n}`)}};rf.default=EP});var L_=E(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var zP=pt(),RP=re(),Yn=J(),PP={message:({schemaCode:t})=>(0,Yn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Yn._)`{pattern: ${t}}`},IP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PP,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,Yn._)`new RegExp`:(0,RP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Yn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Yn._)`!${l}`)}else{let c=(0,zP.usePattern)(t,o);t.fail$data((0,Yn._)`!${c}.test(${r})`)}}};nf.default=IP});var q_=E(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var hs=J(),CP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hs._)`{limit: ${t}}`},AP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hs.operators.GT:hs.operators.LT;t.fail$data((0,hs._)`Object.keys(${r}).length ${o} ${n}`)}};of.default=AP});var U_=E(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var gs=pt(),ys=J(),OP=re(),NP={message:({params:{missingProperty:t}})=>(0,ys.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ys._)`{missingProperty: ${t}}`},MP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:NP,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,OP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ys.nil,d);else for(let p of r)(0,gs.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,gs.checkMissingProp)(t,r,p)),(0,gs.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,gs.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,gs.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ys.not)(f),()=>{t.error(),e.break()})},ys.nil)}}};sf.default=MP});var F_=E(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var _s=J(),jP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_s.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_s._)`{limit: ${t}}`},ZP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:jP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?_s.operators.GT:_s.operators.LT;t.fail$data((0,_s._)`${r}.length ${o} ${n}`)}};af.default=ZP});var ca=E(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var H_=kd();H_.code='require("ajv/dist/runtime/equal").default';cf.default=H_});var B_=E(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var uf=ns(),Oe=J(),DP=re(),LP=ca(),qP={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},UP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qP,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,uf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Oe._)`${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,uf.checkDataTypes)(u,h,a.opts.strictNumbers,uf.DataType.Wrong),v=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${f}--;`,()=>{e.let(h,(0,Oe._)`${r}[${f}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${h} == "string"`,(0,Oe._)`${h} += "_"`),e.if((0,Oe._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Oe._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,DP.useFunc)(e,LP.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${f}--;`,()=>e.for((0,Oe._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Oe._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};lf.default=UP});var V_=E(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var df=J(),FP=re(),HP=ca(),BP={message:"must be equal to constant",params:({schemaCode:t})=>(0,df._)`{allowedValue: ${t}}`},VP={keyword:"const",$data:!0,error:BP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,df._)`!${(0,FP.useFunc)(e,HP.default)}(${r}, ${o})`):t.fail((0,df._)`${s} !== ${r}`)}};ff.default=VP});var J_=E(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var vs=J(),JP=re(),WP=ca(),KP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vs._)`{allowedValues: ${t}}`},GP={keyword:"enum",schemaType:"array",$data:!0,error:KP,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,JP.useFunc)(e,WP.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,vs.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,vs._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,vs._)`${u()}(${r}, ${p}[${f}])`:(0,vs._)`${r} === ${g}`}}};pf.default=GP});var W_=E(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var XP=N_(),YP=M_(),QP=D_(),e1=L_(),t1=q_(),r1=U_(),n1=F_(),o1=B_(),s1=V_(),i1=J_(),a1=[XP.default,YP.default,QP.default,e1.default,t1.default,r1.default,n1.default,o1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},s1.default,i1.default];mf.default=a1});var gf=E(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.validateAdditionalItems=void 0;var yn=J(),hf=re(),c1={message:({params:{len:t}})=>(0,yn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,yn._)`{limit: ${t}}`},u1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:c1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,hf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}K_(t,n)}};function K_(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,yn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,yn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,hf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,yn._)`${a} <= ${e.length}`);r.if((0,yn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:hf.Type.Num},u),i.allErrors||r.if((0,yn.not)(u),()=>r.break())})}}xs.validateAdditionalItems=K_;xs.default=u1});var yf=E(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.validateTuple=void 0;var G_=J(),ua=re(),l1=pt(),d1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return X_(t,"additionalItems",e);r.items=!0,!(0,ua.alwaysValidSchema)(r,e)&&t.ok((0,l1.validateArray)(t))}};function X_(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=ua.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,G_._)`${s}.length`);r.forEach((d,m)=>{(0,ua.alwaysValidSchema)(a,d)||(n.if((0,G_._)`${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,ua.checkStrictMode)(a,h,m.strictTuples)}}}bs.validateTuple=X_;bs.default=d1});var Y_=E(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var f1=yf(),p1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,f1.validateTuple)(t,"items")};_f.default=p1});var e0=E(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var Q_=J(),m1=re(),h1=pt(),g1=gf(),y1={message:({params:{len:t}})=>(0,Q_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Q_._)`{limit: ${t}}`},_1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:y1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,m1.alwaysValidSchema)(n,e)&&(o?(0,g1.validateAdditionalItems)(t,o):t.ok((0,h1.validateArray)(t)))}};vf.default=_1});var t0=E(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var ht=J(),la=re(),v1={message:({params:{min:t,max:e}})=>e===void 0?(0,ht.str)`must contain at least ${t} valid item(s)`:(0,ht.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ht._)`{minContains: ${t}}`:(0,ht._)`{minContains: ${t}, maxContains: ${e}}`},x1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:v1,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,ht._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,la.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,la.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,la.alwaysValidSchema)(s,r)){let g=(0,ht._)`${l} >= ${i}`;a!==void 0&&(g=(0,ht._)`${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,ht._)`${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:la.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,ht._)`${g}++`),a===void 0?e.if((0,ht._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ht._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ht._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};xf.default=x1});var o0=E(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.validateSchemaDeps=Dt.validatePropertyDeps=Dt.error=void 0;var bf=J(),b1=re(),ws=pt();Dt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,bf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,bf._)`{property: ${t},
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
32
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,V._)`+${o}`);return;case"integer":n.elseIf((0,V._)`${i} === "boolean" || ${o} === null
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},
35
35
  missingProperty: ${n},
36
36
  depsCount: ${e},
37
- deps: ${r}}`};var w1={keyword:"dependencies",type:"object",schemaType:"object",error:Dt.error,code(t){let[e,r]=$1(t);r0(t,e),n0(t,r)}};function $1({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 r0(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,ws.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,ws.checkReportMissingProp)(t,u)}):(r.if((0,bf._)`${c} && (${(0,ws.checkMissingProp)(t,a,s)})`),(0,ws.reportMissingProp)(t,s),r.else())}}Dt.validatePropertyDeps=r0;function n0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,b1.alwaysValidSchema)(s,e[a])||(r.if((0,ws.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))}Dt.validateSchemaDeps=n0;Dt.default=w1});var i0=E(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var s0=J(),k1=re(),S1={message:"property name must be valid",params:({params:t})=>(0,s0._)`{propertyName: ${t.propertyName}}`},T1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:S1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,k1.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,s0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};wf.default=T1});var kf=E($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var da=pt(),Et=J(),E1=tr(),fa=re(),z1={message:"must NOT have additional properties",params:({params:t})=>(0,Et._)`{additionalProperty: ${t.additionalProperty}}`},R1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:z1,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,fa.alwaysValidSchema)(i,r))return;let u=(0,da.allSchemaProperties)(n.properties),l=(0,da.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Et._)`${s} === ${E1.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,fa.schemaRefOrVal)(i,n.properties,"properties");_=(0,da.isOwnProperty)(e,v,h)}else u.length?_=(0,Et.or)(...u.map(v=>(0,Et._)`${h} === ${v}`)):_=Et.nil;return l.length&&(_=(0,Et.or)(_,...l.map(v=>(0,Et._)`${(0,da.usePattern)(t,v)}.test(${h})`))),(0,Et.not)(_)}function p(h){e.code((0,Et._)`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,fa.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,Et.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,Et.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:fa.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};$f.default=R1});var u0=E(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var P1=as(),a0=pt(),Sf=re(),c0=kf(),I1={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&&c0.default.code(new P1.KeywordCxt(s,c0.default,"additionalProperties"));let i=(0,a0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Sf.mergeEvaluated.props(e,(0,Sf.toHash)(i),s.props));let a=i.filter(d=>!(0,Sf.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,a0.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)}}};Tf.default=I1});var p0=E(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var l0=pt(),pa=J(),d0=re(),f0=re(),C1={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,l0.allSchemaProperties)(r),c=a.filter(g=>(0,d0.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 pa.Name)&&(s.props=(0,f0.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,d0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,pa._)`${(0,l0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:f0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,pa._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,pa.not)(l),()=>e.break())})})}}};Ef.default=C1});var m0=E(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var A1=re(),O1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,A1.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"}};zf.default=O1});var h0=E(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var N1=pt(),M1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:N1.validateUnion,error:{message:"must match a schema in anyOf"}};Rf.default=M1});var g0=E(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var ma=J(),j1=re(),Z1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ma._)`{passingSchemas: ${t.passing}}`},D1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Z1,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,j1.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ma._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ma._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,ma.Name)})})}}};Pf.default=D1});var y0=E(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var L1=re(),q1={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,L1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};If.default=q1});var x0=E(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var ha=J(),v0=re(),U1={message:({params:t})=>(0,ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ha._)`{failingKeyword: ${t.ifClause}}`},F1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:U1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,v0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=_0(n,"then"),s=_0(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,ha.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,ha._)`${l}`):t.setParams({ifClause:l})}}}};function _0(t,e){let r=t.schema[e];return r!==void 0&&!(0,v0.alwaysValidSchema)(t,r)}Cf.default=F1});var b0=E(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var H1=re(),B1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,H1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Af.default=B1});var w0=E(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var V1=gf(),J1=Y_(),W1=yf(),K1=e0(),G1=t0(),X1=o0(),Y1=i0(),Q1=kf(),eI=u0(),tI=p0(),rI=m0(),nI=h0(),oI=g0(),sI=y0(),iI=x0(),aI=b0();function cI(t=!1){let e=[rI.default,nI.default,oI.default,sI.default,iI.default,aI.default,Y1.default,Q1.default,X1.default,eI.default,tI.default];return t?e.push(J1.default,K1.default):e.push(V1.default,W1.default),e.push(G1.default),e}Of.default=cI});var $0=E(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var ke=J(),uI={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},lI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:uI,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,ke._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(h,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(v(),y()));function v(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== 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 O=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,C=r.scopeValue("formats",{key:s,ref:$,code:O});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${C}.validate`]:["string",$,C]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof h=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};Nf.default=lI});var k0=E(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var dI=$0(),fI=[dI.default];Mf.default=fI});var S0=E(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.contentVocabulary=Qn.metadataVocabulary=void 0;Qn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Qn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var E0=E(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var pI=O_(),mI=W_(),hI=w0(),gI=k0(),T0=S0(),yI=[pI.default,mI.default,(0,hI.default)(),gI.default,T0.metadataVocabulary,T0.contentVocabulary];jf.default=yI});var R0=E(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.DiscrError=void 0;var z0;(function(t){t.Tag="tag",t.Mapping="mapping"})(z0||(ga.DiscrError=z0={}))});var I0=E(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var eo=J(),Zf=R0(),P0=Xi(),_I=cs(),vI=re(),xI={message:({params:{discrError:t,tagName:e}})=>t===Zf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,eo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bI={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,eo._)`${r}${(0,eo.getProperty)(a)}`);e.if((0,eo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Zf.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,eo._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Zf.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,eo.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,vI.schemaHasRulesButRef)($,s.self.RULES)){let C=$.$ref;if($=P0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),$ instanceof P0.SchemaEnv&&($=$.schema),$===void 0)throw new _I.default(s.opts.uriResolver,s.baseId,C)}let O=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(O,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 O of x.enum)y(O,$);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]=$}}}};Df.default=bI});var C0=E((xL,wI)=>{wI.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 qf=E((ye,Lf)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var $I=z_(),kI=E0(),SI=I0(),A0=C0(),TI=["/properties"],ya="http://json-schema.org/draft-07/schema",to=class extends $I.default{_addVocabularies(){super._addVocabularies(),kI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(SI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(A0,TI):A0;this.addMetaSchema(e,ya,!1),this.refs["http://json-schema.org/schema"]=ya}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ya)?ya:void 0)}};ye.Ajv=to;Lf.exports=ye=to;Lf.exports.Ajv=to;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=to;var EI=as();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return EI.KeywordCxt}});var ro=J();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return ro._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return ro.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return ro.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return ro.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return ro.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return ro.CodeGen}});var zI=Ki();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return zI.default}});var RI=cs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return RI.default}})});var q0=E(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.formatNames=qt.fastFormats=qt.fullFormats=void 0;function Lt(t,e){return{validate:t,compare:e}}qt.fullFormats={date:Lt(j0,Bf),time:Lt(Ff(!0),Vf),"date-time":Lt(O0(!0),D0),"iso-time":Lt(Ff(),Z0),"iso-date-time":Lt(O0(),L0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:NI,"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:UI,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:MI,int32:{type:"number",validate:DI},int64:{type:"number",validate:LI},float:{type:"number",validate:M0},double:{type:"number",validate:M0},password:!0,binary:!0};qt.fastFormats={...qt.fullFormats,date:Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bf),time:Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Vf),"date-time":Lt(/^\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,D0),"iso-time":Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Z0),"iso-date-time":Lt(/^\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,L0),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};qt.formatNames=Object.keys(qt.fullFormats);function PI(t){return t%4===0&&(t%100!==0||t%400===0)}var II=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function j0(t){let e=II.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&&PI(r)?29:CI[n])}function Bf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Uf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ff(t){return function(r){let n=Uf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function Vf(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 Z0(t,e){if(!(t&&e))return;let r=Uf.exec(t),n=Uf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Hf=/t|\s/i;function O0(t){let e=Ff(t);return function(n){let o=n.split(Hf);return o.length===2&&j0(o[0])&&e(o[1])}}function D0(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function L0(t,e){if(!(t&&e))return;let[r,n]=t.split(Hf),[o,s]=e.split(Hf),i=Bf(r,o);if(i!==void 0)return i||Vf(n,s)}var AI=/\/|:/,OI=/^(?:[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 NI(t){return AI.test(t)&&OI.test(t)}var N0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function MI(t){return N0.lastIndex=0,N0.test(t)}var jI=-(2**31),ZI=2**31-1;function DI(t){return Number.isInteger(t)&&t<=ZI&&t>=jI}function LI(t){return Number.isInteger(t)}function M0(){return!0}var qI=/[^\\]\\Z/;function UI(t){if(qI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var U0=E(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.formatLimitDefinition=void 0;var FI=qf(),zt=J(),Tr=zt.operators,_a={formatMaximum:{okStr:"<=",ok:Tr.LTE,fail:Tr.GT},formatMinimum:{okStr:">=",ok:Tr.GTE,fail:Tr.LT},formatExclusiveMaximum:{okStr:"<",ok:Tr.LT,fail:Tr.GTE},formatExclusiveMinimum:{okStr:">",ok:Tr.GT,fail:Tr.LTE}},HI={message:({keyword:t,schemaCode:e})=>(0,zt.str)`should be ${_a[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,zt._)`{comparison: ${_a[t].okStr}, limit: ${e}}`};no.formatLimitDefinition={keyword:Object.keys(_a),type:"string",schemaType:"string",$data:!0,error:HI,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 FI.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,zt._)`${m}[${c.schemaCode}]`);t.fail$data((0,zt.or)((0,zt._)`typeof ${p} != "object"`,(0,zt._)`${p} instanceof RegExp`,(0,zt._)`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,zt._)`${i.code.formats}${(0,zt.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,zt._)`${m}.compare(${r}, ${n}) ${_a[o].fail} 0`}},dependencies:["format"]};var BI=t=>(t.addKeyword(no.formatLimitDefinition),t);no.default=BI});var V0=E(($s,B0)=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var oo=q0(),VI=U0(),Jf=J(),F0=new Jf.Name("fullFormats"),JI=new Jf.Name("fastFormats"),Wf=(t,e={keywords:!0})=>{if(Array.isArray(e))return H0(t,e,oo.fullFormats,F0),t;let[r,n]=e.mode==="fast"?[oo.fastFormats,JI]:[oo.fullFormats,F0],o=e.formats||oo.formatNames;return H0(t,o,r,n),e.keywords&&(0,VI.default)(t),t};Wf.get=(t,e="full")=>{let n=(e==="fast"?oo.fastFormats:oo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function H0(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Jf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}B0.exports=$s=Wf;Object.defineProperty($s,"__esModule",{value:!0});$s.default=Wf});var Vv={};vo(Vv,{findEmbeddingModel:()=>Bv,ollamaUrl:()=>hp,semanticRerank:()=>zA});import{createHash as yA}from"node:crypto";import{existsSync as _A,mkdirSync as vA,readFileSync as xA,writeFileSync as bA}from"node:fs";import{homedir as wA}from"node:os";import{join as mp}from"node:path";function hp(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 Hv(t,e,r=6e4){let n=await fetch(hp()+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 Bv(t){let r=((await Hv("/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=>$A.test(n))}function Ma(){return mp(process.env.XDG_CACHE_HOME??mp(wA(),".cache"),"context-doctor","embeddings.json")}function kA(){try{return _A(Ma())?JSON.parse(xA(Ma(),"utf8")):{}}catch{return{}}}function SA(t){try{let e=Object.keys(t);if(e.length>Fv)for(let r of e.slice(0,e.length-Fv))delete t[r];vA(mp(Ma(),".."),{recursive:!0}),bA(Ma(),JSON.stringify(t))}catch{}}async function TA(t,e){let r=[];for(let n=0;n<e.length;n+=Uv){let o=await Hv("/api/embed",{model:t,input:e.slice(n,n+Uv),truncate:!0});r.push(...o.embeddings)}return r}function EA(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 zA(t,e,r={}){let n;try{n=await Bv(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${hp()} (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=kA(),s=f=>yA("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 TA(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&&SA(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:EA(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 $A,Uv,Fv,Jv=G(()=>{"use strict";$A=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,Uv=64,Fv=5e4});var qx,Ux=G(()=>{qx="x-hono-already-sent"});var Fx,Hx=G(()=>{Fx=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{Http2ServerRequest as go,constants as uN}from"node:http2";import{Readable as Bx}from"node:stream";async function CN(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function ob(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 Gx(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:ob(t.getReader(),e)}var Ft,lN,dN,fN,pN,mN,hN,yo,Yx,Qx,gN,yN,Ip,Cp,eb,Zp,Vx,Ga,Jx,_N,Ar,sr,_o,Is,tb,rb,Rs,Ap,Op,Cr,Ka,ar,Wx,Ps,Xa,Cs,vN,xN,bN,wN,$N,kN,SN,Dp,TN,Kx,EN,Bt,zN,Ir,Np,ho,ir,Ya,Ht,RN,PN,IN,Mp,Qa,Xx,AN,ON,sb,NN,MN,jN,ib,ec,jp,ab,cb,ZN,Lp,DN,LN,qN,UN,FN,sU,ub=G(()=>{Ux();Hx();Ft=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},lN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,dN=/\/\.\.?(?:[/?#]|$)/,fN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,pN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(fN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Ft("Invalid URL");return!lN.test(r)||dN.test(r)?new URL(n).href:n}else{let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Ft("Invalid host header");return o.href}},mN=t=>t instanceof Ft?t:new Ft(t.message,{cause:t}),hN=global.Request,yo=class extends hN{constructor(t,e){if(typeof t=="object"&&Ar in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[ar]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Ar]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Yx=t=>{let e=[],r=t.rawHeaders;for(let n=0,o=r.length;n<o;n+=2){let s=r[n];s.charCodeAt(0)!==58&&e.push([s,r[n+1]])}return new Headers(e)},Qx=Symbol("wrapBodyStream"),gN=new Set(["latin1","binary","hex","base64","base64url"]),yN=t=>t===null||gN.has(t),Ip=Symbol("bodyBufferedBeforeDisconnect"),Cp=Symbol("bodyBufferedLengthBeforeDisconnect"),eb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Zp=t=>!(t instanceof go)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&yN(t.readableEncoding),Vx=t=>{if(t.readableDidRead||!Zp(t))return;let e=t;e[Cp]??=t.readableLength},Ga=(t,e)=>{if(t.readableDidRead&&!e||!Zp(t))return;let r=t;if(r[Ip]!==void 0)return r[Ip];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Cp]!==void 0&&t.readableLength!==r[Cp])n=Xa();else{let s=e??[],i=t.read();i!==null&&s.push(eb(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=Xa())}}return r[Ip]=n,n},Jx=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},_N=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new yo(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[Qx]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=Ga(n);if(l!==void 0){Jx(a,l);return}}i||=Bx.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=Ga(n);i!==void 0?s.body=new ReadableStream({start(a){Jx(a,i)}}):s.body=Bx.toWeb(n)}return new yo(e,s)},Ar=Symbol("getRequestCache"),sr=Symbol("requestCache"),_o=Symbol("incomingKey"),Is=Symbol("urlKey"),tb=Symbol("methodKey"),rb=Symbol("headersKey"),Rs=Symbol("abortControllerKey"),Ap=Symbol("getAbortController"),Op=Symbol("abortRequest"),Cr=Symbol("bodyBuffer"),Ka=Symbol("bodyReadPromise"),ar=Symbol("bodyConsumedDirectly"),Wx=Symbol("bodyLockReader"),Ps=Symbol("abortReason"),Xa=()=>new TypeError("Body is unusable"),Cs=()=>Promise.reject(Xa()),vN=new TextDecoder,xN=t=>{if(t[ar])return Cs();t[ar]=!0},bN=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),wN=t=>(t[rb]||=Yx(t[_o])).get("content-type")||"",$N=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,kN=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}},SN=t=>{if(!$N.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.`)},Dp=(t,e,r)=>{if(t[ar])return Cs();let n=t.method;if(n==="GET"||n==="HEAD")return t[Ar]()[e]();let o=SN(n);if(o)return Promise.reject(o);if(t[sr]&&n!=="TRACE")return t[sr][e]();let s=xN(t);if(s)return s;let i=TN(t);if(i){let a=Promise.resolve(r(i,t));return t[Cr]=void 0,a}return EN(t).then(a=>{let c=r(a,t);return t[Cr]=void 0,c})},TN=t=>{let e=t[_o];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},Kx=(t,e)=>{if(e.errored)return e.errored;let r=t[Ps];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},EN=t=>{if(t[Cr])return Promise.resolve(t[Cr]);if(t[Ka])return t[Ka];let e=t[_o];if(e.readableDidRead)return Cs();let r=Ga(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Cr]=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!Zp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=Ga(e,i);_ instanceof Error?s(_):_===void 0?s(g??Kx(t,e)):(t[Cr]=_,o(_))}),!0)},l=g=>{i.push(eb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[Cr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(Kx(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[Ka]=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[Ka]=n,n},Bt={get method(){return this[tb]},get url(){return this[Is]},get headers(){return this[rb]||=Yx(this[_o])},[Op](t){this[Ps]===void 0&&(this[Ps]=t);let e=this[Rs];e&&!e.signal.aborted&&e.abort(t)},[Ap](){return this[Rs]||=new AbortController,this[Ps]!==void 0&&!this[Rs].signal.aborted&&this[Rs].abort(this[Ps]),this[Rs]},[Ar](){let t=this[Ap]();if(this[sr])return this[sr];let e=this.method;if(this[ar]&&!(e==="GET"||e==="HEAD")){this[Cr]=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 yo(this[Is],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[sr]=n}return this[sr]=_N(this.method,this[Is],this.headers,this[_o],t)},get body(){if(!this[ar])return this[Ar]().body;let t=this[Ar]();return!this[Wx]&&t.body&&(this[Wx]=t.body.getReader()),t.body},get bodyUsed(){return this[ar]?!0:this[sr]?this[sr].bodyUsed:!1}};Object.defineProperty(Bt,"signal",{get(){return this[Ap]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Bt,t,{get(){return this[Ar]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Bt,t,{value:function(){if(this[ar]){if(t==="clone")throw Xa();return Cs()}return this[Ar]()[t]()}})});Object.defineProperty(Bt,"text",{value:function(){return Dp(this,"text",t=>vN.decode(t))}});Object.defineProperty(Bt,"arrayBuffer",{value:function(){return Dp(this,"arrayBuffer",t=>bN(t))}});Object.defineProperty(Bt,"blob",{value:function(){return Dp(this,"blob",(t,e)=>{let r=wN(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Bt,"json",{value:function(){return this[ar]?Cs():this.text().then(JSON.parse)}});Object.defineProperty(Bt,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[sr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Bt,yo.prototype);zN=(t,e)=>{let r=Object.create(Bt);r[_o]=t,r[tb]=kN(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof go)throw new Ft("Absolute URL for :path is not allowed in HTTP/2");try{r[Is]=new URL(n).href}catch(i){throw new Ft("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof go?t.authority:t.headers.host)||e;if(!o)throw new Ft("Missing host header");let s;if(t instanceof go){if(s=t.scheme,!(s==="http"||s==="https"))throw new Ft("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Is]=pN(s,o,n)}catch(i){throw i instanceof Ft?i:new Ft("Invalid URL",{cause:i})}return r},Ir="text/plain; charset=UTF-8",Np=Symbol("responseCache"),ho=Symbol("getResponseCache"),ir=Symbol("cache"),Ya=global.Response,Ht=class nb{#e;#t;[ho](){let e=this[ir],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[ir],this[Np]||=new Ya(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 Ya){let o=r[Np];if(o){this.#t=o,this[ho]();return}this.#t=r instanceof nb?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[ir]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[ir];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Ir}))),e[2]):this[ho]().headers}get status(){return this[ir]?.[0]??this[ho]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Ht.prototype,t,{get(){return this[ho]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Ht.prototype,t,{value:function(){return this[ho]()[t]()}})});Object.defineProperty(Ht.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[Np]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Ht,Ya);Object.setPrototypeOf(Ht.prototype,Ya.prototype);RN=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,PN=t=>t instanceof URL?t.href:RN.test(t)?t:new URL(t).href,IN=new Set([301,302,303,307,308]);Object.defineProperty(Ht,"redirect",{value:function(e,r=302){if(!IN.has(r))throw new RangeError("Invalid status code");return new Ht(null,{status:r,headers:{location:PN(e)}})},writable:!0,configurable:!0});Object.defineProperty(Ht,"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 Ht(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Mp=(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},Qa=Symbol("outgoingEnded"),Xx=Symbol("incomingDraining"),AN=500,ON=64*1024*1024,sb=t=>{let e=t;if(t.destroyed||e[Xx])return;if(e[Xx]=!0,t instanceof go){try{t.stream?.close?.(uN.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,AN);s.unref?.();let i=a=>{r+=a.length,r>ON&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},NN=(t,e,r,n)=>()=>{e.errored?(Vx(e),t[Op](e.errored.toString())):r.writableFinished||(Vx(e),t[Op]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{sb(e)})})},MN=t=>{if(!(ir in t))return!1;let e=t[ir][1];return e===null||typeof e=="string"||e instanceof Uint8Array},jN=()=>new Response(null,{status:400}),ib=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),ec=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},jp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},ab=async(t,e)=>{let[r,n,o]=t[ir];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":Buffer.byteLength(n)}),e.end(n)):n instanceof Uint8Array?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":n.byteLength}),e.end(n)):n instanceof Blob?(e.writeHead(r,{"Content-Type":Ir,"Content-Length":n.size}),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Ir}),jp(e),await Gx(n,e)?.catch(i=>ec(i,e))),e[Qa]?.();return}let s=!1;if(o instanceof Headers)s=o.has("content-length"),o=Mp(o,n===null?void 0:Ir);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Mp(i,n===null?void 0:Ir)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(jp(e),await Gx(n,e)?.catch(i=>ec(i,e))),e[Qa]?.()},cb=t=>typeof t.then=="function",ZN=async(t,e,r={})=>{if(cb(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(ib);if(ir in t)return ab(t,e);let n=Mp(t.headers,t.body===null?void 0:Ir);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 CN(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&&jp(e),await ob(o,e,a))}else n[qx]||(e.writeHead(t.status,n),e.end());e[Qa]?.()},Lp=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==yo&&(Object.defineProperty(global,"Request",{value:yo}),Object.defineProperty(global,"Response",{value:Ht})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",NN(i,n,o,a)))};try{if(i=zN(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Qx]=!0,n instanceof go&&(o[Qa]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!cb(s)&&MN(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||sb(n)}),ab(s,o);u()}catch(l){if(s)return ec(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:mN(l)),!s)return}else i?s=ib(l):s=jN()}try{return await ZN(s,o,e)}catch(l){return ec(l,o)}}},DN=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??""}},LN=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}},qN=()=>Symbol("connection"),UN=Symbol("CONNECTION_SYMBOL_KEY"),FN=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),sU=Fx(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[FN];if(!o||!n.incoming)return new Response(null,{status:500});let s=qN();return n[UN]=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 DN("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new LN("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var pb=E(qp=>{"use strict";var lb=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,HN=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,db=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,BN=/\\([\u000b\u0020-\u00ff])/g,VN=/([\\"])/g,fb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;qp.format=JN;qp.parse=WN;function JN(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!fb.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],!db.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+GN(e[o])}return n}function WN(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?KN(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(!fb.test(n))throw new TypeError("invalid media type");var o=new XN(n.toLowerCase());if(r!==-1){var s,i,a;for(lb.lastIndex=r;i=lb.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(BN,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function KN(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 GN(t){var e=String(t);if(db.test(e))return e;if(e.length>0&&!HN.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(VN,"\\$1")+'"'}function XN(t){this.parameters=Object.create(null),this.type=t}});function YN(t){if(t)try{return mb.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:YN(t)==="application/json"}var mb,gb=G(()=>{mb=oc(pb(),1)});function yb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function _b(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 vb(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 xb=G(()=>{});function bb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var wb=G(()=>{});var tc,$b=G(()=>{gb();xb();wb();yr();tc=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=_b(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=bb(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
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
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(!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 vb(e,this._maxRequestBodySize);if(v.tooLarge){let y=yb(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=>Zo.parse(v)):a=[Zo.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(Pl);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(Xt)){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=>Pl(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??Qh;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)Xt(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)Xt(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;Xt(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)Xt(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&&!Mn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Mn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Mn.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((Yt(e)||jn(e))&&(n=e.id),n===void 0){if(Yt(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(Yt(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 kb={};vo(kb,{StreamableHTTPServerTransport:()=>Fp});var Fp,Sb=G(()=>{ub();$b();Fp=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new tc(e),this._requestListener=Lp(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 Lp(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var Z={};vo(Z,{BRAND:()=>aw,DIRTY:()=>Mr,EMPTY_PATH:()=>Db,INVALID:()=>D,NEVER:()=>Hw,OK:()=>Me,ParseStatus:()=>Re,Schema:()=>V,ZodAny:()=>lr,ZodArray:()=>Kt,ZodBigInt:()=>Zr,ZodBoolean:()=>Dr,ZodBranded:()=>bo,ZodCatch:()=>Gr,ZodDate:()=>Lr,ZodDefault:()=>Kr,ZodDiscriminatedUnion:()=>Ms,ZodEffects:()=>ut,ZodEnum:()=>Jr,ZodError:()=>We,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Zs,ZodIntersection:()=>Hr,ZodIssueCode:()=>k,ZodLazy:()=>Br,ZodLiteral:()=>Vr,ZodMap:()=>Tn,ZodNaN:()=>zn,ZodNativeEnum:()=>Wr,ZodNever:()=>xt,ZodNull:()=>Ur,ZodNullable:()=>At,ZodNumber:()=>jr,ZodObject:()=>Ge,ZodOptional:()=>Ke,ZodParsedType:()=>R,ZodPipeline:()=>wo,ZodPromise:()=>dr,ZodReadonly:()=>Xr,ZodRecord:()=>js,ZodSchema:()=>V,ZodSet:()=>En,ZodString:()=>ur,ZodSymbol:()=>kn,ZodTransformer:()=>ut,ZodTuple:()=>Ct,ZodType:()=>V,ZodUndefined:()=>qr,ZodUnion:()=>Fr,ZodUnknown:()=>Wt,ZodVoid:()=>Sn,addIssueToContext:()=>T,any:()=>gw,array:()=>xw,bigint:()=>dw,boolean:()=>rm,coerce:()=>Fw,custom:()=>Qp,date:()=>fw,datetimeRegex:()=>Xp,defaultErrorMap:()=>Vt,discriminatedUnion:()=>$w,effect:()=>Nw,enum:()=>Cw,function:()=>Rw,getErrorMap:()=>bn,getParsedType:()=>It,instanceof:()=>uw,intersection:()=>kw,isAborted:()=>Os,isAsync:()=>wn,isDirty:()=>Ns,isValid:()=>cr,late:()=>cw,lazy:()=>Pw,literal:()=>Iw,makeIssue:()=>xo,map:()=>Ew,nan:()=>lw,nativeEnum:()=>Aw,never:()=>_w,null:()=>hw,nullable:()=>jw,number:()=>tm,object:()=>cc,objectUtil:()=>sc,oboolean:()=>Uw,onumber:()=>qw,optional:()=>Mw,ostring:()=>Lw,pipeline:()=>Dw,preprocess:()=>Zw,promise:()=>Ow,quotelessJson:()=>Mb,record:()=>Tw,set:()=>zw,setErrorMap:()=>Zb,strictObject:()=>bw,string:()=>em,symbol:()=>pw,transformer:()=>Nw,tuple:()=>Sw,undefined:()=>mw,union:()=>ww,unknown:()=>yw,util:()=>X,void:()=>vw});var X;(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})(X||(X={}));var sc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(sc||(sc={}));var R=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),It=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var k=X.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"]),Mb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),We=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,X.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()}};We.create=t=>new We(t);var jb=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,X.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${X.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${X.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${X.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}"`:X.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,X.assertNever(t)}return{message:r}},Vt=jb;var Vp=Vt;function Zb(t){Vp=t}function bn(){return Vp}var xo=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}},Db=[];function T(t,e){let r=bn(),n=xo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Vt?void 0:Vt].filter(o=>!!o)});t.common.issues.push(n)}var Re=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return D;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return D;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},D=Object.freeze({status:"aborted"}),Mr=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Os=t=>t.status==="aborted",Ns=t=>t.status==="dirty",cr=t=>t.status==="valid",wn=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var ct=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}},Jp=(t,e)=>{if(cr(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 We(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return It(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Re,ctx:{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(wn(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:It(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Jp(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:It(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return cr(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=>cr(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:It(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(wn(o)?o:Promise.resolve(o));return Jp(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 ut({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 Ke.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return dr.create(this,this._def)}or(e){return Fr.create([this,e],this._def)}and(e){return Hr.create(this,e,this._def)}transform(e){return new ut({...H(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Kr({...H(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new bo({typeName:S.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Gr({...H(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return wo.create(this,e)}readonly(){return Xr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lb=/^c[^\s-]{8,}$/i,qb=/^[0-9a-z]+$/,Ub=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fb=/^[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,Hb=/^[a-z0-9_-]{21}$/i,Bb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Vb=/^[-+]?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)?)??$/,Jb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ic,Kb=/^(?:(?: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])$/,Gb=/^(?:(?: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])$/,Xb=/^(([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]))$/,Yb=/^(([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])$/,Qb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ew=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kp="((\\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])))",tw=new RegExp(`^${Kp}$`);function Gp(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 rw(t){return new RegExp(`^${Gp(t)}$`)}function Xp(t){let e=`${Kp}T${Gp(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 nw(t,e){return!!((e==="v4"||!e)&&Kb.test(t)||(e==="v6"||!e)&&Xb.test(t))}function ow(t,e){if(!Bb.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 sw(t,e){return!!((e==="v4"||!e)&&Gb.test(t)||(e==="v6"||!e)&&Yb.test(t))}var ur=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.string,received:s.parsedType}),D}let n=new Re,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Jb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ic||(ic=new RegExp(Wb,"u")),ic.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Fb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Hb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Lb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")qb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Ub.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Xp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?tw.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?rw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Vb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?nw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ow(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?sw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Qb.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ew.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):X.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,...N.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.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}};ur.create=t=>new ur({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...H(t)});function iw(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 jr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.number,received:s.parsedType}),D}let n,o=new Re;for(let s of this._def.checks)s.kind==="int"?X.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?iw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_finite,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&X.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)}};jr.create=t=>new jr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Zr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,o=new Re;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):X.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.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:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.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}};Zr.create=t=>new Zr({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Dr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.boolean,received:n.parsedType}),D}return Me(e.data)}};Dr.create=t=>new Dr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Lr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.date,received:s.parsedType}),D}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),D}let n=new Re,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):X.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:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.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}};Lr.create=t=>new Lr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...H(t)});var kn=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.symbol,received:n.parsedType}),D}return Me(e.data)}};kn.create=t=>new kn({typeName:S.ZodSymbol,...H(t)});var qr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.undefined,received:n.parsedType}),D}return Me(e.data)}};qr.create=t=>new qr({typeName:S.ZodUndefined,...H(t)});var Ur=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.null,received:n.parsedType}),D}return Me(e.data)}};Ur.create=t=>new Ur({typeName:S.ZodNull,...H(t)});var lr=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};lr.create=t=>new lr({typeName:S.ZodAny,...H(t)});var Wt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};Wt.create=t=>new Wt({typeName:S.ZodUnknown,...H(t)});var xt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.never,received:r.parsedType}),D}};xt.create=t=>new xt({typeName:S.ZodNever,...H(t)});var Sn=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.void,received:n.parsedType}),D}return Me(e.data)}};Sn.create=t=>new Sn({typeName:S.ZodVoid,...H(t)});var Kt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:k.invalid_type,expected:R.array,received:r.parsedType}),D;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ct(r,i,r.path,a)))).then(i=>Re.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ct(r,i,r.path,a)));return Re.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...H(e)});function $n(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ke.create($n(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:$n(t.element)}):t instanceof Ke?Ke.create($n(t.unwrap())):t instanceof At?At.create($n(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>$n(e))):t}var Ge=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=X.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),D}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof xt&&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 ct(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof xt){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&&(T(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ct(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=>Re.mergeObjectSync(n,u)):Re.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.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:N.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 X.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 X.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return $n(this)}partial(e){let r={};for(let n of X.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 X.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ke;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Yp(X.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:xt.create(),typeName:S.ZodObject,...H(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:xt.create(),typeName:S.ZodObject,...H(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:xt.create(),typeName:S.ZodObject,...H(e)});var Fr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new We(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},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 We(c));return T(r,{code:k.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Fr.create=(t,e)=>new Fr({options:t,typeName:S.ZodUnion,...H(e)});var Jt=t=>t instanceof Br?Jt(t.schema):t instanceof ut?Jt(t.innerType()):t instanceof Vr?[t.value]:t instanceof Jr?t.options:t instanceof Wr?X.objectValues(t.enum):t instanceof Kr?Jt(t._def.innerType):t instanceof qr?[void 0]:t instanceof Ur?[null]:t instanceof Ke?[void 0,...Jt(t.unwrap())]:t instanceof At?[null,...Jt(t.unwrap())]:t instanceof bo||t instanceof Xr?Jt(t.unwrap()):t instanceof Gr?Jt(t._def.innerType):[],Ms=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:k.invalid_type,expected:R.object,received:r.parsedType}),D;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Jt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...H(n)})}};function ac(t,e){let r=It(t),n=It(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=X.objectKeys(e),s=X.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=ac(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.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=ac(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Hr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Os(s)||Os(i))return D;let a=ac(s.value,i.value);return a.valid?((Ns(s)||Ns(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Hr.create=(t,e,r)=>new Hr({left:t,right:e,typeName:S.ZodIntersection,...H(r)});var Ct=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ct(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Re.mergeArray(r,i)):Re.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:S.ZodTuple,rest:null,...H(e)})};var js=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),D;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ct(n,a,n.path,a)),value:i._parse(new ct(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Re.mergeObjectAsync(r,o):Re.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...H(n)}):new t({keyType:ur.create(),valueType:e,typeName:S.ZodRecord,...H(r)})}},Tn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:k.invalid_type,expected:R.map,received:n.parsedType}),D;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ct(n,a,n.path,[u,"key"])),value:s._parse(new ct(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 D;(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 D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Tn.create=(t,e,r)=>new Tn({valueType:e,keyType:t,typeName:S.ZodMap,...H(r)});var En=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:k.invalid_type,expected:R.set,received:n.parsedType}),D;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return D;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 ct(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:N.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};En.create=(t,e)=>new En({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...H(e)});var Zs=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:k.invalid_type,expected:R.function,received:r.parsedType}),D;function n(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,bn(),Vt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,bn(),Vt].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 dr){let a=this;return Me(async function(...c){let u=new We([]),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 Me(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new We([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new We([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:Ct.create(e).rest(Wt.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||Ct.create([]).rest(Wt.create()),returns:r||Wt.create(),typeName:S.ZodFunction,...H(n)})}},Br=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Br.create=(t,e)=>new Br({getter:t,typeName:S.ZodLazy,...H(e)});var Vr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Vr.create=(t,e)=>new Vr({value:t,typeName:S.ZodLiteral,...H(e)});function Yp(t,e){return new Jr({values:t,typeName:S.ZodEnum,...H(e)})}var Jr=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:X.joinValues(n),received:r.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:k.invalid_enum_value,options:n}),D}return Me(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Jr.create=Yp;var Wr=class extends V{_parse(e){let r=X.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=X.objectValues(r);return T(n,{expected:X.joinValues(o),received:n.parsedType,code:k.invalid_type}),D}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=X.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:o}),D}return Me(e.data)}get enum(){return this._def.values}};Wr.create=(t,e)=>new Wr({values:t,typeName:S.ZodNativeEnum,...H(e)});var dr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:R.promise,received:r.parsedType}),D;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Me(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};dr.create=(t,e)=>new dr({type:t,typeName:S.ZodPromise,...H(e)});var ut=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Mr(c.value):r.value==="dirty"?Mr(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?Mr(a.value):r.value==="dirty"?Mr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!cr(i))return D;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>cr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):D);X.assertNever(o)}};ut.create=(t,e,r)=>new ut({schema:t,typeName:S.ZodEffects,effect:e,...H(r)});ut.createWithPreprocess=(t,e,r)=>new ut({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...H(r)});var Ke=class extends V{_parse(e){return this._getType(e)===R.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(t,e)=>new Ke({innerType:t,typeName:S.ZodOptional,...H(e)});var At=class extends V{_parse(e){return this._getType(e)===R.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};At.create=(t,e)=>new At({innerType:t,typeName:S.ZodNullable,...H(e)});var Kr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Gr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return wn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new We(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gr.create=(t,e)=>new Gr({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var zn=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};zn.create=t=>new zn({typeName:S.ZodNaN,...H(t)});var aw=Symbol("zod_brand"),bo=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},wo=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),Mr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},Xr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(cr(o)&&(o.value=Object.freeze(o.value)),o);return wn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Xr.create=(t,e)=>new Xr({innerType:t,typeName:S.ZodReadonly,...H(e)});function Wp(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Qp(t,e={},r){return t?lr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Wp(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Wp(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):lr.create()}var cw={object:Ge.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var uw=(t,e={message:`Input not instance of ${t.name}`})=>Qp(r=>r instanceof t,e),em=ur.create,tm=jr.create,lw=zn.create,dw=Zr.create,rm=Dr.create,fw=Lr.create,pw=kn.create,mw=qr.create,hw=Ur.create,gw=lr.create,yw=Wt.create,_w=xt.create,vw=Sn.create,xw=Kt.create,cc=Ge.create,bw=Ge.strictCreate,ww=Fr.create,$w=Ms.create,kw=Hr.create,Sw=Ct.create,Tw=js.create,Ew=Tn.create,zw=En.create,Rw=Zs.create,Pw=Br.create,Iw=Vr.create,Cw=Jr.create,Aw=Wr.create,Ow=dr.create,Nw=ut.create,Mw=Ke.create,jw=At.create,Zw=ut.createWithPreprocess,Dw=wo.create,Lw=()=>em().optional(),qw=()=>tm().optional(),Uw=()=>rm().optional(),Fw={string:(t=>ur.create({...t,coerce:!0})),number:(t=>jr.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>Zr.create({...t,coerce:!0})),date:(t=>Lr.create({...t,coerce:!0}))};var Hw=D;Ue();Ue();Ue();Ue();var Q$=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(t,e),t.def=e,t.parse=(r,n)=>$c(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>en(t,r,n),t.parseAsync=async(r,n)=>Sc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>tn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>st(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var ek=w("ZodMiniObject",(t,e)=>{Gs.init(t,e),Q$.init(t,e),Y.defineLazy(t,"shape",()=>e.shape)});function dl(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new ek(r)}Ue();Ys();function Mt(t){return!!t._zod}function on(t){let e=Object.values(t);if(e.length===0)return dl({});let r=e.every(Mt),n=e.every(o=>!Mt(o));if(r)return dl(t);if(n)return cc(t);throw new Error("Mixed Zod versions detected in object shape.")}function mr(t,e){return Mt(t)?en(t,e):t.safeParse(e)}async function ii(t,e){return Mt(t)?await tn(t,e):await t.safeParseAsync(e)}function hr(t){if(!t)return;let e;if(Mt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function An(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 on(t)}}if(Mt(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 rk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ai(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 ${rk(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 kh(t){return t.description}function Sh(t){if(Mt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function On(t){if(Mt(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}yr();function _r(t){return t==="completed"||t==="failed"||t==="cancelled"}var gg=Symbol("Let zodToJsonSchema decide on which parser to use");var hg={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"},yg=t=>typeof t=="string"?{...hg,name:t}:{...hg,...t};var _g=t=>{let e=yg(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 ql(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,ql(t,e,n,o)}var Ci=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ci(e,t.currentPath):e.join("/")}}function vg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function xg(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function bg(){return{type:"boolean"}}function Ai(t,e){return q(t.type._def,e)}var wg=(t,e)=>q(t.innerType._def,e);function Ul(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Ul(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zT(t,e)}}var zT=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function $g(t,e){return{...q(t.innerType._def,e),default:t.defaultValue()}}function kg(t,e){return e.effectStrategy==="input"?q(t.schema._def,e):we(e)}function Sg(t){return{type:"string",enum:Array.from(t.values)}}var RT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Tg(t,e){let r=[q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),q(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(RT(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 Eg(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 Fl,wt={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:()=>(Fl===void 0&&(Fl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fl),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 Oi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":$t(r,"email",n.message,e);break;case"format:idn-email":$t(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,wt.email,n.message,e);break}break;case"url":$t(r,"uri",n.message,e);break;case"uuid":$t(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,wt.cuid,n.message,e);break;case"cuid2":He(r,wt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${Hl(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${Hl(n.value,e)}$`),n.message,e);break;case"datetime":$t(r,"date-time",n.message,e);break;case"date":$t(r,"date",n.message,e);break;case"time":$t(r,"time",n.message,e);break;case"duration":$t(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(Hl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&$t(r,"ipv4",n.message,e),n.version!=="v4"&&$t(r,"ipv6",n.message,e);break}case"base64url":He(r,wt.base64url,n.message,e);break;case"jwt":He(r,wt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,wt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,wt.ipv6Cidr,n.message,e);break}case"emoji":He(r,wt.emoji(),n.message,e);break;case"ulid":{He(r,wt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{$t(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,wt.base64,n.message,e);break}}break}case"nanoid":He(r,wt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Hl(t,e){return e.patternStrategy==="escape"?IT(t):t}var PT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function IT(t){let e="";for(let r=0;r<t.length;r++)PT.has(t[r])||(e+="\\"),e+=t[r];return e}function $t(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zg(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",zg(e,n),r,n)}function zg(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(!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
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 Ni(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Oi(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}=Ai(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Rg(t,e){if(e.mapStrategy==="record")return Ni(t,e);let r=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Pg(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 Ig(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Cg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Og(t,e){if(e.target==="openApi3")return Ag(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Jo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Jo[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 Ag(t,e)}var Ag=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Ng(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:Jo[t.innerType._def.typeName],nullable:!0}:{type:[Jo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Mg(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",ql(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function jg(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=AT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=q(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=CT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function CT(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function AT(t){try{return t.isOptional()}catch{return!0}}var Zg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Dg=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let r=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Lg(t,e){return q(t.type._def,e)}function qg(t,e){let n={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ug(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Fg(t){return{not:we(t)}}function Hg(t){return we(t)}var Bg=(t,e)=>q(t.innerType._def,e);var Vg=(t,e,r)=>{switch(e){case S.ZodString:return Oi(t,r);case S.ZodNumber:return Mg(t,r);case S.ZodObject:return jg(t,r);case S.ZodBigInt:return xg(t,r);case S.ZodBoolean:return bg();case S.ZodDate:return Ul(t,r);case S.ZodUndefined:return Fg(r);case S.ZodNull:return Cg(r);case S.ZodArray:return vg(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Og(t,r);case S.ZodIntersection:return Tg(t,r);case S.ZodTuple:return Ug(t,r);case S.ZodRecord:return Ni(t,r);case S.ZodLiteral:return Eg(t,r);case S.ZodEnum:return Sg(t);case S.ZodNativeEnum:return Pg(t);case S.ZodNullable:return Ng(t,r);case S.ZodOptional:return Zg(t,r);case S.ZodMap:return Rg(t,r);case S.ZodSet:return qg(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return Lg(t,r);case S.ZodNaN:case S.ZodNever:return Ig(r);case S.ZodEffects:return kg(t,r);case S.ZodAny:return we(r);case S.ZodUnknown:return Hg(r);case S.ZodDefault:return $g(t,r);case S.ZodBranded:return Ai(t,r);case S.ZodReadonly:return Bg(t,r);case S.ZodCatch:return wg(t,r);case S.ZodPipeline:return Dg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==gg)return a}if(n&&!r){let a=OT(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=Vg(t,t.typeName,e),i=typeof s=="function"?q(s(),e):s;if(i&&NT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var OT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ci(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},NT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Bl=(t,e)=>{let r=_g(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:q(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function MT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Vl(t,e){return Mt(t)?ll(t,{target:MT(e?.target),io:e?.pipeStrategy??"input"}):Bl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Jl(t){let r=hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=On(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wl(t,e){let r=mr(t,e);if(!r.success)throw r.error;return r.data}var jT=6e4,Mi=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(mi,r=>{this._oncancel(r)}),this.setNotificationHandler(yi,r=>{this._onprogress(r)}),this.setRequestHandler(gi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(_i,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(xi,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new I(A.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 I(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 I(A.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,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(bi,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler($i,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(_r(o.status))throw new I(A.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 I(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(A.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(A.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),Yt(s)||jn(s)?this._onresponse(s):Xt(s)?this._onrequest(s,i):sg(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(A.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?.[gr]?.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 I(A.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:A.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=rg(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 I(A.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 I(A.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:A.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),Yt(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Yt(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),Yt(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(A.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Zn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(A.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 I(A.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(A.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(A.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||{},[gr]: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 I?v:new I(A.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=mr(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??jT,h=()=>f(I.fromError(A.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},vi,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},wi,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ag,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||{},[gr]: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||{},[gr]: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||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Jl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Wl(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=Jl(e);this._notificationHandlers.set(n,o=>{let s=Wl(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"&&Xt(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(A.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 I(A.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new I(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(A.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=Fo.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 I(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(_r(a.status))throw new I(A.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=Fo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),_r(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Jg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Wg(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];Jg(i)&&Jg(s)?r[o]={...i,...s}:r[o]=s}return r}yr();var J0=oc(qf(),1),W0=oc(V0(),1);function WI(){let t=new J0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,W0.default)(t),t}var va=class{constructor(e){this._ajv=e??WI()}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)}}};yr();var xa=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},Vo,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},qn,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 K0(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 G0(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 ba=class extends Mi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Bo.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 va,this.setRequestHandler(hi,n=>this._oninitialize(n)),this.setNotificationHandler(Il,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Bo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Wg(this._capabilities,e)}setRequestHandler(e,r){let o=hr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=On(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=mr(Ln,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new I(A.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=mr(Zn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new I(A.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=mr(Pi,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new I(A.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){G0(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&K0(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:Mn.includes(r)?r:Tl,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"},pi)}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},Dl,r):this.request({method:"sampling/createMessage",params:e},Vo,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},qn,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},qn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(A.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},Ll,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"})}};yr();var Y0=Symbol.for("mcp.completable");function Kf(t){return!!t&&typeof t=="object"&&Y0 in t}function Q0(t){return t[Y0]?.complete}var X0;(function(t){t.Completable="McpCompletable"})(X0||(X0={}));var wa=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 KI=/^[A-Za-z0-9._-]{1,128}$/;function GI(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"),!KI.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 XI(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 Gf(t){let e=GI(t);return XI(t,e.warnings),e.isValid}var $a=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 YI(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 QI(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 ka=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 ba(e,r),this._maxToolInputElements=QI(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 $a(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Er(Ri)),this.server.assertCanSetRequestHandler(Er(Ln)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ri,()=>({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=An(r.inputSchema);return o?Vl(o,{strictUnions:!0,pipeStrategy:"input"}):eC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=An(r.outputSchema);o&&(n.outputSchema=Vl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ln,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new I(A.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new I(A.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new I(A.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof I&&n.code===A.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&&YI(r,this._maxToolInputElements)>this._maxToolInputElements)throw new I(A.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=An(e.inputSchema)??e.inputSchema,i=await ii(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=ai(a);throw new I(A.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new I(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=An(e.outputSchema),s=await ii(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ai(i);throw new I(A.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 I(A.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Er(Ii)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ii,async e=>{switch(e.params.ref.type){case"ref/prompt":return pg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return mg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new I(A.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new I(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ks;let s=hr(n.argsSchema)?.[e.params.argument.name];if(!Kf(s))return ks;let i=Q0(s);if(!i)return ks;let a=await i(e.params.argument.value,e.params.context);return tv(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 ks;throw new I(A.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ks;let s=await o(e.params.argument.value,e.params.context);return tv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Er(ki)),this.server.assertCanSetRequestHandler(Er(Si)),this.server.assertCanSetRequestHandler(Er(Ti)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ki,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Si,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ti,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new I(A.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new I(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Er(Ei)),this.server.assertCanSetRequestHandler(Er(zi)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ei,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?tC(r.argsSchema):void 0}))})),this.server.setRequestHandler(zi,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new I(A.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=An(n.argsSchema),s=await ii(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=ai(c);throw new I(A.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:on(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=on(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 Ke?c._def?.innerType:c;return Kf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Gf(e);let l={title:r,description:n,inputSchema:ev(o),outputSchema:ev(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"&&Gf(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=on(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=on(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(Xf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Xf(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()}},Sa=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new wa(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},eC={type:"object",properties:{}};function rv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function nv(t){return"_def"in t||"_zod"in t||rv(t)}function Xf(t){return typeof t!="object"||t===null||nv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(rv)}function ev(t){if(t){if(Xf(t))return on(t);if(!nv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function tC(t){let e=hr(t);return e?Object.entries(e).map(([r,n])=>{let o=kh(n),s=Sh(n);return{name:r,description:o,required:!s}}):[]}function Er(t){let r=hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=On(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function tv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ks={completion:{values:[],hasMore:!1}};import sv from"node:process";yr();var rC=10*1024*1024,Ta=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??rC}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),nC(r)}clear(){this._buffer=void 0}};function nC(t){return Zo.parse(JSON.parse(t))}function ov(t){return JSON.stringify(t)+`
58
- `}var Ea=class{constructor(e=sv.stdin,r=sv.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 Ta({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=ov(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};yr();function za(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=za(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 ep(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=za(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 Yf(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 oC(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 Qf(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=oC(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}:za(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 ep(r,e)}function iv(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return Yf("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return Yf(t,l)}if(e===null||typeof e!="object")return Yf(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)=>Qf(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)=>ep(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}:Qf(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>Qf(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=za(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>ep(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 jC}from"node:crypto";var av=[[/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]],rq=Math.max(...av.map(([,t])=>t));function Ra(t){if(t){for(let[e,r]of av)if(e.test(t))return r}}function zr(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function iC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Ss={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 cv(t){return iC(t)>.08}function tp(t,e){let r=Ss[zr(e)];return cv(t)?r.code:r.prose}function Rt(t,e){return typeof t!="string"&&(t=String(t??"")),t?aC(t.length,cv(t),e):0}function aC(t,e,r){if(!(t>0))return 0;let n=Ss[zr(r)];return Math.ceil(t/(e?n.code:n.prose))}var rp=4;function z(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${z(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var ie=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function Ne(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var Pa=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],cC=[[Ne("fable|mythos",5,1),ie(10,50,.25)],[Ne("fable|mythos",5),ie(10,50,1)],[Ne("opus",5,5),ie(4,20,.2)],[Ne("opus",5),ie(5,25,.5)],[Ne("opus",4,8),ie(5,25,.5)],[Ne("opus",4,7),ie(5,25,.5)],[Ne("opus",4,6),ie(5,25,.5)],[Ne("opus",4,5),ie(5,25,.5)],[Ne("opus",4,1),ie(15,75,1.5)],[Ne("opus",4),ie(15,75,1.5)],[/claude-3-opus/i,ie(15,75,1.5)],[Ne("sonnet",5,5),ie(2,10,.2)],[Ne("sonnet",5),ie(2,10,.2)],[Ne("haiku",5,5),ie(.1,.5,.01)],[Ne("haiku",4,5),ie(1,5,.1)],[/claude-3-5-haiku/i,ie(.8,4,.08)],[/claude-3-haiku/i,ie(.25,1.25,.03)],[Ne("sonnet",4,6),ie(3,15,.3)],[Ne("sonnet",4,5),ie(3,15,.3)],[Ne("sonnet",4),ie(3,15,.3)],[/claude-3-[57]-sonnet/i,ie(3,15,.3)],[Pa[0],ie(10,50,1)],[Pa[1],ie(5,25,.5)],[Pa[2],ie(3,15,.3)],[Pa[3],ie(1,5,.1)],[/gpt-5.*(mini|nano)/i,{inputPerM:.25,outputPerM:2,cacheReadPerM:.025}],[/gpt-5/i,{inputPerM:1.25,outputPerM:10,cacheReadPerM:.125}],[/gpt-4o-mini/i,{inputPerM:.15,outputPerM:.6,cacheReadPerM:.075}],[/gpt-4o|gpt-4\.1/i,{inputPerM:2.5,outputPerM:10,cacheReadPerM:1.25}],[/gpt-4-turbo/i,{inputPerM:10,outputPerM:30,cacheReadPerM:10}],[/o[13](-|$)/i,{inputPerM:2,outputPerM:8,cacheReadPerM:1}],[/gemini-3[.\d]*-flash-lite/i,ie(.3,2.5,.03)],[/gemini-3\.1-flash-lite/i,ie(.25,1.5,.025)],[/gemini-3-flash/i,ie(.5,3,.05)],[/gemini-3[.\d]*-flash/i,ie(.75,3.75,.075)],[/gemini-3[.\d]*-pro/i,ie(2,12,.2)],[/gemini.*flash/i,{inputPerM:.1,outputPerM:.4,cacheReadPerM:.025}],[/gemini.*pro/i,{inputPerM:1.25,outputPerM:5,cacheReadPerM:.31}]];function so(t){if(t){for(let[e,r]of cC)if(e.test(t))return r}}function Rr(t,e){return t/1e6*e.inputPerM}function np(t){return t/25e3}function Ut(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var uv=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,uC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function lv(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 io(t){for(let e of t.matchAll(uv))if(lv(e[0]))return!0;return!1}function op(t){return t.replace(uv,e=>lv(e)?uC:e)}import{mkdirSync as hq,readFileSync as zC,writeFileSync as gq}from"node:fs";import{dirname as RC,join as PC}from"node:path";import{appendFileSync as pC,existsSync as sp,mkdirSync as mC,readFileSync as hC,statSync as gC,writeFileSync as yC}from"node:fs";import{homedir as fv}from"node:os";import{dirname as mv,join as co}from"node:path";import{homedir as dv}from"node:os";import{join as lC,resolve as dC}from"node:path";function fC(t,e){if(t!==void 0&&t!==dv())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?dC(r):void 0}function ao(t,e=process.env){return fC(t,e)??lC(t??dv(),".claude")}var _C={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function vC(t){let e={..._C},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 xC(){let t=process.env.XDG_STATE_HOME?.trim();return t?co(t,"context-doctor"):process.platform==="win32"?co(process.env.LOCALAPPDATA?.trim()||co(fv(),"AppData","Local"),"context-doctor"):co(fv(),".local","state","context-doctor")}function bC(){let t=xC();if(sp(t))return t;let e=ao();return sp(e)?e:t}function ip(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??co(bC(),".context-doctor-hook-state.json")}function wC(){return co(mv(ip()),".context-doctor-ledger.jsonl")}var pv=100,$C=256*1024,kC=128*1024,SC=500,TC=4*1024;function EC(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>pv?e.slice(0,pv):e}function Ia(t){let e=wC();try{if(mC(mv(e),{recursive:!0}),sp(e)&&gC(e).size>$C){let n=hC(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<SC;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>TC)){if(i+m>kC)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=vC(c),l={ts:Date.now(),ev:"rollup",carried:u};yC(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 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(`
63
63
  `)+`
64
- `)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=EC(r[n]);o===void 0?delete r[n]:r[n]=o}pC(e,JSON.stringify({ts:Date.now(),...r})+`
65
- `)}catch{}}var IC=2,CC=.5,AC=2;function OC(){return PC(RC(ip()),".context-doctor-calibration.json")}function NC(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 MC(){try{return JSON.parse(zC(OC(),"utf8"))}catch{return{}}}function hv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=MC()[NC(t)];if(!e||e.v!==IC||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<CC||r>AC?{factor:1,samples:0}:{factor:r,samples:e.samples}}function ZC(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 DC(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 LC(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function gv(t){return jC("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function qC(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 UC(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=qC(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var yv=.6;function FC(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var _v=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function HC(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function BC(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;_v.lastIndex=0;for(let n of e.matchAll(_v)){let o=n[2].replace(/\\+$/,"");HC(o)&&r.add(o)}return[...r]}function vv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=hv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(Rt(y.text,r)*n.factor)+rp})),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[ZC(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 ~${z(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 ~${z(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=gv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-rp,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${z(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(F=>F.msg.text.length>=300).sort((F,_e)=>_e.tokens-F.tokens).slice(0,150),x=y.map(F=>UC(F.msg.text)),$=x.map(F=>F.size),O=new Set(a.filter(F=>F.id==="duplicate_content").flatMap(F=>F.messages)),C=y.map((F,_e)=>_e),ae=F=>{for(;C[F]!==F;)F=C[F]=C[C[F]];return F},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let F=0;F<y.length;F++)for(let _e=F+1;_e<y.length;_e++){let Pt=y[F],Or=y[_e];if(O.has(Pt.msg.index)&&O.has(Or.msg.index))continue;let As=Math.min($[F],$[_e]),xn=Math.max($[F],$[_e]);if(xn===0||As/xn<yv)continue;let _t=FC(x[F],x[_e]);_t<yv||(C[ae(F)]=ae(_e),_t>ce[F].sim&&(ce[F]={sim:_t,partnerTokens:Or.tokens}),_t>ce[_e].sim&&(ce[_e]={sim:_t,partnerTokens:Pt.tokens}))}let Ee=new Map;y.forEach((F,_e)=>{if(ce[_e].sim===0)return;let Pt=ae(_e);Ee.set(Pt,[...Ee.get(Pt)??[],_e])});for(let F of Ee.values()){if(F.length<2)continue;F.sort((vt,Nr)=>y[vt].msg.index-y[Nr].msg.index);let _e=F.slice(1),Pt=_e.reduce((vt,Nr)=>vt+Math.round(Math.min(y[Nr].tokens,ce[Nr].partnerTokens)*ce[Nr].sim*.9),0),Or=F.map(vt=>ce[vt].sim),As=Math.round(Math.min(...Or)*100),xn=Math.round(Math.max(...Or)*100),_t=F.map(vt=>y[vt].msg.index),Bp=As===xn?`~${xn}%`:`${As}-${xn}%`,Rb=_e.reduce((vt,Nr)=>vt+y[Nr].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Pt,message:F.length===2?`Messages #${_t[0]} and #${_t[1]} are ${Bp} similar (~${z(Math.min(y[F[0]].tokens,y[F[1]].tokens))} tokens repeated with different framing).`:`${F.length} messages are ${Bp} similar to each other (${_t.slice(0,6).map(vt=>`#${vt}`).join(", ")}${_t.length>6?", \u2026":""}): ~${z(Rb)} tokens in the ${_e.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:_t})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=gv(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((O,C)=>l(y[C])?.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 BC(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let O=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),C=Math.round(O*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:C>4e3?"high":"warn",estSavings:C,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 ~${z(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)io(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 (~${z(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(($,O)=>$+O.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${z(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 ~${z(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:[]}),(zr(e)==="anthropic"||zr(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=Ra(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:LC(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=DC(a,s),_=so(e),v;if(_){let y=Rr(s,_),x=Rr(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:np(s),ttftSavedSeconds:np(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 VC}from"node:crypto";var wv=10,Ca={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:wv};function JC(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 WC(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function xv(t,e,r){let n=Math.round(e*tp("",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 ap(t,e,r=wv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function KC(t){return VC("sha1").update(t.trim()).digest("hex")}function uo(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"?uo(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
- `):JSON.stringify(t)}function cp(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 up(t){return typeof t=="string"?io(t)?op(t):t:Array.isArray(t)?t.map(up):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,up(r)])):t}function GC(t,e,r){let n=Math.round(e*tp(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 XC(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 bv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function $v(t,e={}){let r={strategies:e.strategies??Ca.strategies,keepRecent:e.keepRecent??Ca.keepRecent,maxToolResultTokens:e.maxToolResultTokens??Ca.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):Ca.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=>Rt(h,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:uo(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=h=>{let _=a(uo(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=uo(h.content);if(!io(v))return;let y=a(v),x=cp(h,O=>io(O)?op(O):O);Array.isArray(x)&&(x=x.map(O=>O?.type==="tool_use"&&O.input!=null?{...O,input:up(O.input)}:O));let $=y-a(uo(x));$>50&&(h.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let h=ap(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,O=cp(v,C=>{if(C.length<300)return C;let ae=KC(C),ce=_.get(ae);if(ce===void 0)return _.set(ae,y),C;if(y>=h)return C;let Ee=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(C)-a(Ee),$??=ce,Ee});x<=0||(v.content=O,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let h=ap(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h||!bv(_))return;let y=0,x=cp(_,($,O)=>{if(O!=="tool_result")return $;let C=a($);if(C<=r.maxToolResultTokens)return $;let ae=GC($,r.maxToolResultTokens,i),ce=a(ae);return ce>=C?$:(y+=C-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=ap(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"||WC(o,v,JC(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let O=xv(x.input,r.maxToolResultTokens,i),C=a(JSON.stringify(O));C>=$||(x.input=O,y+=$-C)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let O=a($);if(O<=r.maxToolResultTokens)continue;let C;try{C=JSON.parse($)}catch{continue}if(!C||typeof C!="object"||Array.isArray(C))continue;let ae=JSON.stringify(xv(C,r.maxToolResultTokens,i)),ce=a(ae);ce>=O||(x.function.arguments=ae,y+=O-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&&bv(o[h]);)h++;if(o.length-h>=2){XC(o.slice(h));let _=o.slice(p,h),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${uo(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 kv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},YC={high:"\u2716",warn:"\u25B2",info:"\u2139"};function QC(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function eA(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 Sv(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: ~${z(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 ${z(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Ut(n.cost.perCallUsd)} input per call \xB7 ~${Ut(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])=>kv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${kv[i].padEnd(s)} ${QC(c)} ${String(Math.round(c*100)).padStart(3)}% ~${z(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}] ~${z(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 ~${z(u.estSavings)}]`:"";r.push(`${YC[u.severity]} ${e.redact?eA(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 ~${z(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: ~${z(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Ut(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 tA=2060,rA={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},nA=6.3,oA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},sA=1500,Tv=2e3,iA=30,lp=400,aA=1e4,cA=6;function uA(t,e){let r=Ss[zr(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):sA;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*rA[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*nA:oA[t.kind];return Math.round(r/uA(t.kind,e))}function dp(t){return Math.round(tA/Ss[zr(t)].prose)}var Ev=60;function dA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Ev?e.slice(0,Ev-1)+"\u2026":e}function fA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:dA(_?.label)})),n=dp(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 (~${z(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 (~${z(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>=Tv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Tv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${z(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 (~${z(_)}) 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>=iA){let _=cA*n+lp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${z(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${lp}-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 ~${z(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Ra(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 ${z(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=so(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:g,perTurnUsd:h?Rr(a,h):void 0,perTurnCachedUsd:h?a/1e6*h.cacheReadPerM:void 0}}function zv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${z(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${z(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${z(t.baselineTokens)} plain conversation + ${z(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Ut(t.perTurnUsd)} at list price, ${Ut(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 ~${z(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?` [~${z(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>=aA&&e.push(`To recover the ~${z(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${lp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
73
- `))}function Rv(t,{record:e=!0}={}){let r=fA(t);return e&&Ia({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as Kv}from"node:child_process";import{existsSync as Gv,lstatSync as RA,readdirSync as PA,readFileSync as IA,realpathSync as _p,statSync as CA}from"node:fs";import{homedir as AA}from"node:os";import{basename as vp,extname as Da,isAbsolute as OA,join as lo,relative as Xv,resolve as NA,sep as MA}from"node:path";import{execFile as pA,spawnSync as Pv}from"node:child_process";import{existsSync as Iv,mkdtempSync as Cv,readFileSync as pp,rmSync as Av}from"node:fs";import{tmpdir as Ov}from"node:os";import{dirname as Nv,extname as Mv,join as Aa}from"node:path";var Oa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),jv={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function Ts(t,e){try{let r=Pv(t,e,jv);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var Zv=["-convert","txt","-noload","-nostore","-stdout"],Dv='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function mA(t){let e=Ts("pdftotext",["-enc","UTF-8",t,"-"])??Ts("pdftotext",[t,"-"]);if(e)return e;let r=Aa(Cv(Aa(Ov(),"cd-pdf-")),"out.txt");try{Pv("pdftotext",[t,r],jv);let n=Iv(r)?pp(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{Av(Nv(r),{recursive:!0,force:!0})}}function hA(t,e){let r=Ts("unzip",["-p",t,...e]);return r?Lv(r):void 0}function Lv(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=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,`
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 qv(t){let e=Mv(t).toLowerCase(),r=process.platform==="darwin",n;if(e===".pdf"){if(n=mA(t)?.replace(/\f/g,`
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,`
78
78
 
79
- `),!n&&r&&(n=Ts("osascript",["-l","JavaScript","-e",Dv,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=Ts("textutil",[...Zv,t])),!n){let o=e===".docx"?["word/document.xml"]:e===".pptx"?["ppt/slides/*.xml"]:e===".odt"?["content.xml"]:[];o.length&&(n=hA(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 Es=2e4,at=()=>performance.now();function gA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function fp(t,e,r){let n=Math.ceil(r-at());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(gA(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:at()>=r-50})},o);try{c=pA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:at()>=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 Na(t,e=at()+Es){let r=Mv(t).toLowerCase(),n=process.platform==="darwin",o,s=!1,i=async(c,u)=>{if(o||s)return;let l=await fp(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=Aa(Cv(Aa(Ov(),"cd-pdf-")),"out.txt");try{(await fp("pdftotext",[t,c],e)).timedOut?s=!0:Iv(c)&&(o=pp(c,"utf8").trim()?pp(c,"utf8"):void 0)}finally{Av(Nv(c),{recursive:!0,force:!0})}}return o=o?.replace(/\f/g,`
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,`
80
80
 
81
- `),!o&&n&&await i("osascript",["-l","JavaScript","-e",Dv,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",[...Zv,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 fp("unzip",["-p",t,...c],e);u.timedOut?s=!0:u.out&&(o=Lv(u.out))}}return o?{text:o}:s?a():{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}var jA=4e3,ZA=400,DA="claude",LA=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"]),qA=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function UA(t,e){let r=Da(t).toLowerCase();return qA.has(r)?"markdown":LA.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var FA=/^(?![\s})\]]|$)/,Wv=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function HA(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()&&FA.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(Wv,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!Wv.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var BA=t=>t>=55296&&t<=56319,VA=t=>t>=56320&&t<=57343;function Yv(t,e={}){let r=Math.max(50,e.maxChunkTokens??ZA),n=e.model??DA,o=UA(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
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,`
82
82
  `).split(`
83
- `).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;BA(m.charCodeAt(g-1))&&VA(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]+Rt(m+`
84
- `,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of HA(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:Rt(h,n),score:0}})}var JA=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 ja(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||JA.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 Qv(t,e){let r=[...new Set(ja(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...ja(i.text),...ja(i.heading),...ja(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 ex(t,e={}){let r=t.map(o=>Yv(o,e)),n=e.query?.trim()||void 0;return n&&Qv(r.flat(),n),rx(t,r,n,e)}async function tx(t,e={}){let r=t.map(s=>Yv(s,e)),n=e.query?.trim()||void 0,o;if(n&&(Qv(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(Jv(),Vv));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...rx(t,r,n,e),semanticNote:o}}function rx(t,e,r,n){let o=Math.max(1,n.budget??jA),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 gp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${z(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function nx(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}: ~${z(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...gp(t.chunks,e)),r.join(`
86
- `);r.push(`PACKED ~${z(t.packedTokens)} of ~${z(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${z(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 ${z(t.budget)}: ${s.map(a=>`${a.id} (~${z(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 ${z(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${z(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...gp(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(...gp(t.chunks,e)),r.join(`
88
- `);for(let a of t.selected)r.push("",`\u2500\u2500 ${a.id} \xB7 L${a.startLine}-${a.endLine}${a.heading?` \xB7 ${a.heading}`:""} \xB7 ~${z(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 WA=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Za={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function KA(t){try{let e=Kv("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&&Gv(lo(t,r))).sort()}catch{return}}function GA(t){let e=Kv("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 ox(t,e){let r=Xv(t,e);return r===""||r!==".."&&!r.startsWith(".."+MA)&&!OA(r)}var XA=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd"]),YA=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function QA(t){let e=vp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(XA.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(YA.has(Da(r)))return`a key or certificate store (${Da(r)})`;let n=t.split(/[\\/]+/);if(r==="credentials"&&n[n.length-2]===".aws")return"AWS credentials"}function eO(){let t=AA(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",lo(".config","gcloud"),lo("Library","Keychains"),".password-store"].map(n=>lo(t,n)),"/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 tO(t,e){return e.find(r=>ox(r,t))}function yp(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 rO(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?[]:eO(),a=[],c=[],u=0,l=new Set,d="",m=0,p=!1,f=h=>{try{return _p(h)}catch{return NA(h)}},g=(h,_)=>{if(a.length>=Za.files){(_||c.length<20)&&c.push(`${h}: over ${Za.files} files`);return}let v;try{v=_?CA(h):RA(h)}catch(C){c.push(`${h}: ${yp(C)}`);return}if(v.isSymbolicLink()){let C;try{C=_p(h)}catch{return}ox(d,C)||c.push(`${h}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let C=tO(f(h),i);if(C){_&&c.push(`${h}: refused, ${C} holds credentials${s}`);return}}if(v.isDirectory()){let C=vp(h);if(!_&&WA.has(C))return;if(!_&&C.startsWith(".")){m++;return}let ae=_?KA(h):void 0;if(_&&(p=ae!==void 0),ae){ae.length===0&&GA(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 Ee of ae)g(lo(h,Ee),!1);return}let ce;try{ce=PA(h).sort()}catch(Ee){c.push(`${h}: ${yp(Ee)}`);return}for(let Ee of ce)g(lo(h,Ee),!1);return}if(!v.isFile()){_&&c.push(`${h}: not a regular file`);return}if(!o){let C=QA(h);if(C){c.push(`${h}: ${C}, likely holding secrets; not packed${s}`);return}}if(!_&&vp(h).startsWith(".")&&!p){m++;return}let y=f(h);if(l.has(y))return;if(v.size>Za.fileBytes||u+v.size>Za.totalBytes){c.push(`${h}: too large (${Math.round(v.size/1024)} KB)`);return}let x=Xv(n,h),$=x&&!x.startsWith("..")?x:h;if(Oa.has(Da(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 C=qv(h);"error"in C?c.push(`${h}: ${C.error}`):(u+=v.size,l.add(y),a.push({name:$,text:C.text}));return}let O;try{O=IA(h)}catch(C){c.push(`${h}: ${yp(C)}`);return}if(O.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:O.toString("utf8")})};for(let h of t){if(!Gv(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 sx(t,e={}){let r=[],{sources:n,skipped:o}=rO(t,{...e,defer:r}),s=at()+(e.budgetMs??Es),i=new Set;for(let a of r){let c=await Na(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 ix=`Context hygiene rules (always on):
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(`
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):
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 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 fo=t=>Math.round(t);function cx(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${z(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${z(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,fo(c)])),i={total_tokens:fo(t.totalTokens),messages:t.messageCount,recoverable_tokens:fo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${z(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:fo(a.tokens),preview:a.preview}))}}}function ux(t,e){let[r,...n]=t.findings,o=[`~${z(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${z(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?` ~${z(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 oO(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function sO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function lx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=sO(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:fo(f),sections:p.map(g=>`${oO(g.first,g.last)} ${g.heading} ~${z(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}: ~${z(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:fo(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 iO,lstatSync as or,mkdirSync as mx,readdirSync as aO,readFileSync as xp,realpathSync as La,rmSync as cO,writeFileSync as dx}from"node:fs";import{homedir as mo}from"node:os";import{isAbsolute as uO,join as nt,relative as lO,sep as dO}from"node:path";var yt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function wp(t=mo()){return nt(t,".context-doctor","handoffs")}var fO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function hx(t){return typeof t=="string"&&t.length<=80&&fO.test(t)}function pO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function mO(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 $p(t){let e=[],r=yt;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 po="masked by context-doctor",qe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${po}]`:void 0}),hO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),gO=[qe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),qe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),qe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,hO),qe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),qe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),qe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),qe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),qe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),qe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),qe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),qe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),qe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),qe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),qe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),qe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),qe("a JWT",/(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g),{kind:"a password in a URL",re:/\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]*):([^\s@/]+)@/gi,replace:t=>`${t[1]}${t[2]}:[${po}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${po}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${po}]`}],gx="(?: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?)",yO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${gx}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),_O=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${gx}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),vO=/^(?: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,xO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function fx(t){return!(vO.test(t)||xO.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 Pr(t){let e=0,r=new Set,n=String(t??"");for(let o of gO)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(_O,(o,s,i,a)=>fx(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${po}]${i}`):o),n=n.replace(yO,(o,s,i)=>fx(i)?(e++,r.add("a password or secret assignment"),`${s}[${po}]`):o),{text:n,count:e,kinds:[...r]}}function bO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function bp(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function wO(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=bO(s.text);o.push("",`### ${bp(s.label,yt.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 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(`
98
98
  `)+`
99
- `}function $O(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)*dp(e.model),r.nowSource="turns");let n=so(e.model);return n&&(r.afterUsd=Rr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=Rr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function yx(t){let e=(o,s)=>o!==void 0?` (${Ut(o)} at list price, ${Ut(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${z(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: ~${z(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${z(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${z(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
100
- `)}function qa(t,e){let r=lO(t,e);return r===""||r!==".."&&!r.startsWith(".."+dO)&&!uO(r)}var _n=class extends Error{};function Ua(t,e){let r=i=>{if(e)throw new _n(i)},n;try{n=La(t)}catch{return r("the home directory cannot be read")}let o=nt(t,".context-doctor"),s=wp(t);for(let i of[o,s]){let a;try{a=or(i)}catch{if(!e)return;try{mx(i,{mode:448}),a=or(i)}catch(u){return r(`cannot create ${gt(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${gt(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${gt(i,t)} is not a folder`);let c;try{c=La(i)}catch{return r(`${gt(i,t)} cannot be read`)}if(!qa(n,c))return r(`${gt(i,t)} resolves outside the home directory`)}return s}function px(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function kO(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>px(n,t)-px(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var SO=0;function Fa(t=mo()){let e=Ua(t,!1);if(!e)return[];let r;try{r=aO(e)}catch{return[]}let n=[];for(let o of r){if(!hx(o))continue;let s=nt(e,o);try{if(!or(s).isDirectory())continue;let i=nt(s,"meta.json");if(!or(i).isFile())continue;let a=JSON.parse(xp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(kO(Date.now()))}function kp(t,e=mo()){let r=t==="latest"?Fa(e)[0]?.id:t;if(!hx(r))return;let n=Ua(e,!1);if(!n)return;let o=nt(n,r),s=nt(o,"handoff.md");if(qa(n,s))try{let i=or(s);if(!i.isFile()||i.size>yt.readBytes||!or(o).isDirectory()||!or(nt(o,"meta.json")).isFile())return;let a=JSON.parse(xp(nt(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:xp(s,"utf8")}}catch{return}}function TO(t,e,r){let n=Ua(t,!1);if(!n)return 0;let o=Fa(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=nt(n,i.id);try{if(!qa(n,a)||!or(a).isDirectory()||!or(nt(a,"meta.json")).isFile()||!qa(La(n),La(a)))continue;cO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function nr(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 _x(t,{home:e=mo(),now:r=new Date,store:n=!0}={}){let o=$p(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Pr(x);return i+=$.count,$.kinds.forEach(O=>s.add(O)),$.text},c=a(nr(t.brief)),u=bp(t.title?.trim()?a(nr(t.title,{keepNewlines:!1})):c.split(`
102
- `).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",yt.titleChars),l=(t.verbatim??[]).map(x=>({label:bp(a(nr(x.label,{keepNewlines:!1})),yt.labelChars),text:a(nr(x.text))})),d=t.model===void 0?void 0:a(nr(String(t.model),{keepNewlines:!1})).slice(0,yt.modelChars)||void 0,m=r.toISOString(),p=wO(u,m,c,l),f=`${mO(r)}-${pO(u)}`,g={id:f,title:u,created:m,model:d,tokens:Rt(p,d),briefTokens:Rt(c,d),blocks:l.map(x=>({label:x.label,tokens:Rt(x.text,d)})),masked:i,order:Date.now()*1e3+SO++%1e3},h=$O(g.tokens,{...t,model:d});if(!n)return{meta:g,markdown:p,maskedKinds:[...s],math:h,rotated:0};let _=Ua(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,O=nt(_,$);try{mx(O,{mode:448}),g.id=$,v=O;break}catch(C){if(C.code!=="EEXIST")throw new _n(`cannot create a handoff folder in ${gt(_,e)} (${C.code??"error"})`)}}if(!v)throw new _n(`too many handoffs saved in the same second in ${gt(_,e)}`);try{dx(nt(v,"handoff.md"),p,{mode:384,flag:"wx"}),dx(nt(v,"meta.json"),JSON.stringify(g,null,2)+`
103
- `,{mode:384,flag:"wx"})}catch(x){throw new _n(`cannot write the handoff in ${gt(v,e)} (${x.code??"error"})`)}let y=TO(e,yt.kept,g.id);if(!iO(nt(v,"handoff.md")))throw new _n(`the handoff in ${gt(v,e)} is gone`);return{meta:g,markdown:p,dir:v,maskedKinds:[...s],math:h,rotated:y}}function gt(t,e=mo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function vx(t,e=mo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as EO}from"node:dns";import{request as zO}from"node:http";import{request as RO}from"node:https";import{isIP as bx}from"node:net";import{mkdtempSync as PO,rmSync as IO,writeFileSync as CO}from"node:fs";import{tmpdir as AO}from"node:os";import{extname as OO,join as xx}from"node:path";var Je={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},NO={"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 Sp(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 MO(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 $x(t){let e=t.replace(/^\[|\]$/g,""),r=bx(e);if(r===4)return Sp(e);if(r===6){let n=MO(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:Sp(`${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?Sp(`${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 Tp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function jO(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)&&Tp(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"}:bx(n)&&$x(n)?{error:"a private or loopback address"}:{url:r}}function ZO(t){return(e,r,n)=>{EO(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>$x(u.address)&&!(t&&Tp(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 DO(t,e,r,n){return new Promise(o=>{let s=wx(e)&&Tp(t.hostname),i=t.protocol==="https:"?RO:zO,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-at()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:ZO(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<Je.bytes?`over the ${Je.totalBytes/1024/1024} MB total for one call`:`too large (over ${Je.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 LO(t,e=process.env,{deadline:r,maxBytes:n=Je.bytes}={}){let o=Math.min(at()+Je.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Je.bytes)),i=t;for(let a=0;a<=Je.redirects;a++){let c=jO(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(at()>=o)return{error:"timed out"};let u=await DO(c.url,e,o,s);if(u.error)return{error:u.error};if(u.location!==void 0){if(!u.location)return{error:`HTTP ${u.status} without a location`};try{i=new URL(u.location,c.url).toString()}catch{return{error:"refused a redirect: not a URL"}}continue}return{body:u.body??Buffer.alloc(0)}}return{error:`more than ${Je.redirects} redirects`}}function qO(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function kx(t,e=process.env){let r=[],n=[],o=0,s=at()+Je.callMs;for(let i of t.slice(0,Je.files)){let a=qO(i);if(at()>=s){n.push(`${a}: not read, the ${Je.callMs/1e3} s allowed for one call ran out`);continue}let c=await LO(String(i.download_url??""),e,{deadline:s,maxBytes:Je.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=OO(a).toLowerCase(),l=Oa.has(u)?u:NO[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=PO(xx(AO(),"cd-file-"));try{let m=xx(d,`upload${l}`);CO(m,c.body,{mode:384});let p=await Na(m,Math.min(at()+Es,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{IO(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>Je.files&&n.push(`${t.length-Je.files} more file(s): at most ${Je.files} per call`),{sources:r,skipped:n}}var Sx={bodyBytes:10485760,bodyMs:3e4},UO=["https://chatgpt.com","https://chat.openai.com"],Tx=["localhost","127.0.0.1","::1"];function Ha(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function Ba(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 Ex(t,e,r,n=process.env){let o=[...Ha(e),...Ha(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],s=new Set([...UO,...Ha(r),...Ha(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(c=>c.toLowerCase().replace(/\/+$/,"")));if(o.includes("*"))return{hosts:"*",origins:s};let i=Ba(t),a=new Set([...Tx,...o.map(Ba)]);return i&&i!=="0.0.0.0"&&i!=="::"&&a.add(i),{hosts:a,origins:s}}function zx(t,e){if(t.hosts!=="*"){let n=Ba(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=Ba(o.host);if(!(Tx.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 Rx(t,e=Sx.bodyBytes,r=Sx.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 XO,existsSync as Ja,openSync as YO,readdirSync as Wa,readSync as QO,statSync as Rp}from"node:fs";import{homedir as Pp}from"node:os";import{basename as Mx,dirname as eN,isAbsolute as tN,join as vn,resolve as jx}from"node:path";import{homedir as Px}from"node:os";import{join as FO,resolve as HO}from"node:path";function Va(t,e=process.env){if(t===void 0||t===Px()){let r=e.CODEX_HOME?.trim();if(r)return HO(r)}return FO(t??Px(),".codex")}import{readdirSync as C9,readFileSync as A9,statSync as O9,existsSync as N9,openSync as BO,readSync as VO,closeSync as JO}from"node:fs";import{StringDecoder as WO}from"node:string_decoder";import{homedir as KO}from"node:os";import{join as GO}from"node:path";function Ix(t,e=KO()){return GO(ao(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function Ep(t,e){let r=BO(t,"r"),n=new WO("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=VO(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{JO(r)}}var zs=2e5,rN=8e6,Cx=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 nN(t){if(t.length<=zs)return{whole:t};let e=zs/2;return{head:t.slice(0,e+Cx),tail:t.slice(-(e+Cx)),length:t.length}}var Ax=t=>"whole"in t?t.whole.length:zs;function oN(t){if("whole"in t){let a=Pr(nr(t.whole));return{text:a.text,masked:a.count}}let e=zs/2,r=Pr(nr(t.head)),n=nr(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=Pr(n);return{text:`${r.text.slice(0,e)}
106
- [\u2026 ${t.length-zs} characters \u2026]
107
- ${i.text.slice(-e)}`,masked:r.count+i.count+o}}function Ox(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 sN(t,e=rN){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=nN(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=Ax(h);o>e&&n<r.length-1;)o-=Ax(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};Ep(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",Ox(_,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",Ox(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=oN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function iN(t){try{let e=YO(t,"r");try{let r=Buffer.alloc(65536),n=QO(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{XO(e)}}catch{return}}function Nx(t){let e;try{for(let r of Wa(t)){if(!r.endsWith(".jsonl"))continue;let n=vn(t,r),o=Rp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function aN(t,e){let r=vn(Va(e),"sessions");if(!Ja(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=Wa(i)}catch{return}for(let u of c){let l=vn(i,u),d;try{d=Rp(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=>iN(i.path)===jx(t))}function Zx(t=process.env,e=process.cwd(),r=Pp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=cN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=Nx(eN(a));if(c&&c.path!==a&&c.at>Rp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${Mx(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=Nx(Ix(e,r)),i=aN(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 cN(t,e=Pp()){if((tN(t)||t.includes("/")||t.includes("\\"))&&Ja(t))return jx(t);if(!/^[\w.-]+$/.test(t))return;let r=vn(ao(e),"projects"),n=[];try{n=Wa(r)}catch{}for(let a of n){let c=vn(r,a,`${t}.jsonl`);if(Ja(c))return c}let o=vn(Va(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=Wa(a)}catch{return}for(let l of u){let d=vn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return Ja(o)&&i(o,0),s}function Dx(t,e,r={}){let n=sN(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=ex(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 Lx(t,e=Pp()){let r=Mx(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${z(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
- `);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 ~${z(o.tokens)}`,o.text)}return n.join(`
110
- `).replaceAll(e,"~")}var eM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],tM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Hp(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 Tb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.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 Eb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new ka({name:"context-doctor",version:"0.42.0"},{instructions:ix,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:Z.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:Z.object({turns:Z.number().int().nonnegative().describe("Exchanges so far"),model:Z.string().optional(),blocks:Z.array(Z.object({turn:Z.number().int().positive(),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name"),approx_tokens:Z.number().optional(),approx_lines:Z.number().optional(),approx_words:Z.number().optional(),approx_chars:Z.number().optional(),repeated:Z.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:Z.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:Z.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(tM)){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=Rv({...a,model:a.model??c},{record:!t}),g=p+zv(f);return Hp(u?._meta,g,()=>{let h=ux(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=vv(iv(i),c),d=Sv(l);return Hp(u?._meta,d,()=>cx(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:Z.string().describe("Conversation JSON"),strategies:Z.array(Z.enum(eM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:Z.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 Tb(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=$v(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&Ia({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${z(m)} tokens (${z(d.tokensBefore)} \u2192 ${z(d.tokensAfter)}) via ${d.applied.length} change(s):
112
- `+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${z(_.tokensSaved)})`).join(`
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(`
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):
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=Z.object({download_url:Z.string(),file_id:Z.string(),mime_type:Z.string().optional(),file_name:Z.string().optional()}).strict(),s={...t?{}:{paths:Z.array(Z.string()).optional().describe("Files or folders, absolute paths")},text:Z.string().optional().describe("Raw text to pack instead of files"),query:Z.string().optional().describe("The question; omit for an outline"),max_tokens:Z.number().int().positive().optional().describe("Budget, default 4000"),ids:Z.array(Z.string()).optional().describe("Chunk ids, e.g. docs/guide.md#4"),model:Z.string().optional().describe("Model to count for"),...t?{files:Z.array(o).optional().describe("Files the user uploaded")}:{semantic:Z.boolean().optional().describe("Also rank by meaning (local Ollama embeddings)")}};if(n.registerTool("pack_context",{description:"Read only the parts of large files a question needs: 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=O=>({content:[{type:"text",text:O}],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 sx(c):{sources:[],skipped:[]};if(t&&g?.length){let O=await kx(g);_.push(...O.sources),v.push(...O.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)`:""}`:"",$=nx(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:Hp(a?._meta,$,()=>{let O=lx(y,$);return{...O,text:O.text+x}})}),n.prompt("context_checkup","Profile this conversation's context and apply the top fix. One click, no typing.",async()=>({messages:[{role:"user",content:{type:"text",text:"Run profile_context on our conversation so far: pass a `sketch` (turn count, the model you are running as, and every block over ~500 tokens, repeated, or an image; one size hint each). Report the total, the top three findings, and the estimated recoverable tokens in under 120 words. Then, if the top finding is recoverable, apply it: summarize the offending content into the points still needed and tell me what you dropped. Do not re-quote the content you are summarizing."}}]})),n.registerPrompt("handoff",{title:"Hand off to a new chat",description:"Write a short brief of this chat, save it, and continue in a new chat: the only way to cut a long chat's cost.",argsSchema:{focus:Z.string().max(200).optional().describe("What the next chat should work on (optional)")}},async({focus:i})=>({messages:[{role:"user",content:{type:"text",text:`Hand this chat off to a new one. Write a dense brief of at most ${yt.briefTargetTokens} tokens: the goal, decisions made (with the reason in a few words), the current state, open items and the next step, and key identifiers (names, paths, IDs, versions, numbers). Leave out what is finished or no longer needed. Separately, list only the blocks that must stay exact (code, config, commands, figures), each with a short label. Then call save_handoff with the brief, those blocks as \`verbatim\`, a short title, the model you run as, and \`chat_tokens\` if you have a profile_context figure (else \`turns\`). Do not write the brief into this reply before the call. After it, tell me in two lines how to continue, as its result says.`+(i?.trim()?` The next chat will work on: ${i.trim()}`:"")}}]})),n.registerPrompt("ask_file",{title:"Ask a big file",description:"Answer from a big file or folder without reading it whole: pack_context returns only the parts the question needs.",argsSchema:{path:Z.string().max(1e3).describe("Absolute path to the file or folder"),question:Z.string().max(2e3).describe("What you want to know from it")}},async({path:i,question:a})=>({messages:[{role:"user",content:{type:"text",text:`Answer from ${JSON.stringify(i)} without pasting or reading it whole: ${a}
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}
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${yt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:Z.string(),verbatim:Z.array(Z.object({label:Z.string(),text:Z.string()})).optional().describe("Code, config, figures"),title:Z.string().optional(),chat_tokens:Z.number().optional().describe("Chat size, from profile_context"),turns:Z.number().optional(),model:Z.string().optional()},annotations:{title:"Save handoff",readOnlyHint:!e,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async({brief:i,verbatim:a,title:c,chat_tokens:u,turns:l,model:d})=>{let m={brief:i,verbatim:a,title:c,model:d,chatTokens:u,turns:l},p=$p(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 Tb(n,`Save a handoff of this chat on this computer (${gt(wp())}) to start a new chat from? "${Pr(c??i.split(`
120
- `)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Pr(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=_x({...m,verbatim:f},{store:e})}catch(y){let x=vx(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 ~${z(h.briefTokens)}${h.blocks.length?`, ${h.blocks.length} verbatim block(s) ~${z(h.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[g.dir?`Handoff saved: ${h.id} (~${z(h.tokens)} tokens: ${_}) in ${gt(g.dir)}.`:`Handoff ready (~${z(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>yt.briefTargetTokens&&v.push(`The brief is ~${h.briefTokens} tokens; the target is \u2264${yt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(yx(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:kp("latest")?.markdown??i}]})),n.registerResource("handoff",new Sa("handoff://{id}",{list:async()=>({resources:Fa().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${z(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=kp(String(Array.isArray(c)?c[0]:c));if(!u)throw new I(A.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:Z.string(),max_tokens:Z.number().optional()},annotations:{title:"Recall",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({query:i,max_tokens:a})=>{let c=Zx(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=Dx(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:Lx(l)}]}}),n.tool("context_best_practices","Checklist for keeping context lean and prompts cacheable, optionally per provider.",{provider:Z.enum(["general","anthropic","openai"]).optional().describe("Default: general")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:i})=>({content:[{type:"text",text:[...zb.general,...i&&i!=="general"?zb[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
122
- `)}]})),rM(n),n}function rM(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 zb={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 nM(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 rc=process.argv.slice(2);if(rc.includes("--http")){let t=a=>{let c=rc.indexOf(a);return c>=0?rc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=rc.includes("--store-handoffs"),o=Ex(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(Sb(),kb));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=zx(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 Rx(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"))&&nM(a,"accept","application/json, text/event-stream");let g=Eb({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 Ea;await Eb().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${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)}