context-doctor 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +4 -2
  2. package/dist/budget.d.ts +23 -3
  3. package/dist/budget.js +184 -50
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +1 -1
  6. package/dist/cachettl.d.ts +5 -1
  7. package/dist/cachettl.js +16 -29
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +16 -12
  10. package/dist/codexcompact.d.ts +24 -3
  11. package/dist/codexcompact.js +221 -48
  12. package/dist/coldresume.js +16 -8
  13. package/dist/compactwindow.js +14 -9
  14. package/dist/cursor.d.ts +10 -0
  15. package/dist/cursor.js +20 -0
  16. package/dist/doctor.d.ts +9 -0
  17. package/dist/doctor.js +52 -0
  18. package/dist/extract.d.ts +2 -2
  19. package/dist/extract.js +14 -3
  20. package/dist/fanout.js +4 -2
  21. package/dist/fix.d.ts +8 -1
  22. package/dist/fix.js +59 -13
  23. package/dist/hook.js +45 -15
  24. package/dist/httpguard.d.ts +9 -1
  25. package/dist/httpguard.js +5 -4
  26. package/dist/install.js +56 -19
  27. package/dist/lens.js +7 -7
  28. package/dist/limits.d.ts +17 -4
  29. package/dist/limits.js +41 -29
  30. package/dist/mcp.js +63 -63
  31. package/dist/mcpclient.js +19 -19
  32. package/dist/mcpschema.js +10 -12
  33. package/dist/overhead.d.ts +7 -2
  34. package/dist/overhead.js +11 -3
  35. package/dist/pack.js +87 -23
  36. package/dist/pricing.d.ts +125 -6
  37. package/dist/pricing.js +304 -59
  38. package/dist/proxy.d.ts +26 -1
  39. package/dist/proxy.js +45 -5
  40. package/dist/prune.d.ts +8 -0
  41. package/dist/prune.js +73 -10
  42. package/dist/savings.js +17 -9
  43. package/dist/scan.d.ts +7 -1
  44. package/dist/scan.js +19 -1
  45. package/dist/sessionprice.d.ts +9 -2
  46. package/dist/sessionprice.js +95 -36
  47. package/dist/settingsedit.js +3 -2
  48. package/dist/spend.d.ts +75 -10
  49. package/dist/spend.js +279 -37
  50. package/dist/statusline.d.ts +10 -2
  51. package/dist/statusline.js +17 -8
  52. package/dist/subagentmodel.d.ts +2 -2
  53. package/dist/subagentmodel.js +42 -25
  54. package/dist/subagentpay.d.ts +17 -0
  55. package/dist/subagentpay.js +41 -2
  56. package/dist/subagents.d.ts +24 -0
  57. package/dist/subagents.js +93 -27
  58. package/dist/tasks.js +9 -6
  59. package/dist/tooloutput.d.ts +2 -0
  60. package/dist/tooloutput.js +16 -5
  61. 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 sw=Object.create;var fc=Object.defineProperty;var iw=Object.getOwnPropertyDescriptor;var aw=Object.getOwnPropertyNames;var cw=Object.getPrototypeOf,uw=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),To=(t,e)=>{for(var r in e)fc(t,r,{get:e[r],enumerable:!0})},lw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aw(e))!uw.call(t,o)&&o!==r&&fc(t,o,{get:()=>e[o],enumerable:!(n=iw(e,o))||n.enumerable});return t};var pc=(t,e,r)=>(r=t!=null?sw(cw(t)):{},lw(e||!t||!t.__esModule?fc(r,"default",{value:t,enumerable:!0}):r,t));function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function at(t){return t&&Object.assign(Vs,t),Vs}var x$,b$,rr,Vs,Dn=X(()=>{x$=Object.freeze({status:"aborted"});b$=Symbol("zod_brand"),rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vs={}});var ee={};To(ee,{BIGINT_FORMAT_RANGES:()=>_m,Class:()=>vc,NUMBER_FORMAT_RANGES:()=>Tc,aborted:()=>an,allowsEval:()=>$c,assert:()=>T$,assertEqual:()=>w$,assertIs:()=>k$,assertNever:()=>S$,assertNotEqual:()=>$$,assignProp:()=>wc,cached:()=>Co,captureStackTrace:()=>Ws,cleanEnum:()=>D$,cleanRegex:()=>Oo,clone:()=>ct,createTransparentProxy:()=>C$,defineLazy:()=>me,esc:()=>sn,escapeRegex:()=>xr,extend:()=>N$,finalizeIssue:()=>St,floatSafeRemainder:()=>bc,getElementAtPath:()=>E$,getEnumValues:()=>Io,getLengthableOrigin:()=>No,getParsedType:()=>I$,getSizableOrigin:()=>vm,isObject:()=>Ln,isPlainObject:()=>qn,issue:()=>Ec,joinValues:()=>Js,jsonStringifyReplacer:()=>xc,merge:()=>M$,normalizeParams:()=>q,nullish:()=>Ao,numKeys:()=>P$,omit:()=>O$,optionalKeys:()=>Sc,partial:()=>j$,pick:()=>A$,prefixIssues:()=>Lt,primitiveTypes:()=>ym,promiseAllObject:()=>z$,propertyKeyTypes:()=>kc,randomString:()=>R$,required:()=>Z$,stringifyPrimitive:()=>Ks,unwrapMessage:()=>Po});function w$(t){return t}function $$(t){return t}function k$(t){}function S$(t){throw new Error}function T$(t){}function Io(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Js(t,e="|"){return t.map(r=>Ks(r)).join(e)}function xc(t,e){return typeof e=="bigint"?e.toString():e}function Co(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ao(t){return t==null}function Oo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function bc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function me(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function wc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function E$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function z$(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function R$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function sn(t){return JSON.stringify(t)}function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function P$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function xr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ct(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function q(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function C$(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ks(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Sc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function A$(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return ct(t,{...t._zod.def,shape:r,checks:[]})}function O$(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return ct(t,{...t._zod.def,shape:r,checks:[]})}function N$(t,e){if(!qn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return wc(this,"shape",n),n},checks:[]};return ct(t,r)}function M$(t,e){return ct(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return wc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function j$(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return ct(e,{...e._zod.def,shape:o,checks:[]})}function Z$(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return ct(e,{...e._zod.def,shape:o,checks:[]})}function an(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Lt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Po(t){return typeof t=="string"?t:t?.message}function St(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Po(t.inst?._zod.def?.error?.(t))??Po(e?.error?.(t))??Po(r.customError?.(t))??Po(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function vm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function No(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ec(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function D$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ws,$c,I$,kc,ym,Tc,_m,vc,qt=X(()=>{Ws=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};$c=Co(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});I$=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},kc=new Set(["string","number","symbol"]),ym=new Set(["string","number","bigint","boolean","symbol","undefined"]);Tc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},_m={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};vc=class{constructor(...e){}}});function zc(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Rc(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var xm,Gs,Mo,Pc=X(()=>{Dn();qt();xm=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,xc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gs=w("$ZodError",xm),Mo=w("$ZodError",xm,{Parent:Error})});var Ic,Cc,Ac,Oc,Nc,cn,Mc,un,jc=X(()=>{Dn();Pc();qt();Ic=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Cc=Ic(Mo),Ac=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>St(c,s,at())));throw Ws(a,o?.callee),a}return i.value},Oc=Ac(Mo),Nc=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new rr;return s.issues.length?{success:!1,error:new(t??Gs)(s.issues.map(i=>St(i,o,at())))}:{success:!0,data:s.value}},cn=Nc(Mo),Mc=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>St(i,o,at())))}:{success:!0,data:s.value}},un=Mc(Mo)});function Pm(){return new RegExp(q$,"u")}function Lm(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qm(t){return new RegExp(`^${Lm(t)}$`)}function Um(t){let e=Lm({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Zm}T(?:${n})$`)}var bm,wm,$m,km,Sm,Tm,Em,zm,Zc,Rm,q$,Im,Cm,Am,Om,Nm,Dc,Mm,jm,Zm,Dm,Fm,Hm,Bm,Vm,Jm,Wm,Km,Ys=X(()=>{bm=/^[cC][^\s-]{8,}$/,wm=/^[0-9a-z]+$/,$m=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,km=/^[0-9a-vA-V]{20}$/,Sm=/^[A-Za-z0-9]{27}$/,Tm=/^[a-zA-Z0-9_-]{21}$/,Em=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zm=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Zc=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Rm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,q$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Im=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Cm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Am=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Om=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Dc=/^[A-Za-z0-9_-]*$/,Mm=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,jm=/^\+(?:[0-9]){6,14}[0-9]$/,Zm="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Dm=new RegExp(`^${Zm}$`);Fm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Hm=/^\d+$/,Bm=/^-?\d+(?:\.\d+)?/i,Vm=/true|false/i,Jm=/null/i,Wm=/^[^A-Z]*$/,Km=/^[^a-z]*$/});var Ce,Gm,Lc,qc,Xm,Ym,Qm,eh,th,jo,rh,nh,oh,sh,ih,ah,ch,Qs=X(()=>{Dn();Ys();qt();Ce=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Gm={number:"number",bigint:"bigint",object:"date"},Lc=w("$ZodCheckLessThan",(t,e)=>{Ce.init(t,e);let r=Gm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qc=w("$ZodCheckGreaterThan",(t,e)=>{Ce.init(t,e);let r=Gm[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Xm=w("$ZodCheckMultipleOf",(t,e)=>{Ce.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):bc(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ym=w("$ZodCheckNumberFormat",(t,e)=>{Ce.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Tc[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Hm)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Qm=w("$ZodCheckMaxLength",(t,e)=>{var r;Ce.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=No(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),eh=w("$ZodCheckMinLength",(t,e)=>{var r;Ce.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=No(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),th=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ce.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ao(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=No(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),jo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ce.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),rh=w("$ZodCheckRegex",(t,e)=>{jo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),nh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Wm),jo.init(t,e)}),oh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Km),jo.init(t,e)}),sh=w("$ZodCheckIncludes",(t,e)=>{Ce.init(t,e);let r=xr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),ih=w("$ZodCheckStartsWith",(t,e)=>{Ce.init(t,e);let r=new RegExp(`^${xr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),ah=w("$ZodCheckEndsWith",(t,e)=>{Ce.init(t,e);let r=new RegExp(`.*${xr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),ch=w("$ZodCheckOverwrite",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ei,Uc=X(()=>{ei=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
4
4
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
5
- `))}}});var 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 lh,Fc=X(()=>{lh={major:4,minor:0,patch:0}});function kh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function U$(t){if(!Dc.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return kh(r)}function F$(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function dh(t,e,r){t.issues.length&&e.issues.push(...Lt(r,t.issues)),e.value[r]=t.value}function ti(t,e,r){t.issues.length&&e.issues.push(...Lt(r,t.issues)),e.value[r]=t.value}function fh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Lt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ph(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>St(s,n,at())))}),e}function Hc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(qn(t)&&qn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Hc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Hc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function mh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),an(t))return t;let n=Hc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function hh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function gh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function yh(t,e,r){return an(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function _h(t){return t.value=Object.freeze(t.value),t}function vh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Ec(o))}}var le,Zo,he,Bc,Vc,Jc,Wc,Kc,Gc,Xc,Yc,Qc,eu,tu,xh,bh,wh,$h,ru,nu,ou,su,iu,au,cu,uu,ri,lu,du,fu,pu,mu,hu,ni,oi,gu,yu,_u,vu,xu,bu,wu,$u,ku,Su,Tu,Eu,zu,Ru,Pu,Sh=X(()=>{Qs();Dn();Uc();jc();Ys();qt();Fc();qt();le=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=lh;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=an(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,m=l._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new rr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==d&&(c||(c=an(s,d)))});else{if(s.issues.length===d)continue;c||(c=an(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new rr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=cn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return un(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Zo=w("$ZodString",(t,e)=>{le.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Fm(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=w("$ZodStringFormat",(t,e)=>{jo.init(t,e),Zo.init(t,e)}),Bc=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zm),he.init(t,e)}),Vc=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Zc(n))}else e.pattern??(e.pattern=Zc());he.init(t,e)}),Jc=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Rm),he.init(t,e)}),Wc=w("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Mm.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Kc=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Pm()),he.init(t,e)}),Gc=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Tm),he.init(t,e)}),Xc=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=bm),he.init(t,e)}),Yc=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=wm),he.init(t,e)}),Qc=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=$m),he.init(t,e)}),eu=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=km),he.init(t,e)}),tu=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Sm),he.init(t,e)}),xh=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Um(e)),he.init(t,e)}),bh=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Dm),he.init(t,e)}),wh=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=qm(e)),he.init(t,e)}),$h=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Em),he.init(t,e)}),ru=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Im),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),nu=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Cm),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),ou=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Am),he.init(t,e)}),su=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Om),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});iu=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Nm),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{kh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});au=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Dc),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{U$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),cu=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jm),he.init(t,e)});uu=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{F$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ri=w("$ZodNumber",(t,e)=>{le.init(t,e),t._zod.pattern=t._zod.bag.pattern??Bm,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),lu=w("$ZodNumber",(t,e)=>{Ym.init(t,e),ri.init(t,e)}),du=w("$ZodBoolean",(t,e)=>{le.init(t,e),t._zod.pattern=Vm,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),fu=w("$ZodNull",(t,e)=>{le.init(t,e),t._zod.pattern=Jm,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),pu=w("$ZodUnknown",(t,e)=>{le.init(t,e),t._zod.parse=r=>r}),mu=w("$ZodNever",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});hu=w("$ZodArray",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>dh(u,r,i))):dh(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});ni=w("$ZodObject",(t,e)=>{le.init(t,e);let r=Co(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof le))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let m=Sc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(m)}});me(t._zod,"propValues",()=>{let d=e.shape,m={};for(let p in d){let f=d[p]._zod;if(f.values){m[p]??(m[p]=new Set);for(let g of f.values)m[p].add(g)}}return m});let n=d=>{let m=new ei(["shape","payload","ctx"]),p=r.value,f=v=>{let y=sn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),h=0;for(let v of p.keys)g[v]=`key_${h++}`;m.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let y=g[v];m.write(`const ${y} = ${f(v)};`);let x=sn(v);m.write(`
6
6
  if (${y}.issues.length) {
7
7
  if (input[${x}] === undefined) {
8
8
  if (${x} in input) {
@@ -24,18 +24,18 @@ var 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 ? [${sn(v)}, ...iss.path] : [${sn(v)}]
28
+ })));`),m.write(`newResult[${sn(v)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(v,y)=>_(d,v,y)},o,s=Ln,i=!Vs.jitless,c=i&&$c.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let f=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let y=l.shape;for(let x of l.keys){let $=y[x],N=$._zod.run({value:p[x],issues:[]},m),A=$._zod.optin==="optional"&&$._zod.optout==="optional";N instanceof Promise?f.push(N.then(ae=>A?fh(ae,d,x,p):ti(ae,d,x))):A?fh(N,d,x,p):ti(N,d,x)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let g=[],h=l.keySet,_=u._zod,v=_.def.type;for(let y of Object.keys(p)){if(h.has(y))continue;if(v==="never"){g.push(y);continue}let x=_.run({value:p[y],issues:[]},m);x instanceof Promise?f.push(x.then($=>ti($,d,y))):ti(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:p,inst:t}),f.length?Promise.all(f).then(()=>d):d}});oi=w("$ZodUnion",(t,e)=>{le.init(t,e),me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Oo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>ph(i,r,t,n)):ph(s,r,t,n)}}),gu=w("$ZodDiscriminatedUnion",(t,e)=>{oi.init(t,e);let r=t._zod.parse;me(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Co(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ln(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),yu=w("$ZodIntersection",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>mh(r,c,u)):mh(r,s,i)}});_u=w("$ZodRecord",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!qn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Lt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Lt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>St(u,n,at())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Lt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Lt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),vu=w("$ZodEnum",(t,e)=>{le.init(t,e);let r=Io(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>kc.has(typeof n)).map(n=>typeof n=="string"?xr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),xu=w("$ZodLiteral",(t,e)=>{le.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?xr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),bu=w("$ZodTransform",(t,e)=>{le.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new rr;return r.value=o,r}}),wu=w("$ZodOptional",(t,e)=>{le.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),$u=w("$ZodNullable",(t,e)=>{le.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Oo(r.source)}|null)$`):void 0}),me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),ku=w("$ZodDefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>hh(s,e)):hh(o,e)}});Su=w("$ZodPrefault",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Tu=w("$ZodNonOptional",(t,e)=>{le.init(t,e),me(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>gh(s,t)):gh(o,t)}});Eu=w("$ZodCatch",(t,e)=>{le.init(t,e),t._zod.optin="optional",me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>St(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>St(s,n,at()))},input:r.value}),r.issues=[]),r)}}),zu=w("$ZodPipe",(t,e)=>{le.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>yh(s,e,n)):yh(o,e,n)}});Ru=w("$ZodReadonly",(t,e)=>{le.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(_h):_h(o)}});Pu=w("$ZodCustom",(t,e)=>{Ce.init(t,e),le.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>vh(s,r,n,t));vh(o,r,n,t)}})});function Th(){return{localeError:B$()}}var H$,B$,Eh=X(()=>{qt();H$=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},B$=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${H$(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ks(n.values[0])}`:`Invalid option: expected one of ${Js(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Js(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var si=X(()=>{});function zh(){return new Do}var V$,J$,Do,br,Cu=X(()=>{V$=Symbol("ZodOutput"),J$=Symbol("ZodInput"),Do=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};br=zh()});function Au(t,e){return new t({type:"string",...q(e)})}function Ou(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ii(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Nu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Mu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function ju(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Du(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function Lu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function qu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function Uu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Fu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Hu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Bu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Vu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Ju(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Wu(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Ku(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Gu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Xu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Yu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Qu(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function el(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function Rh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function Ph(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function Ih(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function Ch(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function tl(t,e){return new t({type:"number",checks:[],...q(e)})}function rl(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function nl(t,e){return new t({type:"boolean",...q(e)})}function ol(t,e){return new t({type:"null",...q(e)})}function sl(t){return new t({type:"unknown"})}function il(t,e){return new t({type:"never",...q(e)})}function ai(t,e){return new Lc({check:"less_than",...q(e),value:t,inclusive:!1})}function Lo(t,e){return new Lc({check:"less_than",...q(e),value:t,inclusive:!0})}function ci(t,e){return new qc({check:"greater_than",...q(e),value:t,inclusive:!1})}function qo(t,e){return new qc({check:"greater_than",...q(e),value:t,inclusive:!0})}function ui(t,e){return new Xm({check:"multiple_of",...q(e),value:t})}function li(t,e){return new Qm({check:"max_length",...q(e),maximum:t})}function Un(t,e){return new eh({check:"min_length",...q(e),minimum:t})}function di(t,e){return new th({check:"length_equals",...q(e),length:t})}function al(t,e){return new rh({check:"string_format",format:"regex",...q(e),pattern:t})}function cl(t){return new nh({check:"string_format",format:"lowercase",...q(t)})}function ul(t){return new oh({check:"string_format",format:"uppercase",...q(t)})}function ll(t,e){return new sh({check:"string_format",format:"includes",...q(e),includes:t})}function dl(t,e){return new ih({check:"string_format",format:"starts_with",...q(e),prefix:t})}function fl(t,e){return new ah({check:"string_format",format:"ends_with",...q(e),suffix:t})}function ln(t){return new ch({check:"overwrite",tx:t})}function pl(t){return ln(e=>e.normalize(t))}function ml(){return ln(t=>t.trim())}function hl(){return ln(t=>t.toLowerCase())}function gl(){return ln(t=>t.toUpperCase())}function Ah(t,e,r){return new t({type:"array",element:e,...q(r)})}function yl(t,e,r){let n=q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function _l(t,e,r){return new t({type:"custom",check:"custom",fn:e,...q(r)})}var Oh=X(()=>{Qs();qt()});var Nh=X(()=>{});function vl(t,e){if(t instanceof Do){let n=new fi(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new fi(e);return r.process(t),r.emit(t,e)}function Ee(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ee(o.element,r);case"object":{for(let s in o.shape)if(Ee(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ee(s,r))return!0;return!1}case"intersection":return Ee(o.left,r)||Ee(o.right,r);case"tuple":{for(let s of o.items)if(Ee(s,r))return!0;return!!(o.rest&&Ee(o.rest,r))}case"record":return Ee(o.keyType,r)||Ee(o.valueType,r);case"map":return Ee(o.keyType,r)||Ee(o.valueType,r);case"set":return Ee(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ee(o.innerType,r);case"lazy":return Ee(o.getter(),r);case"default":return Ee(o.innerType,r);case"prefault":return Ee(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ee(o.in,r)||Ee(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var fi,Mh=X(()=>{Cu();qt();fi=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??br,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,d),this.seen.get(m).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let f=p;f.type="string";let{minimum:g,maximum:h,format:_,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof h=="number"&&(f.maxLength=h),_&&(f.format=s[_]??_,f.format===""&&delete f.format),y&&(f.contentEncoding=y),v&&v.size>0){let x=[...v];x.length===1?f.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{let f=p,{minimum:g,maximum:h,format:_,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:x}=e._zod.bag;typeof _=="string"&&_.includes("int")?f.type="integer":f.type="number",typeof x=="number"&&(f.exclusiveMinimum=x),typeof g=="number"&&(f.minimum=g,typeof x=="number"&&(x>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof y=="number"&&(f.exclusiveMaximum=y),typeof h=="number"&&(f.maximum=h,typeof y=="number"&&(y<=h?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{let f=p;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=p,{minimum:g,maximum:h}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof h=="number"&&(f.maxItems=h),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=p;f.type="object",f.properties={};let g=o.shape;for(let v in g)f.properties[v]=this.process(g[v],{...d,path:[...d.path,"properties",v]});let h=new Set(Object.keys(g)),_=new Set([...h].filter(v=>{let y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));_.size>0&&(f.required=Array.from(_)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=p;f.anyOf=o.options.map((g,h)=>this.process(g,{...d,path:[...d.path,"anyOf",h]}));break}case"intersection":{let f=p,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),h=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,v=[..._(g)?g.allOf:[g],..._(h)?h.allOf:[h]];f.allOf=v;break}case"tuple":{let f=p;f.type="array";let g=o.items.map((v,y)=>this.process(v,{...d,path:[...d.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:h,maximum:_}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof _=="number"&&(f.maxItems=_);break}case"record":{let f=p;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=p,g=Io(o.entries);g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=p,g=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(h))}else g.push(h);if(g.length!==0)if(g.length===1){let h=g[0];f.type=h===null?"null":typeof h,f.const=h}else g.every(h=>typeof h=="number")&&(f.type="number"),g.every(h=>typeof h=="string")&&(f.type="string"),g.every(h=>typeof h=="boolean")&&(f.type="string"),g.every(h=>h===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=p,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:_,mime:v}=e._zod.bag;h!==void 0&&(g.minLength=h),_!==void 0&&(g.maxLength=_),v?v.length===1?(g.contentMediaType=v[0],Object.assign(f,g)):f.anyOf=v.map(y=>({...g,contentMediaType:y})):Object.assign(f,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);p.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=p;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=p,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,p.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ee(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let g=n.external.registry.get(l[0])?.id,h=n.external.uri??(v=>v);if(g)return{ref:h(g)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${h("__shared")}#/${d}/${_}`}}if(l[1]===o)return{ref:"#"};let p=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:p+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let f=d.schema;for(let g in f)delete f[g];f.$ref=m};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
29
29
 
30
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let m=this.seen.get(l),p=m.def??m.schema,f={...p};if(m.ref===null)return;let g=m.ref;if(m.ref=null,g){a(g,d);let h=this.seen.get(g).schema;h.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(h)):(Object.assign(p,h),Object.assign(p,f))}m.isParent||this.override({zodSchema:l,jsonSchema:p,path:m.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var $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 jh=X(()=>{});var He=X(()=>{Dn();jc();Pc();Sh();Qs();Fc();qt();Ys();si();Cu();Uc();Nh();Oh();Mh();jh()});var bl=X(()=>{He()});var Uo={};To(Uo,{ZodISODate:()=>qh,ZodISODateTime:()=>Lh,ZodISODuration:()=>Fh,ZodISOTime:()=>Uh,date:()=>$l,datetime:()=>wl,duration:()=>Sl,time:()=>kl});function wl(t){return Rh(Lh,t)}function $l(t){return Ph(qh,t)}function kl(t){return Ih(Uh,t)}function Sl(t){return Ch(Fh,t)}var Lh,qh,Uh,Fh,Tl=X(()=>{He();El();Lh=w("ZodISODateTime",(t,e)=>{xh.init(t,e),be.init(t,e)});qh=w("ZodISODate",(t,e)=>{bh.init(t,e),be.init(t,e)});Uh=w("ZodISOTime",(t,e)=>{wh.init(t,e),be.init(t,e)});Fh=w("ZodISODuration",(t,e)=>{$h.init(t,e),be.init(t,e)})});var Hh,mZ,Fo,zl=X(()=>{He();He();Hh=(t,e)=>{Gs.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Rc(t,r)},flatten:{value:r=>zc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},mZ=w("ZodError",Hh),Fo=w("ZodError",Hh,{Parent:Error})});var Bh,Vh,Jh,Wh,Rl=X(()=>{He();zl();Bh=Ic(Fo),Vh=Ac(Fo),Jh=Nc(Fo),Wh=Mc(Fo)});function b(t){return Au(Dk,t)}function ue(t){return tl(Qh,t)}function Gh(t){return rl(nS,t)}function Pe(t){return nl(oS,t)}function eg(t){return ol(sS,t)}function we(){return sl(iS)}function cS(t){return il(aS,t)}function te(t,e){return Ah(uS,t,e)}function I(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new tg(r)}function Be(t,e){return new tg({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:we(),...ee.normalizeParams(e)})}function ye(t,e){return new rg({type:"union",options:t,...ee.normalizeParams(e)})}function Cl(t,e,r){return new lS({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}function gi(t,e){return new dS({type:"intersection",left:t,right:e})}function ge(t,e,r){return new fS({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Pl({type:"enum",entries:r,...ee.normalizeParams(e)})}function j(t,e){return new pS({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}function ng(t){return new mS({type:"transform",transform:t})}function $e(t){return new og({type:"optional",innerType:t})}function Xh(t){return new hS({type:"nullable",innerType:t})}function yS(t,e){return new gS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function vS(t,e){return new _S({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function xS(t,e){return new sg({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}function wS(t,e){return new bS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Il(t,e){return new $S({type:"pipe",in:t,out:e})}function SS(t){return new kS({type:"readonly",innerType:t})}function TS(t){let e=new Ce({check:"custom"});return e._zod.check=t,e}function ag(t,e){return yl(ig,t??(()=>!0),e)}function ES(t,e={}){return _l(ig,t,e)}function zS(t){let e=TS(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ee.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ee.issue(o))}},t(r.value,r)));return e}function Al(t,e){return Il(ng(t),e)}var Se,Yh,Dk,be,Lk,Kh,hi,qk,Uk,Fk,Hk,Bk,Vk,Jk,Wk,Kk,Gk,Xk,Yk,Qk,eS,tS,rS,Qh,nS,oS,sS,iS,aS,uS,tg,rg,lS,dS,fS,Pl,pS,mS,og,hS,gS,_S,sg,bS,$S,kS,ig,El=X(()=>{He();He();bl();Tl();Rl();Se=w("ZodType",(t,e)=>(le.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Bh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Jh(t,r,n),t.parseAsync=async(r,n)=>Vh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wh(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(ES(r,n)),t.superRefine=r=>t.check(zS(r)),t.overwrite=r=>t.check(ln(r)),t.optional=()=>$e(t),t.nullable=()=>Xh(t),t.nullish=()=>$e(Xh(t)),t.nonoptional=r=>xS(t,r),t.array=()=>te(t),t.or=r=>ye([t,r]),t.and=r=>gi(t,r),t.transform=r=>Il(t,ng(r)),t.default=r=>yS(t,r),t.prefault=r=>vS(t,r),t.catch=r=>wS(t,r),t.pipe=r=>Il(t,r),t.readonly=()=>SS(t),t.describe=r=>{let n=t.clone();return br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return br.get(t);let n=t.clone();return br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Yh=w("_ZodString",(t,e)=>{Zo.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(al(...n)),t.includes=(...n)=>t.check(ll(...n)),t.startsWith=(...n)=>t.check(dl(...n)),t.endsWith=(...n)=>t.check(fl(...n)),t.min=(...n)=>t.check(Un(...n)),t.max=(...n)=>t.check(li(...n)),t.length=(...n)=>t.check(di(...n)),t.nonempty=(...n)=>t.check(Un(1,...n)),t.lowercase=n=>t.check(cl(n)),t.uppercase=n=>t.check(ul(n)),t.trim=()=>t.check(ml()),t.normalize=(...n)=>t.check(pl(...n)),t.toLowerCase=()=>t.check(hl()),t.toUpperCase=()=>t.check(gl())}),Dk=w("ZodString",(t,e)=>{Zo.init(t,e),Yh.init(t,e),t.email=r=>t.check(Ou(Lk,r)),t.url=r=>t.check(Du(qk,r)),t.jwt=r=>t.check(el(rS,r)),t.emoji=r=>t.check(Lu(Uk,r)),t.guid=r=>t.check(ii(Kh,r)),t.uuid=r=>t.check(Nu(hi,r)),t.uuidv4=r=>t.check(Mu(hi,r)),t.uuidv6=r=>t.check(ju(hi,r)),t.uuidv7=r=>t.check(Zu(hi,r)),t.nanoid=r=>t.check(qu(Fk,r)),t.guid=r=>t.check(ii(Kh,r)),t.cuid=r=>t.check(Uu(Hk,r)),t.cuid2=r=>t.check(Fu(Bk,r)),t.ulid=r=>t.check(Hu(Vk,r)),t.base64=r=>t.check(Xu(Qk,r)),t.base64url=r=>t.check(Yu(eS,r)),t.xid=r=>t.check(Bu(Jk,r)),t.ksuid=r=>t.check(Vu(Wk,r)),t.ipv4=r=>t.check(Ju(Kk,r)),t.ipv6=r=>t.check(Wu(Gk,r)),t.cidrv4=r=>t.check(Ku(Xk,r)),t.cidrv6=r=>t.check(Gu(Yk,r)),t.e164=r=>t.check(Qu(tS,r)),t.datetime=r=>t.check(wl(r)),t.date=r=>t.check($l(r)),t.time=r=>t.check(kl(r)),t.duration=r=>t.check(Sl(r))});be=w("ZodStringFormat",(t,e)=>{he.init(t,e),Yh.init(t,e)}),Lk=w("ZodEmail",(t,e)=>{Jc.init(t,e),be.init(t,e)}),Kh=w("ZodGUID",(t,e)=>{Bc.init(t,e),be.init(t,e)}),hi=w("ZodUUID",(t,e)=>{Vc.init(t,e),be.init(t,e)}),qk=w("ZodURL",(t,e)=>{Wc.init(t,e),be.init(t,e)}),Uk=w("ZodEmoji",(t,e)=>{Kc.init(t,e),be.init(t,e)}),Fk=w("ZodNanoID",(t,e)=>{Gc.init(t,e),be.init(t,e)}),Hk=w("ZodCUID",(t,e)=>{Xc.init(t,e),be.init(t,e)}),Bk=w("ZodCUID2",(t,e)=>{Yc.init(t,e),be.init(t,e)}),Vk=w("ZodULID",(t,e)=>{Qc.init(t,e),be.init(t,e)}),Jk=w("ZodXID",(t,e)=>{eu.init(t,e),be.init(t,e)}),Wk=w("ZodKSUID",(t,e)=>{tu.init(t,e),be.init(t,e)}),Kk=w("ZodIPv4",(t,e)=>{ru.init(t,e),be.init(t,e)}),Gk=w("ZodIPv6",(t,e)=>{nu.init(t,e),be.init(t,e)}),Xk=w("ZodCIDRv4",(t,e)=>{ou.init(t,e),be.init(t,e)}),Yk=w("ZodCIDRv6",(t,e)=>{su.init(t,e),be.init(t,e)}),Qk=w("ZodBase64",(t,e)=>{iu.init(t,e),be.init(t,e)}),eS=w("ZodBase64URL",(t,e)=>{au.init(t,e),be.init(t,e)}),tS=w("ZodE164",(t,e)=>{cu.init(t,e),be.init(t,e)}),rS=w("ZodJWT",(t,e)=>{uu.init(t,e),be.init(t,e)}),Qh=w("ZodNumber",(t,e)=>{ri.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ci(n,o)),t.gte=(n,o)=>t.check(qo(n,o)),t.min=(n,o)=>t.check(qo(n,o)),t.lt=(n,o)=>t.check(ai(n,o)),t.lte=(n,o)=>t.check(Lo(n,o)),t.max=(n,o)=>t.check(Lo(n,o)),t.int=n=>t.check(Gh(n)),t.safe=n=>t.check(Gh(n)),t.positive=n=>t.check(ci(0,n)),t.nonnegative=n=>t.check(qo(0,n)),t.negative=n=>t.check(ai(0,n)),t.nonpositive=n=>t.check(Lo(0,n)),t.multipleOf=(n,o)=>t.check(ui(n,o)),t.step=(n,o)=>t.check(ui(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});nS=w("ZodNumberFormat",(t,e)=>{lu.init(t,e),Qh.init(t,e)});oS=w("ZodBoolean",(t,e)=>{du.init(t,e),Se.init(t,e)});sS=w("ZodNull",(t,e)=>{fu.init(t,e),Se.init(t,e)});iS=w("ZodUnknown",(t,e)=>{pu.init(t,e),Se.init(t,e)});aS=w("ZodNever",(t,e)=>{mu.init(t,e),Se.init(t,e)});uS=w("ZodArray",(t,e)=>{hu.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Un(r,n)),t.nonempty=r=>t.check(Un(1,r)),t.max=(r,n)=>t.check(li(r,n)),t.length=(r,n)=>t.check(di(r,n)),t.unwrap=()=>t.element});tg=w("ZodObject",(t,e)=>{ni.init(t,e),Se.init(t,e),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:we()}),t.loose=()=>t.clone({...t._zod.def,catchall:we()}),t.strict=()=>t.clone({...t._zod.def,catchall:cS()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(og,t,r[0]),t.required=(...r)=>ee.required(sg,t,r[0])});rg=w("ZodUnion",(t,e)=>{oi.init(t,e),Se.init(t,e),t.options=e.options});lS=w("ZodDiscriminatedUnion",(t,e)=>{rg.init(t,e),gu.init(t,e)});dS=w("ZodIntersection",(t,e)=>{yu.init(t,e),Se.init(t,e)});fS=w("ZodRecord",(t,e)=>{_u.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Pl=w("ZodEnum",(t,e)=>{vu.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Pl({...e,checks:[],...ee.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Pl({...e,checks:[],...ee.normalizeParams(o),entries:s})}});pS=w("ZodLiteral",(t,e)=>{xu.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});mS=w("ZodTransform",(t,e)=>{bu.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ee.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ee.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});og=w("ZodOptional",(t,e)=>{wu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});hS=w("ZodNullable",(t,e)=>{$u.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});gS=w("ZodDefault",(t,e)=>{ku.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});_S=w("ZodPrefault",(t,e)=>{Su.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});sg=w("ZodNonOptional",(t,e)=>{Tu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});bS=w("ZodCatch",(t,e)=>{Eu.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});$S=w("ZodPipe",(t,e)=>{zu.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});kS=w("ZodReadonly",(t,e)=>{Ru.init(t,e),Se.init(t,e)});ig=w("ZodCustom",(t,e)=>{Pu.init(t,e),Se.init(t,e)})});var cg=X(()=>{});var ug=X(()=>{});var lg=X(()=>{He();El();bl();zl();Rl();cg();He();Eh();si();Tl();ug();at(Th())});var dg=X(()=>{lg()});var fg=X(()=>{dg()});function Eg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Nl,pg,Vn,kr,_i,ze,mg,hg,PZ,IS,CS,Ml,ut,Ho,gg,Ae,pt,mt,Oe,vi,yg,nr,_g,vg,jl,or,O,Zl,Jn,Bo,IZ,xi,AS,bi,OS,Vo,Bn,xg,NS,MS,jS,ZS,DS,LS,wi,Dl,qS,US,Ll,$i,FS,HS,ki,BS,Jo,Wo,VS,Ko,Wn,JS,Go,Si,Ti,Ei,CZ,zi,Ri,Pi,bg,wg,$g,ql,kg,Xo,Kn,Sg,WS,Ii,KS,Ci,GS,Ul,XS,Ai,YS,QS,eT,tT,rT,nT,oT,sT,iT,aT,Oi,cT,uT,Ni,Fl,Hl,Bl,lT,dT,fT,Vl,pT,mT,hT,gT,yT,Tg,Mi,_T,ji,AZ,vT,Gn,xT,OZ,Yo,bT,Jl,wT,$T,kT,ST,TT,ET,zT,yi,RT,PT,IT,Qo,Wl,CT,AT,OT,NT,MT,jT,ZT,DT,LT,qT,UT,FT,HT,BT,VT,JT,WT,KT,Xn,GT,XT,YT,Zi,QT,eE,tE,Kl,rE,NZ,MZ,jZ,ZZ,DZ,LZ,C,Ol,Sr=X(()=>{fg();Nl="2025-11-25",pg="2025-03-26",Vn=[Nl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],kr="io.modelcontextprotocol/related-task",_i="2.0",ze=ag(t=>t!==null&&(typeof t=="object"||typeof t=="function")),mg=ye([b(),ue().int()]),hg=b(),PZ=Be({ttl:ue().optional(),pollInterval:ue().optional()}),IS=I({ttl:ue().optional()}),CS=I({taskId:b()}),Ml=Be({progressToken:mg.optional(),[kr]:CS.optional()}),ut=I({_meta:Ml.optional()}),Ho=ut.extend({task:IS.optional()}),gg=t=>Ho.safeParse(t).success,Ae=I({method:b(),params:ut.loose().optional()}),pt=I({_meta:Ml.optional()}),mt=I({method:b(),params:pt.loose().optional()}),Oe=Be({_meta:Ml.optional()}),vi=ye([b(),ue().int()]),yg=I({jsonrpc:j(_i),id:vi,...Ae.shape}).strict(),nr=t=>yg.safeParse(t).success,_g=I({jsonrpc:j(_i),...mt.shape}).strict(),vg=t=>_g.safeParse(t).success,jl=I({jsonrpc:j(_i),id:vi,result:Oe}).strict(),or=t=>jl.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O||(O={}));Zl=I({jsonrpc:j(_i),id:vi.optional(),error:I({code:ue().int(),message:b(),data:we().optional()})}).strict(),Jn=t=>Zl.safeParse(t).success,Bo=ye([yg,_g,jl,Zl]),IZ=ye([jl,Zl]),xi=Oe.strict(),AS=pt.extend({requestId:vi.optional(),reason:b().optional()}),bi=mt.extend({method:j("notifications/cancelled"),params:AS}),OS=I({src:b(),mimeType:b().optional(),sizes:te(b()).optional(),theme:et(["light","dark"]).optional()}),Vo=I({icons:te(OS).optional()}),Bn=I({name:b(),title:b().optional()}),xg=Bn.extend({...Bn.shape,...Vo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),NS=gi(I({applyDefaults:Pe().optional()}),ge(b(),we())),MS=Al(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,gi(I({form:NS.optional(),url:ze.optional()}),ge(b(),we()).optional())),jS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({sampling:Be({createMessage:ze.optional()}).optional(),elicitation:Be({create:ze.optional()}).optional()}).optional()}),ZS=Be({list:ze.optional(),cancel:ze.optional(),requests:Be({tools:Be({call:ze.optional()}).optional()}).optional()}),DS=I({experimental:ge(b(),ze).optional(),sampling:I({context:ze.optional(),tools:ze.optional()}).optional(),elicitation:MS.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:jS.optional(),extensions:ge(b(),ze).optional()}),LS=ut.extend({protocolVersion:b(),capabilities:DS,clientInfo:xg}),wi=Ae.extend({method:j("initialize"),params:LS}),Dl=t=>wi.safeParse(t).success,qS=I({experimental:ge(b(),ze).optional(),logging:ze.optional(),completions:ze.optional(),prompts:I({listChanged:Pe().optional()}).optional(),resources:I({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:I({listChanged:Pe().optional()}).optional(),tasks:ZS.optional(),extensions:ge(b(),ze).optional()}),US=Oe.extend({protocolVersion:b(),capabilities:qS,serverInfo:xg,instructions:b().optional()}),Ll=mt.extend({method:j("notifications/initialized"),params:pt.optional()}),$i=Ae.extend({method:j("ping"),params:ut.optional()}),FS=I({progress:ue(),total:$e(ue()),message:$e(b())}),HS=I({...pt.shape,...FS.shape,progressToken:mg}),ki=mt.extend({method:j("notifications/progress"),params:HS}),BS=ut.extend({cursor:hg.optional()}),Jo=Ae.extend({params:BS.optional()}),Wo=Oe.extend({nextCursor:hg.optional()}),VS=et(["working","input_required","completed","failed","cancelled"]),Ko=I({taskId:b(),status:VS,ttl:ye([ue(),eg()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:$e(ue()),statusMessage:$e(b())}),Wn=Oe.extend({task:Ko}),JS=pt.merge(Ko),Go=mt.extend({method:j("notifications/tasks/status"),params:JS}),Si=Ae.extend({method:j("tasks/get"),params:ut.extend({taskId:b()})}),Ti=Oe.merge(Ko),Ei=Ae.extend({method:j("tasks/result"),params:ut.extend({taskId:b()})}),CZ=Oe.loose(),zi=Jo.extend({method:j("tasks/list")}),Ri=Wo.extend({tasks:te(Ko)}),Pi=Ae.extend({method:j("tasks/cancel"),params:ut.extend({taskId:b()})}),bg=Oe.merge(Ko),wg=I({uri:b(),mimeType:$e(b()),_meta:ge(b(),we()).optional()}),$g=wg.extend({text:b()}),ql=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),kg=wg.extend({blob:ql}),Xo=et(["user","assistant"]),Kn=I({audience:te(Xo).optional(),priority:ue().min(0).max(1).optional(),lastModified:Uo.datetime({offset:!0}).optional()}),Sg=I({...Bn.shape,...Vo.shape,uri:b(),description:$e(b()),mimeType:$e(b()),size:$e(ue()),annotations:Kn.optional(),_meta:$e(Be({}))}),WS=I({...Bn.shape,...Vo.shape,uriTemplate:b(),description:$e(b()),mimeType:$e(b()),annotations:Kn.optional(),_meta:$e(Be({}))}),Ii=Jo.extend({method:j("resources/list")}),KS=Wo.extend({resources:te(Sg)}),Ci=Jo.extend({method:j("resources/templates/list")}),GS=Wo.extend({resourceTemplates:te(WS)}),Ul=ut.extend({uri:b()}),XS=Ul,Ai=Ae.extend({method:j("resources/read"),params:XS}),YS=Oe.extend({contents:te(ye([$g,kg]))}),QS=mt.extend({method:j("notifications/resources/list_changed"),params:pt.optional()}),eT=Ul,tT=Ae.extend({method:j("resources/subscribe"),params:eT}),rT=Ul,nT=Ae.extend({method:j("resources/unsubscribe"),params:rT}),oT=pt.extend({uri:b()}),sT=mt.extend({method:j("notifications/resources/updated"),params:oT}),iT=I({name:b(),description:$e(b()),required:$e(Pe())}),aT=I({...Bn.shape,...Vo.shape,description:$e(b()),arguments:$e(te(iT)),_meta:$e(Be({}))}),Oi=Jo.extend({method:j("prompts/list")}),cT=Wo.extend({prompts:te(aT)}),uT=ut.extend({name:b(),arguments:ge(b(),b()).optional()}),Ni=Ae.extend({method:j("prompts/get"),params:uT}),Fl=I({type:j("text"),text:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),Hl=I({type:j("image"),data:ql,mimeType:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),Bl=I({type:j("audio"),data:ql,mimeType:b(),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),lT=I({type:j("tool_use"),name:b(),id:b(),input:ge(b(),we()),_meta:ge(b(),we()).optional()}),dT=I({type:j("resource"),resource:ye([$g,kg]),annotations:Kn.optional(),_meta:ge(b(),we()).optional()}),fT=Sg.extend({type:j("resource_link")}),Vl=ye([Fl,Hl,Bl,fT,dT]),pT=I({role:Xo,content:Vl}),mT=Oe.extend({description:b().optional(),messages:te(pT)}),hT=mt.extend({method:j("notifications/prompts/list_changed"),params:pt.optional()}),gT=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),yT=I({taskSupport:et(["required","optional","forbidden"]).optional()}),Tg=I({...Bn.shape,...Vo.shape,description:b().optional(),inputSchema:I({type:j("object"),properties:ge(b(),ze).optional(),required:te(b()).optional()}).catchall(we()),outputSchema:I({type:j("object"),properties:ge(b(),ze).optional(),required:te(b()).optional()}).catchall(we()).optional(),annotations:gT.optional(),execution:yT.optional(),_meta:ge(b(),we()).optional()}),Mi=Jo.extend({method:j("tools/list")}),_T=Wo.extend({tools:te(Tg)}),ji=Oe.extend({content:te(Vl).default([]),structuredContent:ge(b(),we()).optional(),isError:Pe().optional()}),AZ=ji.or(Oe.extend({toolResult:we()})),vT=Ho.extend({name:b(),arguments:ge(b(),we()).optional()}),Gn=Ae.extend({method:j("tools/call"),params:vT}),xT=mt.extend({method:j("notifications/tools/list_changed"),params:pt.optional()}),OZ=I({autoRefresh:Pe().default(!0),debounceMs:ue().int().nonnegative().default(300)}),Yo=et(["debug","info","notice","warning","error","critical","alert","emergency"]),bT=ut.extend({level:Yo}),Jl=Ae.extend({method:j("logging/setLevel"),params:bT}),wT=pt.extend({level:Yo,logger:b().optional(),data:we()}),$T=mt.extend({method:j("notifications/message"),params:wT}),kT=I({name:b().optional()}),ST=I({hints:te(kT).optional(),costPriority:ue().min(0).max(1).optional(),speedPriority:ue().min(0).max(1).optional(),intelligencePriority:ue().min(0).max(1).optional()}),TT=I({mode:et(["auto","required","none"]).optional()}),ET=I({type:j("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:te(Vl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:ge(b(),we()).optional()}),zT=Cl("type",[Fl,Hl,Bl]),yi=Cl("type",[Fl,Hl,Bl,lT,ET]),RT=I({role:Xo,content:ye([yi,te(yi)]),_meta:ge(b(),we()).optional()}),PT=Ho.extend({messages:te(RT),modelPreferences:ST.optional(),systemPrompt:b().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:ue().optional(),maxTokens:ue().int(),stopSequences:te(b()).optional(),metadata:ze.optional(),tools:te(Tg).optional(),toolChoice:TT.optional()}),IT=Ae.extend({method:j("sampling/createMessage"),params:PT}),Qo=Oe.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens"]).or(b())),role:Xo,content:zT}),Wl=Oe.extend({model:b(),stopReason:$e(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Xo,content:ye([yi,te(yi)])}),CT=I({type:j("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),AT=I({type:j("string"),title:b().optional(),description:b().optional(),minLength:ue().optional(),maxLength:ue().optional(),format:et(["email","uri","date","date-time"]).optional(),default:b().optional()}),OT=I({type:et(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ue().optional(),maximum:ue().optional(),default:ue().optional()}),NT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),default:b().optional()}),MT=I({type:j("string"),title:b().optional(),description:b().optional(),oneOf:te(I({const:b(),title:b()})),default:b().optional()}),jT=I({type:j("string"),title:b().optional(),description:b().optional(),enum:te(b()),enumNames:te(b()).optional(),default:b().optional()}),ZT=ye([NT,MT]),DT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:I({type:j("string"),enum:te(b())}),default:te(b()).optional()}),LT=I({type:j("array"),title:b().optional(),description:b().optional(),minItems:ue().optional(),maxItems:ue().optional(),items:I({anyOf:te(I({const:b(),title:b()}))}),default:te(b()).optional()}),qT=ye([DT,LT]),UT=ye([jT,ZT,qT]),FT=ye([UT,CT,AT,OT]),HT=Ho.extend({mode:j("form").optional(),message:b(),requestedSchema:I({type:j("object"),properties:ge(b(),FT),required:te(b()).optional()})}),BT=Ho.extend({mode:j("url"),message:b(),elicitationId:b(),url:b().url()}),VT=ye([HT,BT]),JT=Ae.extend({method:j("elicitation/create"),params:VT}),WT=pt.extend({elicitationId:b()}),KT=mt.extend({method:j("notifications/elicitation/complete"),params:WT}),Xn=Oe.extend({action:et(["accept","decline","cancel"]),content:Al(t=>t===null?void 0:t,ge(b(),ye([b(),ue(),Pe(),te(b())])).optional())}),GT=I({type:j("ref/resource"),uri:b()}),XT=I({type:j("ref/prompt"),name:b()}),YT=ut.extend({ref:ye([XT,GT]),argument:I({name:b(),value:b()}),context:I({arguments:ge(b(),b()).optional()}).optional()}),Zi=Ae.extend({method:j("completion/complete"),params:YT});QT=Oe.extend({completion:Be({values:te(b()).max(100),total:$e(ue().int()),hasMore:$e(Pe())})}),eE=I({uri:b().startsWith("file://"),name:b().optional(),_meta:ge(b(),we()).optional()}),tE=Ae.extend({method:j("roots/list"),params:ut.optional()}),Kl=Oe.extend({roots:te(eE)}),rE=mt.extend({method:j("notifications/roots/list_changed"),params:pt.optional()}),NZ=ye([$i,wi,Zi,Jl,Ni,Oi,Ii,Ci,Ai,tT,nT,Gn,Mi,Si,Ei,zi,Pi]),MZ=ye([bi,ki,Ll,rE,Go]),jZ=ye([xi,Qo,Wl,Xn,Kl,Ti,Ri,Wn]),ZZ=ye([$i,IT,JT,tE,Si,Ei,zi,Pi]),DZ=ye([bi,ki,$T,sT,QS,xT,hT,Go,KT]),LZ=ye([xi,US,QT,mT,cT,KS,GS,YS,ji,_T,Ti,Ri,Wn]),C=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===O.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ol(o.elicitations,r)}return new t(e,r,n)}},Ol=class extends C{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var ns=z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var ts=class{};ie._CodeOrName=ts;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends ts{constructor(e){if(super(),!ie.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ie.Name=pn;var ht=class extends ts{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof pn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ie._Code=ht;ie.nil=new ht("");function uy(t,...e){let r=[t[0]],n=0;for(;n<e.length;)sd(r,e[n]),r.push(t[++n]);return new ht(r)}ie._=uy;var od=new ht("+");function ly(t,...e){let r=[rs(t[0])],n=0;for(;n<e.length;)r.push(od),sd(r,e[n]),r.push(od,rs(t[++n]));return pE(r),new ht(r)}ie.str=ly;function sd(t,e){e instanceof ht?t.push(...e._items):e instanceof pn?t.push(e):t.push(gE(e))}ie.addCodeArg=sd;function pE(t){let e=1;for(;e<t.length-1;){if(t[e]===od){let r=mE(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function mE(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof pn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof pn))return`"${t}${e.slice(1)}`}function hE(t,e){return e.emptyStr()?t:t.emptyStr()?e:ly`${t}${e}`}ie.strConcat=hE;function gE(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:rs(Array.isArray(t)?t.join(","):t)}function yE(t){return new ht(rs(t))}ie.stringify=yE;function rs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=rs;function _E(t){return typeof t=="string"&&ie.IDENTIFIER.test(t)?new ht(`.${t}`):uy`[${t}]`}ie.getProperty=_E;function vE(t){if(typeof t=="string"&&ie.IDENTIFIER.test(t))return new ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ie.getEsmExportName=vE;function xE(t){return new ht(t.toString())}ie.regexpCode=xE});var cd=z(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.ValueScope=rt.ValueScopeName=rt.Scope=rt.varKinds=rt.UsedValueState=void 0;var tt=ns(),id=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Hi;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Hi||(rt.UsedValueState=Hi={}));rt.varKinds={const:new tt.Name("const"),let:new tt.Name("let"),var:new tt.Name("var")};var Bi=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof tt.Name?e:this.name(e)}name(e){return new tt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};rt.Scope=Bi;var Vi=class extends tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,tt._)`.${new tt.Name(r)}[${n}]`}};rt.ValueScopeName=Vi;var bE=(0,tt._)`\n`,ad=class extends Bi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?bE:tt.nil}}get(){return this._scope}name(e){return new Vi(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,tt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=tt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Hi.Started);let l=r(u);if(l){let d=this.opts.es5?rt.varKinds.var:rt.varKinds.const;s=(0,tt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,tt._)`${s}${l}${this.opts._n}`;else throw new id(u);c.set(u,Hi.Completed)})}return s}};rt.ValueScope=ad});var W=z(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var ne=ns(),zt=cd(),Er=ns();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return Er.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return Er.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return Er.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return Er.Name}});var Gi=cd();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return Gi.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return Gi.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return Gi.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return Gi.varKinds}});K.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var sr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ud=class extends sr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?zt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},Ji=class extends sr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Ki(e,this.rhs)}},ld=class extends Ji{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},dd=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},fd=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},pd=class extends sr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},md=class extends sr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Qn(this.code,e,r),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},os=class extends sr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(wE(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>gn(e,r.names),{})}},ir=class extends os{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hd=class extends os{},Yn=class extends ir{};Yn.kind="else";var mn=class t extends ir{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Yn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(dy(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Qn(this.condition,e,r),this}get names(){let e=super.names;return Ki(e,this.condition),this.else&&gn(e,this.else.names),e}};mn.kind="if";var hn=class extends ir{};hn.kind="for";var gd=class extends hn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Qn(this.iteration,e,r),this}get names(){return gn(super.names,this.iteration.names)}},yd=class extends hn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?zt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ki(super.names,this.from);return Ki(e,this.to)}},Wi=class extends hn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Qn(this.iterable,e,r),this}get names(){return gn(super.names,this.iterable.names)}},ss=class extends ir{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ss.kind="func";var is=class extends os{render(e){return"return "+super.render(e)}};is.kind="return";var _d=class extends ir{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&gn(e,this.catch.names),this.finally&&gn(e,this.finally.names),e}},as=class extends ir{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};as.kind="catch";var cs=class extends ir{render(e){return"finally"+super.render(e)}};cs.kind="finally";var vd=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
31
+ `:""},this._extScope=e,this._scope=new zt.Scope({parent:e}),this._nodes=[new hd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new ud(e,s,n)),s}const(e,r,n){return this._def(zt.varKinds.const,e,r,n)}let(e,r,n){return this._def(zt.varKinds.let,e,r,n)}var(e,r,n){return this._def(zt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ji(e,r,n))}add(e,r){return this._leafNode(new ld(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new md(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ne.addCodeArg)(r,o));return r.push("}"),new ne._Code(r)}if(e,r,n){if(this._blockNode(new mn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new mn(e))}else(){return this._elseNode(new Yn)}endIf(){return this._endBlockNode(mn,Yn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new gd(e),r)}forRange(e,r,n,o,s=this.opts.es5?zt.varKinds.var:zt.varKinds.let){let i=this._scope.toName(e);return this._for(new yd(s,i,r,n),()=>o(i))}forOf(e,r,n,o=zt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ne.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ne._)`${i}.length`,a=>{this.var(s,(0,ne._)`${i}[${a}]`),n(s)})}return this._for(new Wi("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?zt.varKinds.var:zt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Wi("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(hn)}label(e){return this._leafNode(new dd(e))}break(e){return this._leafNode(new fd(e))}return(e){let r=new is;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(is)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new _d;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new as(s),r(s)}return n&&(this._currNode=o.finally=new cs,this.code(n)),this._endBlockNode(as,cs)}throw(e){return this._leafNode(new pd(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ne.nil,n,o){return this._blockNode(new ss(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ss)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof mn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=vd;function gn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ki(t,e){return e instanceof ne._CodeOrName?gn(t,e.names):t}function Qn(t,e,r){if(t instanceof ne.Name)return n(t);if(!o(t))return t;return new ne._Code(t._items.reduce((s,i)=>(i instanceof ne.Name&&(i=n(i)),i instanceof ne._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ne._Code&&s._items.some(i=>i instanceof ne.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function wE(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function dy(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ne._)`!${xd(t)}`}K.not=dy;var $E=fy(K.operators.AND);function kE(...t){return t.reduce($E)}K.and=kE;var SE=fy(K.operators.OR);function TE(...t){return t.reduce(SE)}K.or=TE;function fy(t){return(e,r)=>e===ne.nil?r:r===ne.nil?e:(0,ne._)`${xd(e)} ${t} ${xd(r)}`}function xd(t){return t instanceof ne.Name?t:(0,ne._)`(${t})`}});var oe=z(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var fe=W(),EE=ns();function zE(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=zE;function RE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hy(t,e),!gy(e,t.self.RULES.all))}G.alwaysValidSchema=RE;function hy(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||vy(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=hy;function gy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=gy;function PE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=PE;function IE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,fe._)`${r}`}return(0,fe._)`${t}${e}${(0,fe.getProperty)(n)}`}G.schemaRefOrVal=IE;function CE(t){return yy(decodeURIComponent(t))}G.unescapeFragment=CE;function AE(t){return encodeURIComponent(wd(t))}G.escapeFragment=AE;function wd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=wd;function yy(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=yy;function OE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=OE;function py({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof fe.Name?(s instanceof fe.Name?t(o,s,i):e(o,s,i),i):s instanceof fe.Name?(e(o,i,s),s):r(s,i);return a===fe.Name&&!(c instanceof fe.Name)?n(o,c):c}}G.mergeEvaluated={props:py({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,fe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,fe._)`${r} || {}`).code((0,fe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,fe._)`${r} || {}`),$d(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:_y}),items:py({mergeNames:(t,e,r)=>t.if((0,fe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,fe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,fe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,fe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function _y(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,fe._)`{}`);return e!==void 0&&$d(t,r,e),r}G.evaluatedPropsToName=_y;function $d(t,e,r){Object.keys(r).forEach(n=>t.assign((0,fe._)`${e}${(0,fe.getProperty)(n)}`,!0))}G.setEvaluated=$d;var my={};function NE(t,e){return t.scopeValue("func",{ref:e,code:my[e.code]||(my[e.code]=new EE._Code(e.code))})}G.useFunc=NE;var bd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(bd||(G.Type=bd={}));function ME(t,e,r){if(t instanceof fe.Name){let n=e===bd.Num;return r?n?(0,fe._)`"[" + ${t} + "]"`:(0,fe._)`"['" + ${t} + "']"`:n?(0,fe._)`"/" + ${t}`:(0,fe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,fe.getProperty)(t).toString():"/"+wd(t)}G.getErrorPath=ME;function vy(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=vy});var ar=z(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var De=W(),jE={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};kd.default=jE});var us=z(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var se=W(),Xi=oe(),Je=ar();Le.keywordError={message:({keyword:t})=>(0,se.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,se.str)`"${t}" keyword must be ${e} ($data)`:(0,se.str)`"${t}" keyword is invalid ($data)`};function ZE(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=wy(t,e,r);n??(i||a)?xy(s,c):by(o,(0,se._)`[${c}]`)}Le.reportError=ZE;function DE(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=wy(t,e,r);xy(o,a),s||i||by(n,Je.default.vErrors)}Le.reportExtraError=DE;function LE(t,e){t.assign(Je.default.errors,e),t.if((0,se._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,se._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Le.resetErrorsCount=LE;function qE({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Je.default.errors,a=>{t.const(i,(0,se._)`${Je.default.vErrors}[${a}]`),t.if((0,se._)`${i}.instancePath === undefined`,()=>t.assign((0,se._)`${i}.instancePath`,(0,se.strConcat)(Je.default.instancePath,s.errorPath))),t.assign((0,se._)`${i}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,se._)`${i}.schema`,r),t.assign((0,se._)`${i}.data`,n))})}Le.extendErrors=qE;function xy(t,e){let r=t.const("err",e);t.if((0,se._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,se._)`[${r}]`),(0,se._)`${Je.default.vErrors}.push(${r})`),t.code((0,se._)`${Je.default.errors}++`)}function by(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,se._)`new ${t.ValidationError}(${e})`):(r.assign((0,se._)`${n}.errors`,e),r.return(!1))}var yn={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function wy(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,se._)`{}`:UE(t,e,r)}function UE(t,e,r={}){let{gen:n,it:o}=t,s=[FE(o,r),HE(t,r)];return BE(t,e,s),n.object(...s)}function FE({errorPath:t},{instancePath:e}){let r=e?(0,se.str)`${t}${(0,Xi.getErrorPath)(e,Xi.Type.Str)}`:t;return[Je.default.instancePath,(0,se.strConcat)(Je.default.instancePath,r)]}function HE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,se.str)`${e}/${t}`;return r&&(o=(0,se.str)`${o}${(0,Xi.getErrorPath)(r,Xi.Type.Str)}`),[yn.schemaPath,o]}function BE(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([yn.keyword,o],[yn.params,typeof e=="function"?e(t):e||(0,se._)`{}`]),c.messages&&n.push([yn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([yn.schema,i],[yn.parentSchema,(0,se._)`${l}${d}`],[Je.default.data,s]),u&&n.push([yn.propertyName,u])}});var ky=z(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;var VE=us(),JE=W(),WE=ar(),KE={message:"boolean schema is false"};function GE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?$y(t,!1):typeof r=="object"&&r.$async===!0?e.return(WE.default.data):(e.assign((0,JE._)`${n}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=GE;function XE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),$y(t)):r.var(e,!0)}eo.boolOrEmptySchema=XE;function $y(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,VE.reportError)(o,KE,void 0,e)}});var Sd=z(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.getRules=to.isJSONType=void 0;var YE=["string","number","integer","boolean","null","object","array"],QE=new Set(YE);function ez(t){return typeof t=="string"&&QE.has(t)}to.isJSONType=ez;function tz(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}to.getRules=tz});var Td=z(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function rz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Sy(t,n)}zr.schemaHasRulesForType=rz;function Sy(t,e){return e.rules.some(r=>Ty(t,r))}zr.shouldUseGroup=Sy;function Ty(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}zr.shouldUseRule=Ty});var ls=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var nz=Sd(),oz=Td(),sz=us(),V=W(),Ey=oe(),ro;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ro||(qe.DataType=ro={}));function iz(t){let e=zy(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}qe.getSchemaTypes=iz;function zy(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(nz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=zy;function az(t,e){let{gen:r,data:n,opts:o}=t,s=cz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,oz.schemaHasRulesForType)(t,e[0]));if(i){let a=zd(e,n,o.strictNumbers,ro.Wrong);r.if(a,()=>{s.length?uz(t,e,s):Rd(t)})}return i}qe.coerceAndCheckDataType=az;var Ry=new Set(["string","number","integer","boolean","null"]);function cz(t,e){return e?t.filter(r=>Ry.has(r)||e==="array"&&r==="array"):[]}function uz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,V._)`typeof ${o}`),a=n.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&n.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(zd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,V._)`${a} !== undefined`);for(let u of r)(Ry.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Rd(t),n.endIf(),n.if((0,V._)`${a} !== undefined`,()=>{n.assign(o,a),lz(t,a)});function c(u){switch(u){case"string":n.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${i} == "boolean" || ${o} === null
32
+ || (${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 lz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,V._)`${e} !== undefined`,()=>t.assign((0,V._)`${e}[${r}]`,n))}function Ed(t,e,r,n=ro.Correct){let o=n===ro.Correct?V.operators.EQ:V.operators.NEQ,s;switch(t){case"null":return(0,V._)`${e} ${o} null`;case"array":s=(0,V._)`Array.isArray(${e})`;break;case"object":s=(0,V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,V._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${e} ${o} ${t}`}return n===ro.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${e} == "number"`,a,r?(0,V._)`isFinite(${e})`:V.nil)}}qe.checkDataType=Ed;function zd(t,e,r,n){if(t.length===1)return Ed(t[0],e,r,n);let o,s=(0,Ey.toHash)(t);if(s.array&&s.object){let i=(0,V._)`typeof ${e} != "object"`;o=s.null?i:(0,V._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(let i in s)o=(0,V.and)(o,Ed(i,e,r,n));return o}qe.checkDataTypes=zd;var dz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,V._)`{type: ${t}}`:(0,V._)`{type: ${e}}`};function Rd(t){let e=fz(t);(0,sz.reportError)(e,dz)}qe.reportTypeError=Rd;function fz(t){let{gen:e,data:r,schema:n}=t,o=(0,Ey.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Iy=z(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.assignDefaults=void 0;var no=W(),pz=oe();function mz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Py(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Py(t,s,o.default))}Yi.assignDefaults=mz;function Py(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,no._)`${s}${(0,no.getProperty)(e)}`;if(o){(0,pz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,no._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,no._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,no._)`${a} = ${(0,no.stringify)(r)}`)}});var gt=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var _e=W(),Pd=oe(),Rr=ar(),hz=oe();function gz(t,e){let{gen:r,data:n,it:o}=t;r.if(Cd(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}de.checkReportMissingProp=gz;function yz({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(Cd(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}de.checkMissingProp=yz;function _z(t,e){t.setParams({missingProperty:e},!0),t.error()}de.reportMissingProp=_z;function Cy(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Cy;function Id(t,e,r){return(0,_e._)`${Cy(t)}.call(${e}, ${r})`}de.isOwnProperty=Id;function vz(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${Id(t,e,r)}`:o}de.propertyInData=vz;function Cd(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(Id(t,e,r))):o}de.noPropertyInData=Cd;function Ay(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=Ay;function xz(t,e){return Ay(e).filter(r=>!(0,Pd.alwaysValidSchema)(t,e[r]))}de.schemaProperties=xz;function bz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,_e._)`${t}, ${e}, ${n}${o}`:e,d=[[Rr.default.instancePath,(0,_e.strConcat)(Rr.default.instancePath,s)],[Rr.default.parentData,i.parentData],[Rr.default.parentDataProperty,i.parentDataProperty],[Rr.default.rootData,Rr.default.rootData]];i.opts.dynamicRef&&d.push([Rr.default.dynamicAnchors,Rr.default.dynamicAnchors]);let m=(0,_e._)`${l}, ${r.object(...d)}`;return c!==_e.nil?(0,_e._)`${a}.call(${c}, ${m})`:(0,_e._)`${a}(${m})`}de.callValidateCode=bz;var wz=(0,_e._)`new RegExp`;function $z({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${o.code==="new RegExp"?wz:(0,hz.useFunc)(t,o)}(${r}, ${n})`})}de.usePattern=$z;function kz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,_e._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Pd.Type.Num},s),e.if((0,_e.not)(s),a)})}}de.validateArray=kz;function Sz(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Pd.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,_e._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}de.validateUnion=Sz});var My=z(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateKeywordUsage=Ft.validSchemaType=Ft.funcKeywordCode=Ft.macroKeywordCode=void 0;var We=W(),_n=ar(),Tz=gt(),Ez=us();function zz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ny(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ft.macroKeywordCode=zz;function Rz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Iz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Ny(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)g(),e.modifying&&Oy(t),h(()=>t.error());else{let _=e.async?p():f();e.modifying&&Oy(t),h(()=>Pz(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),v=>n.assign(d,!1).if((0,We._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${v}.errors`),()=>n.throw(v))),_}function f(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let v=c.opts.passContext?_n.default.this:_n.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,Tz.callValidateCode)(t,l,v,y)}`,e.modifying)}function h(_){var v;n.if((0,We.not)((v=e.valid)!==null&&v!==void 0?v:d),_)}}Ft.funcKeywordCode=Rz;function Oy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function Pz(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(_n.default.vErrors,(0,We._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,We._)`${_n.default.vErrors}.length`),(0,Ez.extendErrors)(t)},()=>t.error())}function Iz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ny(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}function Cz(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ft.validSchemaType=Cz;function Az({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ft.validateKeywordUsage=Az});var Zy=z(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.extendSubschemaMode=Pr.extendSubschemaData=Pr.getSubschema=void 0;var Ht=W(),jy=oe();function Oz(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,jy.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Pr.getSubschema=Oz;function Nz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,m=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Ht.str)`${u}${(0,jy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Pr.extendSubschemaData=Nz;function Mz(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Pr.extendSubschemaMode=Mz});var Ad=z((rL,Dy)=>{"use strict";Dy.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var qy=z((nL,Ly)=>{"use strict";var Ir=Ly.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Qi(e,n,o,t,"",t)};Ir.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ir.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ir.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ir.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Qi(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Ir.arrayKeywords)for(var m=0;m<d.length;m++)Qi(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in Ir.propsKeywords){if(d&&typeof d=="object")for(var p in d)Qi(t,e,r,d[p],o+"/"+l+"/"+jz(p),s,o,l,n,p)}else(l in Ir.keywords||t.allKeys&&!(l in Ir.skipKeywords))&&Qi(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function jz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ds=z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.getSchemaRefs=nt.resolveUrl=nt.normalizeId=nt._getFullPath=nt.getFullPath=nt.inlineRef=void 0;var Zz=oe(),Dz=Ad(),Lz=qy(),qz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Uz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Od(t):e?Uy(t)<=e:!1}nt.inlineRef=Uz;var Fz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Od(t){for(let e in t){if(Fz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Od)||typeof r=="object"&&Od(r))return!0}return!1}function Uy(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!qz.has(r)&&(typeof t[r]=="object"&&(0,Zz.eachItem)(t[r],n=>e+=Uy(n)),e===1/0))return 1/0}return e}function Fy(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return Hy(t,n)}nt.getFullPath=Fy;function Hy(t,e){return t.serialize(e).split("#")[0]+"#"}nt._getFullPath=Hy;var Hz=/#\/?$/;function oo(t){return t?t.replace(Hz,""):""}nt.normalizeId=oo;function Bz(t,e,r){return r=oo(r),t.resolve(e,r)}nt.resolveUrl=Bz;var Vz=/^[a-z_][-a-z0-9._]*$/i;function Jz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=oo(t[r]||e),s={"":o},i=Fy(n,o,!1),a={},c=new Set;return Lz(t,{allKeys:!0},(d,m,p,f)=>{if(f===void 0)return;let g=i+m,h=s[f];typeof d[r]=="string"&&(h=_.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[m]=h;function _(y){let x=this.opts.uriResolver.resolve;if(y=oo(h?x(h,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==oo(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function v(y){if(typeof y=="string"){if(!Vz.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,m,p){if(m!==void 0&&!Dz(d,m))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}nt.getSchemaRefs=Jz});var ms=z(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getData=Cr.KeywordCxt=Cr.validateFunctionCode=void 0;var Ky=ky(),By=ls(),Md=Td(),ea=ls(),Wz=Iy(),ps=My(),Nd=Zy(),Z=W(),F=ar(),Kz=ds(),cr=oe(),fs=us();function Gz(t){if(Yy(t)&&(Qy(t),Xy(t))){Qz(t);return}Gy(t,()=>(0,Ky.topBoolOrEmptySchema)(t))}Cr.validateFunctionCode=Gz;function Gy({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${Vy(r,o)}`),Yz(t,o),t.code(s)}):t.func(e,(0,Z._)`${F.default.data}, ${Xz(o)}`,n.$async,()=>t.code(Vy(r,o)).code(s))}function Xz(t){return(0,Z._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,Z._)`, ${F.default.dynamicAnchors}={}`:Z.nil}}={}`}function Yz(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,Z._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,Z._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,Z._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,Z._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,Z._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,Z._)`""`),t.var(F.default.parentData,(0,Z._)`undefined`),t.var(F.default.parentDataProperty,(0,Z._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,Z._)`{}`)})}function Qz(t){let{schema:e,opts:r,gen:n}=t;Gy(t,()=>{r.$comment&&e.$comment&&t_(t),oR(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&eR(t),e_(t),aR(t)})}function eR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function Vy(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function tR(t,e){if(Yy(t)&&(Qy(t),Xy(t))){rR(t,e);return}(0,Ky.boolOrEmptySchema)(t,e)}function Xy({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Yy(t){return typeof t.schema!="boolean"}function rR(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&t_(t),sR(t),iR(t);let s=n.const("_errs",F.default.errors);e_(t,s),n.var(e,(0,Z._)`${s} === ${F.default.errors}`)}function Qy(t){(0,cr.checkUnknownRules)(t),nR(t)}function e_(t,e){if(t.opts.jtd)return Jy(t,[],!1,e);let r=(0,By.getSchemaTypes)(t.schema),n=(0,By.coerceAndCheckDataType)(t,r);Jy(t,r,!n,e)}function nR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,cr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function oR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,cr.checkStrictMode)(t,"default is ignored in the schema root")}function sR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Kz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function iR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function t_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function aR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,Z._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,F.default.vErrors),s.unevaluated&&cR(t),e.return((0,Z._)`${F.default.errors} === 0`))}function cR({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Jy(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,cr.schemaHasRulesButRef)(s,l))){o.block(()=>n_(t,"$ref",l.all.$ref.definition));return}c.jtd||uR(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Md.shouldUseGroup)(s,m)&&(m.type?(o.if((0,ea.checkDataType)(m.type,i,c.strictNumbers)),Wy(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,ea.reportTypeError)(t)),o.endIf()):Wy(t,m),a||o.if((0,Z._)`${F.default.errors} === ${n||0}`))}}function Wy(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Wz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Md.shouldUseRule)(n,s)&&n_(t,s.keyword,s.definition,e.type)})}function uR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(lR(t,e),t.opts.allowUnionTypes||dR(t,e),fR(t,t.dataTypes))}function lR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{r_(t.dataTypes,r)||jd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),mR(t,e)}}function dR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&jd(t,"use allowUnionTypes to allow union type keyword")}function fR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Md.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>pR(e,i))&&jd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function pR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function r_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function mR(t,e){let r=[];for(let n of t.dataTypes)r_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function jd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,cr.checkStrictMode)(t,e,t.opts.strictTypes)}var ta=class{constructor(e,r,n){if((0,ps.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,cr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",o_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ps.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,Z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Z._)`${r} !== undefined && (${(0,Z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?fs.reportExtraError:fs.reportError)(this,this.def.error,r)}$dataError(){(0,fs.reportError)(this,this.def.$dataError||fs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,fs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,ea.checkDataTypes)(c,r,s.opts.strictNumbers,ea.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,Nd.getSubschema)(this.it,e);(0,Nd.extendSubschemaData)(n,this.it,e),(0,Nd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return tR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=cr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=cr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,Z.Name)),!0}};Cr.KeywordCxt=ta;function n_(t,e,r,n){let o=new ta(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ps.funcKeywordCode)(o,r):"macro"in r?(0,ps.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ps.funcKeywordCode)(o,r)}var hR=/^\/(?:[^~]|~0|~1)*$/,gR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function o_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!hR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=gR.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,Z._)`${s}${(0,Z.getProperty)((0,cr.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Cr.getData=o_});var ra=z(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Zd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Dd.default=Zd});var hs=z(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Ld=ds(),qd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ld.resolveUrl)(e,r,n),this.missingSchema=(0,Ld.normalizeId)((0,Ld.getFullPath)(e,this.missingRef))}};Ud.default=qd});var oa=z(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Rt=W(),yR=ra(),vn=ar(),Pt=ds(),s_=oe(),_R=ms(),so=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=so;function Hd(t){let e=i_.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Rt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:yR.default,code:(0,Rt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:vn.default.data,parentData:vn.default.parentData,parentDataProperty:vn.default.parentDataProperty,dataNames:[vn.default.data],dataPathArr:[Rt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Rt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Rt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,_R.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(vn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${vn.default.self}`,`${vn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:g}=u;p.evaluated={props:f instanceof Rt.Name?void 0:f,items:g instanceof Rt.Name?void 0:g,dynamicProps:f instanceof Rt.Name,dynamicItems:g instanceof Rt.Name},p.source&&(p.source.evaluated=(0,Rt.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}yt.compileSchema=Hd;function vR(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=wR.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new so({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=xR.call(this,s)}yt.resolveRef=vR;function xR(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Hd.call(this,t)}function i_(t){for(let e of this._compilations)if(bR(e,t))return e}yt.getCompilingSchema=i_;function bR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function wR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||na.call(this,t,e)}function na(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Fd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=na.call(this,t,i);return typeof a?.schema!="object"?void 0:Fd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Hd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new so({schema:a,schemaId:c,root:t,baseId:o})}return Fd.call(this,r,i)}}yt.resolveSchema=na;var $R=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,s_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!$R.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,s_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=na.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new so({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var a_=z((uL,kR)=>{kR.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Gd=z((lL,h_)=>{"use strict";var SR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Vd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),TR=RegExp.prototype.test.bind(/^\d*$/u),xn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Jd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),u_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Wd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),ER=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ot=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)ot[e]="%"+t[e>>4]+t[e&15]}function Ue(t){return t<2048?ot[192|t>>6]+ot[128|t&63]:t<65536?ot[224|t>>12]+ot[128|t>>6&63]+ot[128|t&63]:ot[240|t>>18]+ot[128|t>>12&63]+ot[128|t>>6&63]+ot[128|t&63]}function zR(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var RR=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),PR=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),IR=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),CR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function AR(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!IR(t[e])){if(t[e]==="%"&&e+2<t.length&&xn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function c_(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function OR(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!Vd(c))return;s+=2;continue}if(!RR(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:c_(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return c_(i)}function Bd(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&PR(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(NR(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!AR(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=OR(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function NR(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function l_(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function MR(t){if(t===""||t[0]==="/")return l_(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var jR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZR=/[@/?#:]/g,DR=/[@/?#]/g;function d_(t,e){let r=e?DR:ZR;return r.lastIndex=0,t.replace(r,n=>jR[n])}function f_(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Jd(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function LR(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Jd(i)?e+=i:e+="%"+s,r+=2;continue}}if(u_(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=m_(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function qR(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(xn(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),u_(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=ot[i];else if(i<55296||i>57343)r+=Ue(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=Ue(65536+(i-55296<<10)+(a-56320)),o++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function Kd(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(xn(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=ot[s];else if(s<55296||s>57343)r+=Ue(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Ue(65536+(s-55296<<10)+(i-56320)),n++):r+=Ue(65533)}else r+=Ue(65533)}}return r}function p_(t){return Kd(t,ER)}function UR(t){return Kd(t,Wd)}function FR(t){return Kd(t,Wd)}function m_(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function HR(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(xn(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Jd(i)?e+=i:e+="%"+s,r+=2;continue}}if(Wd(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=m_(o)?n:ot[o];else if(o<55296||o>57343)e+=Ue(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=Ue(65536+(o-55296<<10)+(s-56320)),r++):e+=Ue(65533)}else e+=Ue(65533)}}return e}function BR(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(xn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function VR(t){let e=[];if(t.userinfo!==void 0&&(e.push(p_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!Vd(r)){let n=Bd(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=f_(r,!0),n=Bd(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=d_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!TR(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}h_.exports={nonSimpleDomain:CR,recomposeAuthority:VR,reescapeHostDelimiters:d_,normalizePercentEncoding:f_,normalizePathEncoding:LR,serializePathEncoding:qR,normalizeQueryFragmentEncoding:HR,encodeUserinfo:p_,encodeQuery:UR,encodeFragment:FR,escapePreservingEscapes:BR,removeDotSegments:l_,removeDotSegmentsRelative:MR,isIPv4:Vd,isUUID:SR,normalizeIPv6:Bd,stringArrayToHexStripped:zR}});var x_=z((dL,v_)=>{"use strict";var{isUUID:JR}=Gd(),WR=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,KR=["http","https","ws","wss","urn","urn:uuid"];function GR(t){return KR.indexOf(t)!==-1}function Xd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function g_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function y_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function XR(t){return t.secure=Xd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function YR(t){if((t.port===(Xd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function QR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WR);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Yd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function e1(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Yd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function t1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!JR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function r1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var __={scheme:"http",domainHost:!0,parse:g_,serialize:y_},n1={scheme:"https",domainHost:__.domainHost,parse:g_,serialize:y_},sa={scheme:"ws",domainHost:!0,parse:XR,serialize:YR},o1={scheme:"wss",domainHost:sa.domainHost,parse:sa.parse,serialize:sa.serialize},s1={scheme:"urn",parse:QR,serialize:e1,skipNormalize:!0},i1={scheme:"urn:uuid",parse:t1,serialize:r1,skipNormalize:!0},ia={http:__,https:n1,ws:sa,wss:o1,urn:s1,"urn:uuid":i1};Object.setPrototypeOf(ia,null);function Yd(t){return t&&(ia[t]||ia[t.toLowerCase()])||void 0}v_.exports={wsIsSecure:Xd,SCHEMES:ia,isValidSchemeName:GR,getSchemeHandler:Yd}});var N_=z((fL,da)=>{"use strict";var{normalizeIPv6:S_,removeDotSegments:ys,removeDotSegmentsRelative:T_,recomposeAuthority:a1,normalizePercentEncoding:Qd,normalizePathEncoding:c1,serializePathEncoding:b_,normalizeQueryFragmentEncoding:w_,encodeQuery:u1,encodeFragment:l1,reescapeHostDelimiters:d1,isIPv4:E_,nonSimpleDomain:f1}=Gd(),{SCHEMES:z_,getSchemeHandler:ef}=x_(),R_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,P_="URI scheme is malformed.",aa="URI host is malformed.",p1=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function $_(t){let e=String(t);if(!R_.test(e))throw new TypeError(P_);return e}function m1(t,e){return typeof t=="string"?t=$1(t,e):typeof t=="object"&&(t=ua(bn(t,e),e)),t}function h1(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=ca(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:m,malformedSchemeSpecific:p,malformedHost:f,malformedScheme:g}=ca(e,n);if(s||d||i||m||a||p||c||f||u||g)throw new Error(o.error||l.error||"URI is malformed.");let h=I_(o,l,n,!0),_=ef(r&&r.scheme||h.scheme),v=h.host,y=v!==void 0&&v!==""&&(E_(v)||S_(v).isIPV6);if(A_(h,r||{},_,y))throw new Error(aa);C_(h,r||{},_,y);let x=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(h.error&&!x)throw new Error(h.error);return n.skipEscape=!0,bn(h,n)}function I_(t,e,r,n){let o={};if(n||(t=ua(bn(t,r),r),e=ua(bn(e,r),r)),r=r||{},!r.tolerant&&e.scheme)o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ys(e.path||""),o.query=e.query;else{if(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ys(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ys(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=t.scheme===void 0&&!s&&o.path[0]!=="/"?T_(o.path):ys(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function g1(t,e,r){let n=k_(t,r),o=k_(e,r);return n!==void 0&&o!==void 0&&n===o}function bn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[];r.scheme&&(r.scheme=$_(r.scheme));let s=ef(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Qd(r.path):r.path=b_(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=$_(r.scheme),o.push(r.scheme,":"));let u=a1(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=a&&l[0]!=="/"?T_(l):ys(l)),a&&(l=b_(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",u1(r.query)),r.fragment!==void 0&&o.push("#",l1(r.fragment)),o.join("")}var y1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,_1=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,v1=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function x1(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function gs(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function la(t){return t[0]==="["&&t[t.length-1]==="]"}function b1(t){let e=t[4];return gs(t[3])||e!==void 0&&!la(e)&&gs(e)||gs(t[6])||gs(t[7])||gs(t[8])}function C_(t,e,r,n){if(A_(t,e,r,n))return t.error=t.error||aa,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&f1(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!w1(o))return t.error=t.error||aa,!0;t.host=o.hostname}return!1}function A_(t,e,r,n){return!!(t.host&&n===!1&&!la(t.host)&&(e.domainHost||r&&r.domainHost)&&p1.test(t.host))}function w1(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function ca(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(_1);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let m=t.match(v1);if(m!==null){let f=m[1],g=f.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=t.match(y1);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(R_.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||P_,u=!0)),s=b1(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let f=x1(n,p);if(f!==void 0&&(n.error=n.error||f,o=!0),n.host)if(E_(n.host)===!1){let _=la(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=S_(n.host);l=y.isIPV6||y.isIPVFuture===!0,c=v&&(!_||y.error===!0),n.host=l?y.host:y.host.toLowerCase(),c&&(n.error=n.error||aa,o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let g=ef(r.scheme||n.scheme);if(c||(a=C_(n,r,g,l)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let h=l?n.host:Qd(n.host,!0);l||(h=Qd(h.toLowerCase())),n.host=l||r.scheme!=="null"?d1(h,l):h}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=c1(n.path)),n.query&&(n.query=w_(n.query)),n.fragment&&(n.fragment=w_(n.fragment))),g&&g.parse&&(g.parse(n,r),g===z_.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function ua(t,e){return ca(t,e).parsed}function $1(t,e){return O_(t,e).normalized}function O_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=ca(t,e);return{normalized:n||o||s||i||a?t:bn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function k_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:bn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=O_(r,e);return o||s||i||a||c?void 0:n}var tf={SCHEMES:z_,normalize:m1,resolve:h1,resolveComponent:I_,equal:g1,serialize:bn,parse:ua};da.exports=tf;da.exports.default=tf;da.exports.fastUri=tf});var j_=z(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var M_=N_();M_.code='require("ajv/dist/runtime/uri").default';rf.default=M_});var B_=z(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=void 0;var k1=ms();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return k1.KeywordCxt}});var io=W();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return io._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return io.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return io.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return io.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return io.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return io.CodeGen}});var S1=ra(),U_=hs(),T1=Sd(),_s=oa(),E1=W(),vs=ds(),fa=ls(),of=oe(),Z_=a_(),z1=j_(),F_=(t,e)=>new RegExp(t,e);F_.code="new RegExp";var R1=["removeAdditional","useDefaults","coerceTypes"],P1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),I1={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},C1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},D_=200;function A1(t){var e,r,n,o,s,i,a,c,u,l,d,m,p,f,g,h,_,v,y,x,$,N,A,ae,ce;let Re=t.strict,H=(e=t.code)===null||e===void 0?void 0:e.optimize,xe=H===!0||H===void 0?1:H||0,Mt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:F_,qr=(o=t.uriResolver)!==null&&o!==void 0?o:z1.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Re)!==null&&m!==void 0?m:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:xe,regExp:Mt}:{optimize:xe,regExp:Mt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:D_,loopEnum:(h=t.loopEnum)!==null&&h!==void 0?h:D_,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(A=t.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(ce=t.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:qr}}var xs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...A1(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new E1.ValueScope({scope:{},prefixes:P1,es5:r,lines:n}),this.logger=D1(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,T1.getRules)(),L_.call(this,I1,e,"NOT SUPPORTED"),L_.call(this,C1,e,"DEPRECATED","warn"),this._metaOpts=j1.call(this),e.formats&&N1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&M1.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),O1.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Z_;n==="id"&&(o={...Z_},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let m=this._addSchema(l,d);return m.validate||i.call(this,m)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof U_.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,vs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=q_.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new _s.SchemaEnv({schema:{},schemaId:n});if(r=_s.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=q_.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,vs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(q1.call(this,n,r),!r)return(0,of.eachItem)(n,s=>nf.call(this,s)),this;F1.call(this,r);let o={...r,type:(0,fa.getJSONTypes)(r.type),schemaType:(0,fa.getJSONTypes)(r.schemaType)};return(0,of.eachItem)(n,o.type.length===0?s=>nf.call(this,s,o):s=>o.type.forEach(i=>nf.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=H_(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,vs.normalizeId)(i||n);let u=vs.getSchemaRefs.call(this,e,n);return c=new _s.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):_s.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{_s.compileSchema.call(this,e)}finally{this.opts=r}}};xs.ValidationError=S1.default;xs.MissingRefError=U_.default;Ne.default=xs;function L_(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function q_(t){return t=(0,vs.normalizeId)(t),this.schemas[t]||this.refs[t]}function O1(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function N1(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function M1(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function j1(){let t={...this.opts};for(let e of R1)delete t[e];return t}var Z1={log(){},warn(){},error(){}};function D1(t){if(t===!1)return Z1;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var L1=/^[a-z_$][a-z0-9_$:-]*$/i;function q1(t,e){let{RULES:r}=this;if((0,of.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!L1.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function nf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,fa.getJSONTypes)(e.type),schemaType:(0,fa.getJSONTypes)(e.schemaType)}};e.before?U1.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function U1(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function F1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=H_(e)),t.validateSchema=this.compile(e,!0))}var H1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function H_(t){return{anyOf:[t,H1]}}});var V_=z(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var B1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sf.default=B1});var G_=z(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.callRef=wn.getValidate=void 0;var V1=hs(),J_=gt(),st=W(),ao=ar(),W_=oa(),pa=oe(),J1={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=W_.resolveRef.call(c,u,o,r);if(l===void 0)throw new V1.default(n.opts.uriResolver,o,r);if(l instanceof W_.SchemaEnv)return m(l);return p(l);function d(){if(s===u)return ma(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return ma(t,(0,st._)`${f}.validate`,u,u.$async)}function m(f){let g=K_(t,f);ma(t,g,f,f.$async)}function p(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,st.stringify)(f)}:{ref:f}),h=e.name("valid"),_=t.subschema({schema:f,dataTypes:[],schemaPath:st.nil,topSchemaRef:g,errSchemaPath:r},h);t.mergeEvaluated(_),t.ok(h)}}};function K_(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:e})}.validate`}wn.getValidate=K_;function ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ao.default.this:st.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,st._)`await ${(0,J_.callValidateCode)(t,e,u)}`),p(e),i||o.assign(f,!0)},g=>{o.if((0,st._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),m(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,J_.callValidateCode)(t,e,u),()=>p(e),()=>m(e))}function m(f){let g=(0,st._)`${f}.errors`;o.assign(ao.default.vErrors,(0,st._)`${ao.default.vErrors} === null ? ${g} : ${ao.default.vErrors}.concat(${g})`),o.assign(ao.default.errors,(0,st._)`${ao.default.vErrors}.length`)}function p(f){var g;if(!s.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(s.props=pa.mergeEvaluated.props(o,h.props,s.props));else{let _=o.var("props",(0,st._)`${f}.evaluated.props`);s.props=pa.mergeEvaluated.props(o,_,s.props,st.Name)}if(s.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(s.items=pa.mergeEvaluated.items(o,h.items,s.items));else{let _=o.var("items",(0,st._)`${f}.evaluated.items`);s.items=pa.mergeEvaluated.items(o,_,s.items,st.Name)}}}wn.callRef=ma;wn.default=J1});var X_=z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var W1=V_(),K1=G_(),G1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",W1.default,K1.default];af.default=G1});var Y_=z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var ha=W(),Ar=ha.operators,ga={maximum:{okStr:"<=",ok:Ar.LTE,fail:Ar.GT},minimum:{okStr:">=",ok:Ar.GTE,fail:Ar.LT},exclusiveMaximum:{okStr:"<",ok:Ar.LT,fail:Ar.GTE},exclusiveMinimum:{okStr:">",ok:Ar.GT,fail:Ar.LTE}},X1={message:({keyword:t,schemaCode:e})=>(0,ha.str)`must be ${ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ha._)`{comparison: ${ga[t].okStr}, limit: ${e}}`},Y1={keyword:Object.keys(ga),type:"number",schemaType:"number",$data:!0,error:X1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ha._)`${r} ${ga[e].fail} ${n} || isNaN(${r})`)}};cf.default=Y1});var Q_=z(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var bs=W(),Q1={message:({schemaCode:t})=>(0,bs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bs._)`{multipleOf: ${t}}`},eP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Q1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,bs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bs._)`${i} !== parseInt(${i})`;t.fail$data((0,bs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};uf.default=eP});var t0=z(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});function e0(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}lf.default=e0;e0.code='require("ajv/dist/runtime/ucs2length").default'});var r0=z(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var $n=W(),tP=oe(),rP=t0(),nP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$n.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$n._)`{limit: ${t}}`},oP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$n.operators.GT:$n.operators.LT,i=o.opts.unicode===!1?(0,$n._)`${r}.length`:(0,$n._)`${(0,tP.useFunc)(t.gen,rP.default)}(${r})`;t.fail$data((0,$n._)`${i} ${s} ${n}`)}};df.default=oP});var n0=z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var sP=gt(),iP=oe(),co=W(),aP={message:({schemaCode:t})=>(0,co.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,co._)`{pattern: ${t}}`},cP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:aP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,co._)`new RegExp`:(0,iP.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,co._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,co._)`!${l}`)}else{let c=(0,sP.usePattern)(t,o);t.fail$data((0,co._)`!${c}.test(${r})`)}}};ff.default=cP});var o0=z(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var ws=W(),uP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},lP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:uP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ws.operators.GT:ws.operators.LT;t.fail$data((0,ws._)`Object.keys(${r}).length ${o} ${n}`)}};pf.default=lP});var s0=z(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var $s=gt(),ks=W(),dP=oe(),fP={message:({params:{missingProperty:t}})=>(0,ks.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ks._)`{missingProperty: ${t}}`},pP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:fP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let g of r)if(p?.[g]===void 0&&!f.has(g)){let h=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,dP.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ks.nil,d);else for(let p of r)(0,$s.checkReportMissingProp)(t,p)}function l(){let p=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>m(p,f)),t.ok(f)}else e.if((0,$s.checkMissingProp)(t,r,p)),(0,$s.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,$s.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function m(p,f){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(f,(0,$s.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ks.not)(f),()=>{t.error(),e.break()})},ks.nil)}}};mf.default=pP});var i0=z(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Ss=W(),mP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ss.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ss._)`{limit: ${t}}`},hP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:mP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ss.operators.GT:Ss.operators.LT;t.fail$data((0,Ss._)`${r}.length ${o} ${n}`)}};hf.default=hP});var ya=z(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var a0=Ad();a0.code='require("ajv/dist/runtime/equal").default';gf.default=a0});var c0=z(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var yf=ls(),Me=W(),gP=oe(),yP=ya(),_P={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},vP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:_P,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,yf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Me._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,Me._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,Me._)`${f} > 1`,()=>(d()?m:p)(f,g))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function m(f,g){let h=e.name("item"),_=(0,yf.checkDataTypes)(u,h,a.opts.strictNumbers,yf.DataType.Wrong),v=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${f}--;`,()=>{e.let(h,(0,Me._)`${r}[${f}]`),e.if(_,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${h} == "string"`,(0,Me._)`${h} += "_"`),e.if((0,Me._)`typeof ${v}[${h}] == "number"`,()=>{e.assign(g,(0,Me._)`${v}[${h}]`),t.error(),e.assign(c,!1).break()}).code((0,Me._)`${v}[${h}] = ${f}`)})}function p(f,g){let h=(0,gP.useFunc)(e,yP.default),_=e.name("outer");e.label(_).for((0,Me._)`;${f}--;`,()=>e.for((0,Me._)`${g} = ${f}; ${g}--;`,()=>e.if((0,Me._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};_f.default=vP});var u0=z(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var vf=W(),xP=oe(),bP=ya(),wP={message:"must be equal to constant",params:({schemaCode:t})=>(0,vf._)`{allowedValue: ${t}}`},$P={keyword:"const",$data:!0,error:wP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,vf._)`!${(0,xP.useFunc)(e,bP.default)}(${r}, ${o})`):t.fail((0,vf._)`${s} !== ${r}`)}};xf.default=$P});var l0=z(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var Ts=W(),kP=oe(),SP=ya(),TP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ts._)`{allowedValues: ${t}}`},EP={keyword:"enum",schemaType:"array",$data:!0,error:TP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,kP.useFunc)(e,SP.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",s);l=(0,Ts.or)(...o.map((f,g)=>m(p,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,p=>e.if((0,Ts._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function m(p,f){let g=o[f];return typeof g=="object"&&g!==null?(0,Ts._)`${u()}(${r}, ${p}[${f}])`:(0,Ts._)`${r} === ${g}`}}};bf.default=EP});var d0=z(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var zP=Y_(),RP=Q_(),PP=r0(),IP=n0(),CP=o0(),AP=s0(),OP=i0(),NP=c0(),MP=u0(),jP=l0(),ZP=[zP.default,RP.default,PP.default,IP.default,CP.default,AP.default,OP.default,NP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},MP.default,jP.default];wf.default=ZP});var kf=z(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.validateAdditionalItems=void 0;var kn=W(),$f=oe(),DP={message:({params:{len:t}})=>(0,kn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,kn._)`{limit: ${t}}`},LP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,$f.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}f0(t,n)}};function f0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,kn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,kn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,$f.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,kn._)`${a} <= ${e.length}`);r.if((0,kn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:$f.Type.Num},u),i.allErrors||r.if((0,kn.not)(u),()=>r.break())})}}Es.validateAdditionalItems=f0;Es.default=LP});var Sf=z(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.validateTuple=void 0;var p0=W(),_a=oe(),qP=gt(),UP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return m0(t,"additionalItems",e);r.items=!0,!(0,_a.alwaysValidSchema)(r,e)&&t.ok((0,qP.validateArray)(t))}};function m0(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=_a.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,p0._)`${s}.length`);r.forEach((d,m)=>{(0,_a.alwaysValidSchema)(a,d)||(n.if((0,p0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:p}=a,f=r.length,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(m.strictTuples&&!g){let h=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,_a.checkStrictMode)(a,h,m.strictTuples)}}}zs.validateTuple=m0;zs.default=UP});var h0=z(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var FP=Sf(),HP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,FP.validateTuple)(t,"items")};Tf.default=HP});var y0=z(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var g0=W(),BP=oe(),VP=gt(),JP=kf(),WP={message:({params:{len:t}})=>(0,g0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,g0._)`{limit: ${t}}`},KP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:WP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,BP.alwaysValidSchema)(n,e)&&(o?(0,JP.validateAdditionalItems)(t,o):t.ok((0,VP.validateArray)(t)))}};Ef.default=KP});var _0=z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var _t=W(),va=oe(),GP={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},XP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,va.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,va.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,va.alwaysValidSchema)(s,r)){let g=(0,_t._)`${l} >= ${i}`;a!==void 0&&(g=(0,_t._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let g=e.name("_valid"),h=e.let("count",0);p(g,()=>e.if(g,()=>f(h)))}function p(g,h){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:va.Type.Num,compositeRule:!0},g),h()})}function f(g){e.code((0,_t._)`${g}++`),a===void 0?e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,_t._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};zf.default=XP});var b0=z(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateSchemaDeps=Bt.validatePropertyDeps=Bt.error=void 0;var Rf=W(),YP=oe(),Rs=gt();Bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Rf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Rf._)`{property: ${t},
35
35
  missingProperty: ${n},
36
36
  depsCount: ${e},
37
- deps: ${r}}`};var 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 QP={keyword:"dependencies",type:"object",schemaType:"object",error:Bt.error,code(t){let[e,r]=eI(t);v0(t,e),x0(t,r)}};function eI({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function v0(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Rs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Rs.checkReportMissingProp)(t,u)}):(r.if((0,Rf._)`${c} && (${(0,Rs.checkMissingProp)(t,a,s)})`),(0,Rs.reportMissingProp)(t,s),r.else())}}Bt.validatePropertyDeps=v0;function x0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,YP.alwaysValidSchema)(s,e[a])||(r.if((0,Rs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Bt.validateSchemaDeps=x0;Bt.default=QP});var $0=z(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var w0=W(),tI=oe(),rI={message:"property name must be valid",params:({params:t})=>(0,w0._)`{propertyName: ${t.propertyName}}`},nI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rI,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,tI.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,w0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Pf.default=nI});var Cf=z(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var xa=gt(),It=W(),oI=ar(),ba=oe(),sI={message:"must NOT have additional properties",params:({params:t})=>(0,It._)`{additionalProperty: ${t.additionalProperty}}`},iI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:sI,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ba.alwaysValidSchema)(i,r))return;let u=(0,xa.allSchemaProperties)(n.properties),l=(0,xa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,It._)`${s} === ${oI.default.errors}`);function d(){e.forIn("key",o,h=>{!u.length&&!l.length?f(h):e.if(m(h),()=>f(h))})}function m(h){let _;if(u.length>8){let v=(0,ba.schemaRefOrVal)(i,n.properties,"properties");_=(0,xa.isOwnProperty)(e,v,h)}else u.length?_=(0,It.or)(...u.map(v=>(0,It._)`${h} === ${v}`)):_=It.nil;return l.length&&(_=(0,It.or)(_,...l.map(v=>(0,It._)`${(0,xa.usePattern)(t,v)}.test(${h})`))),(0,It.not)(_)}function p(h){e.code((0,It._)`delete ${o}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(h);return}if(r===!1){t.setParams({additionalProperty:h}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ba.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(h,_,!1),e.if((0,It.not)(_),()=>{t.reset(),p(h)})):(g(h,_),a||e.if((0,It.not)(_),()=>e.break()))}}function g(h,_,v){let y={keyword:"additionalProperties",dataProp:h,dataPropType:ba.Type.Str};v===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};If.default=iI});var T0=z(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var aI=ms(),k0=gt(),Af=oe(),S0=Cf(),cI={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&S0.default.code(new aI.KeywordCxt(s,S0.default,"additionalProperties"));let i=(0,k0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Af.mergeEvaluated.props(e,(0,Af.toHash)(i),s.props));let a=i.filter(d=>!(0,Af.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,k0.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Of.default=cI});var P0=z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var E0=gt(),wa=W(),z0=oe(),R0=oe(),uI={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,E0.allSchemaProperties)(r),c=a.filter(g=>(0,z0.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof wa.Name)&&(s.props=(0,R0.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let g of a)u&&p(g),s.allErrors?f(g):(e.var(l,!0),f(g),e.if(l))}function p(g){for(let h in u)new RegExp(g).test(h)&&(0,z0.checkStrictMode)(s,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,h=>{e.if((0,wa._)`${(0,E0.usePattern)(t,g)}.test(${h})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:R0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,wa._)`${d}[${h}]`,!0):!_&&!s.allErrors&&e.if((0,wa.not)(l),()=>e.break())})})}}};Nf.default=uI});var I0=z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var lI=oe(),dI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,lI.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Mf.default=dI});var C0=z(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var fI=gt(),pI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fI.validateUnion,error:{message:"must match a schema in anyOf"}};jf.default=pI});var A0=z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var $a=W(),mI=oe(),hI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,$a._)`{passingSchemas: ${t.passing}}`},gI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hI,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let m;(0,mI.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,$a._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$a._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,$a.Name)})})}}};Zf.default=gI});var O0=z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var yI=oe(),_I={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,yI.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Df.default=_I});var j0=z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var ka=W(),M0=oe(),vI={message:({params:t})=>(0,ka.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ka._)`{failingKeyword: ${t.ifClause}}`},xI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vI,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,M0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=N0(n,"then"),s=N0(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,ka.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,ka._)`${l}`):t.setParams({ifClause:l})}}}};function N0(t,e){let r=t.schema[e];return r!==void 0&&!(0,M0.alwaysValidSchema)(t,r)}Lf.default=xI});var Z0=z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var bI=oe(),wI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,bI.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};qf.default=wI});var D0=z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var $I=kf(),kI=h0(),SI=Sf(),TI=y0(),EI=_0(),zI=b0(),RI=$0(),PI=Cf(),II=T0(),CI=P0(),AI=I0(),OI=C0(),NI=A0(),MI=O0(),jI=j0(),ZI=Z0();function DI(t=!1){let e=[AI.default,OI.default,NI.default,MI.default,jI.default,ZI.default,RI.default,PI.default,zI.default,II.default,CI.default];return t?e.push(kI.default,TI.default):e.push($I.default,SI.default),e.push(EI.default),e}Uf.default=DI});var L0=z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Te=W(),LI={message:({schemaCode:t})=>(0,Te.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Te._)`{format: ${t}}`},qI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:LI,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?m():p();function m(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,Te._)`${f}[${i}]`),h=r.let("fType"),_=r.let("format");r.if((0,Te._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,Te._)`${g}.type || "string"`).assign(_,(0,Te._)`${g}.validate`),()=>r.assign(h,(0,Te._)`"string"`).assign(_,g)),t.fail$data((0,Te.or)(v(),y()));function v(){return c.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${_}`}function y(){let x=l.$async?(0,Te._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,Te._)`${_}(${n})`,$=(0,Te._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,Te._)`${_} && ${_} !== true && ${h} === ${e} && !${$}`}}function p(){let f=d.formats[s];if(!f){v();return}if(f===!0)return;let[g,h,_]=y(f);g===e&&t.pass(x());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function y($){let N=$ instanceof RegExp?(0,Te.regexpCode)($):c.code.formats?(0,Te._)`${c.code.formats}${(0,Te.getProperty)(s)}`:void 0,A=r.scopeValue("formats",{key:s,ref:$,code:N});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Te._)`${A}.validate`]:["string",$,A]}function x(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${_}(${n})`}return typeof h=="function"?(0,Te._)`${_}(${n})`:(0,Te._)`${_}.test(${n})`}}}};Ff.default=qI});var q0=z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var UI=L0(),FI=[UI.default];Hf.default=FI});var U0=z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.contentVocabulary=uo.metadataVocabulary=void 0;uo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];uo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var H0=z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var HI=X_(),BI=d0(),VI=D0(),JI=q0(),F0=U0(),WI=[HI.default,BI.default,(0,VI.default)(),JI.default,F0.metadataVocabulary,F0.contentVocabulary];Bf.default=WI});var V0=z(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.DiscrError=void 0;var B0;(function(t){t.Tag="tag",t.Mapping="mapping"})(B0||(Sa.DiscrError=B0={}))});var W0=z(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var lo=W(),Vf=V0(),J0=oa(),KI=hs(),GI=oe(),XI={message:({params:{discrError:t,tagName:e}})=>t===Vf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},YI={keyword:"discriminator",type:"object",schemaType:"object",error:XI,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,lo._)`${r}${(0,lo.getProperty)(a)}`);e.if((0,lo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Vf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=m();e.if(!1);for(let f in p)e.elseIf((0,lo._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Vf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(g,lo.Name),f}function m(){var p;let f={},g=_(o),h=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,GI.schemaHasRulesButRef)($,s.self.RULES)){let A=$.$ref;if($=J0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,A),$ instanceof J0.SchemaEnv&&($=$.schema),$===void 0)throw new KI.default(s.opts.uriResolver,s.baseId,A)}let N=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);h=h&&(g||_($)),v(N,x)}if(!h)throw new Error(`discriminator: "${a}" must be required`);return f;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function v(x,$){if(x.const)y(x.const,$);else if(x.enum)for(let N of x.enum)y(N,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[x]=$}}}};Jf.default=YI});var K0=z((eq,QI)=>{QI.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Kf=z((ve,Wf)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var eC=B_(),tC=H0(),rC=W0(),G0=K0(),nC=["/properties"],Ta="http://json-schema.org/draft-07/schema",fo=class extends eC.default{_addVocabularies(){super._addVocabularies(),tC.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(G0,nC):G0;this.addMetaSchema(e,Ta,!1),this.refs["http://json-schema.org/schema"]=Ta}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ta)?Ta:void 0)}};ve.Ajv=fo;Wf.exports=ve=fo;Wf.exports.Ajv=fo;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=fo;var oC=ms();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return oC.KeywordCxt}});var po=W();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return po._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return po.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return po.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return po.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return po.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return po.CodeGen}});var sC=ra();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return sC.default}});var iC=hs();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return iC.default}})});var ov=z(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.formatNames=Jt.fastFormats=Jt.fullFormats=void 0;function Vt(t,e){return{validate:t,compare:e}}Jt.fullFormats={date:Vt(ev,Qf),time:Vt(Xf(!0),ep),"date-time":Vt(X0(!0),rv),"iso-time":Vt(Xf(),tv),"iso-date-time":Vt(X0(),nv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fC,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:vC,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:pC,int32:{type:"number",validate:gC},int64:{type:"number",validate:yC},float:{type:"number",validate:Q0},double:{type:"number",validate:Q0},password:!0,binary:!0};Jt.fastFormats={...Jt.fullFormats,date:Vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Qf),time:Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ep),"date-time":Vt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,rv),"iso-time":Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,tv),"iso-date-time":Vt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,nv),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Jt.formatNames=Object.keys(Jt.fullFormats);function aC(t){return t%4===0&&(t%100!==0||t%400===0)}var cC=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ev(t){let e=cC.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&aC(r)?29:uC[n])}function Qf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Gf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Xf(t){return function(r){let n=Gf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function ep(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function tv(t,e){if(!(t&&e))return;let r=Gf.exec(t),n=Gf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Yf=/t|\s/i;function X0(t){let e=Xf(t);return function(n){let o=n.split(Yf);return o.length===2&&ev(o[0])&&e(o[1])}}function rv(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function nv(t,e){if(!(t&&e))return;let[r,n]=t.split(Yf),[o,s]=e.split(Yf),i=Qf(r,o);if(i!==void 0)return i||ep(n,s)}var lC=/\/|:/,dC=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function fC(t){return lC.test(t)&&dC.test(t)}var Y0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function pC(t){return Y0.lastIndex=0,Y0.test(t)}var mC=-(2**31),hC=2**31-1;function gC(t){return Number.isInteger(t)&&t<=hC&&t>=mC}function yC(t){return Number.isInteger(t)}function Q0(){return!0}var _C=/[^\\]\\Z/;function vC(t){if(_C.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var sv=z(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.formatLimitDefinition=void 0;var xC=Kf(),Ct=W(),Or=Ct.operators,Ea={formatMaximum:{okStr:"<=",ok:Or.LTE,fail:Or.GT},formatMinimum:{okStr:">=",ok:Or.GTE,fail:Or.LT},formatExclusiveMaximum:{okStr:"<",ok:Or.LT,fail:Or.GTE},formatExclusiveMinimum:{okStr:">",ok:Or.GT,fail:Or.LTE}},bC={message:({keyword:t,schemaCode:e})=>(0,Ct.str)`should be ${Ea[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ct._)`{comparison: ${Ea[t].okStr}, limit: ${e}}`};mo.formatLimitDefinition={keyword:Object.keys(Ea),type:"string",schemaType:"string",$data:!0,error:bC,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new xC.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Ct._)`${m}[${c.schemaCode}]`);t.fail$data((0,Ct.or)((0,Ct._)`typeof ${p} != "object"`,(0,Ct._)`${p} instanceof RegExp`,(0,Ct._)`typeof ${p}.compare != "function"`,d(p)))}function l(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:p,code:i.code.formats?(0,Ct._)`${i.code.formats}${(0,Ct.getProperty)(m)}`:void 0});t.fail$data(d(f))}function d(m){return(0,Ct._)`${m}.compare(${r}, ${n}) ${Ea[o].fail} 0`}},dependencies:["format"]};var wC=t=>(t.addKeyword(mo.formatLimitDefinition),t);mo.default=wC});var uv=z((Ps,cv)=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var ho=ov(),$C=sv(),tp=W(),iv=new tp.Name("fullFormats"),kC=new tp.Name("fastFormats"),rp=(t,e={keywords:!0})=>{if(Array.isArray(e))return av(t,e,ho.fullFormats,iv),t;let[r,n]=e.mode==="fast"?[ho.fastFormats,kC]:[ho.fullFormats,iv],o=e.formats||ho.formatNames;return av(t,o,r,n),e.keywords&&(0,$C.default)(t),t};rp.get=(t,e="full")=>{let n=(e==="fast"?ho.fastFormats:ho.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function av(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,tp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}cv.exports=Ps=rp;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.default=rp});var mx={};To(mx,{findEmbeddingModel:()=>px,ollamaUrl:()=>Sp,semanticRerank:()=>aO});import{createHash as GA}from"node:crypto";import{existsSync as XA,mkdirSync as YA,readFileSync as QA,writeFileSync as eO}from"node:fs";import{homedir as tO}from"node:os";import{join as kp}from"node:path";function Sp(t=process.env.OLLAMA_HOST){let e=(t??"").trim(),r="http",n="11434",o=e.indexOf("://");o>=0&&(r=e.slice(0,o),e=e.slice(o+3),r==="http"?n="80":r==="https"&&(n="443"));let s=e.indexOf("/"),i=s>=0?e.slice(s).replace(/\/+$/,""):"",a=s>=0?e.slice(0,s):e,c=/^(\[[^\]]*\]|[^:]*):([^:]*)$/.exec(a);return c?(a=c[1],/^\d+$/.test(c[2])&&Number(c[2])<=65535&&(n=c[2])):a.includes(":")&&!a.startsWith("[")&&(a=`[${a}]`),!a||a==="0.0.0.0"?a="127.0.0.1":a==="[::]"&&(a="[::1]"),`${r}://${a}:${n}${i}`}async function fx(t,e,r=6e4){let n=await fetch(Sp()+t,{method:e?"POST":"GET",headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0,signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`${t}: HTTP ${n.status}`);return n.json()}async function px(t){let r=((await fx("/api/tags",void 0,2e3)).models??[]).map(n=>String(n.name));return t?r.find(n=>n===t||n.startsWith(t+":"))??t:r.find(n=>rO.test(n))}function Ba(){return kp(process.env.XDG_CACHE_HOME??kp(tO(),".cache"),"context-doctor","embeddings.json")}function nO(){try{return XA(Ba())?JSON.parse(QA(Ba(),"utf8")):{}}catch{return{}}}function oO(t){try{let e=Object.keys(t);if(e.length>dx)for(let r of e.slice(0,e.length-dx))delete t[r];YA(kp(Ba(),".."),{recursive:!0}),eO(Ba(),JSON.stringify(t))}catch{}}async function sO(t,e){let r=[];for(let n=0;n<e.length;n+=lx){let o=await fx("/api/embed",{model:t,input:e.slice(n,n+lx),truncate:!0});r.push(...o.embeddings)}return r}function iO(t,e){let r=0,n=0,o=0;for(let s=0;s<t.length;s++)r+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return n&&o?r/Math.sqrt(n*o):0}async function aO(t,e,r={}){let n;try{n=await px(r.model)}catch{return{used:!1,note:`semantic ranking off: no Ollama at ${Sp()} (keyword ranking only)`}}if(!n)return{used:!1,note:"semantic ranking off: Ollama has no embedding model; run `ollama pull nomic-embed-text` (keyword ranking only)"};let o=nO(),s=f=>GA("sha1").update(n+"\0"+f).digest("hex"),i=t.map(f=>(f.heading?f.heading+`
38
+ `:"")+f.text),a=[...new Set(i.filter(f=>!o[s(f)]))],c,u;try{let f=await sO(n,[e,...a]);u=f[0],a.forEach((g,h)=>o[s(g)]=f[h+1]),c=i.map(g=>o[s(g)])}catch(f){return{used:!1,model:n,note:`semantic ranking off: ${n} failed (${f.message}); keyword ranking only`}}a.length&&oO(o);let l=60,d=new Map([...t].filter(f=>f.score>0).sort((f,g)=>g.score-f.score).map((f,g)=>[f,g])),m=t.map((f,g)=>({c:f,s:iO(u,c[g])})).sort((f,g)=>g.s-f.s),p=new Map(m.map((f,g)=>[f.c,g]));for(let f of t){let g=d.get(f);f.score=(g===void 0?0:1/(l+g))+1/(l+p.get(f))}return{used:!0,model:n,note:`semantic ranking: ${n}, ${a.length} of ${i.length} chunks embedded (rest cached)`}}var rO,lx,dx,hx=X(()=>{"use strict";rO=/embed|bge|e5-|gte|minilm|nomic|mxbai|arctic|snowflake/i,lx=64,dx=5e4});var fb,pb=X(()=>{fb="x-hono-already-sent"});var mb,hb=X(()=>{mb=t=>((...e)=>{if(typeof e[0]=="function"){let[r,n]=e;return async function(s,i){let a=await t(s,await r(s),n);if(a)return a;await i()}}else{let[r,n,o]=e;return(async()=>{let s=await t(r,n,o);if(!s)throw new Error("Failed to upgrade WebSocket");return s})()}})});import{STATUS_CODES as UU,ServerResponse as LN,createServer as FU}from"node:http";import{Http2ServerRequest as mr,constants as qN}from"node:http2";import{Readable as gb}from"node:stream";async function fM(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Cb(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(u){o(u)}}}function $b(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Cb(t.getReader(),e)}var Nt,UN,FN,nc,yb,_b,Gp,Sb,Xp,Tb,HN,BN,VN,Fp,JN,WN,KN,ko,Eb,GN,XN,qp,Hp,zb,Yp,vb,sc,xb,YN,Lr,fr,So,Zs,Rb,Pb,Ms,Bp,Vp,Dr,oc,hr,bb,js,ic,Ds,QN,eM,tM,rM,nM,oM,sM,Qp,iM,wb,aM,Xt,cM,Rn,Jp,$o,pr,ac,Gt,uM,lM,dM,Wp,cc,kb,pM,mM,Ab,hM,gM,yM,Ob,uc,Kp,Nb,Up,Mb,jb,_M,em,vM,xM,bM,wM,$M,JU,Zb=X(()=>{pb();hb();Nt=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},UN=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),FN=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,nc=t=>t===9||t===10||t===13||t===32,yb=t=>{if(!nc(t.charCodeAt(0))&&!nc(t.charCodeAt(t.length-1)))return t;let e=0,r=t.length;for(;e<r&&nc(t.charCodeAt(e));)e++;for(;r>e&&nc(t.charCodeAt(r-1));)r--;return t.slice(e,r)},_b=/[\0\r\n]/,Gp=globalThis.Headers,Sb=(t,e=Gp)=>{let r=new e;for(let n=0;n<t.length;n+=2){let o=t[n];o.startsWith(":")||r.append(o,t[n+1])}return r},Xp=class{#e;#t;#n;#o;constructor(t){this.#e=t,t instanceof mr&&(this.#t=t.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=Sb(this.#s),this.#t=void 0),this.#n}#i(t){if(typeof t=="string"){if(!FN.test(t))throw new TypeError(`Invalid header name: ${t}`);return t.toLowerCase()}}#a(t){let e=this.#e instanceof mr?void 0:this.#e.headers;if(!e||UN.has(t)||t==="set-cookie"||t==="__proto__")return;if(!Object.hasOwn(e,t))return null;let r=e[t];if(typeof r=="string"){let n=yb(r);return _b.test(n)?void 0:n}}#c(t,e){let r=e==="cookie"?"; ":", ",n=null;for(let o=0;o<t.length;o+=2){let s=t[o];if(s.length===e.length&&s.toLowerCase()===e){let i=yb(t[o+1]);if(_b.test(i)){this.#o=!0;return}n=n===null?i:n+r+i}}return n}append(t,e){this.#r.append(t,e)}delete(t){this.#r.delete(t)}get(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r;let n=this.#c(this.#s,e);if(n!==void 0)return n}return this.#r.get(t)}has(t){let e=this.#i(t);if(e&&!this.#n&&!this.#o){let r=this.#a(e);if(r!==void 0)return r!==null;let n=this.#c(this.#s,e);if(n!==void 0)return n!==null}return this.#r.has(t)}set(t,e){this.#r.set(t,e)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(t,e){this.#r.forEach((r,n)=>{t.call(e,r,n,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Xp.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Xp.prototype,Gp.prototype);Tb=t=>globalThis.Headers===Gp?new Xp(t):Sb(t.rawHeaders,globalThis.Headers),HN=/^\/[!#$&-;=?-\[\]_a-z~]*$/,BN=/\/\.\.?(?:[/?#]|$)/,VN=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,Fp=t=>{let e=t.indexOf("\\");if(e!==-1){let r=t.indexOf("?");if(r===-1||e<r)throw new Nt("Backslash in request path")}},JN=(t,e,r)=>{let n=`${t}://${e}${r}`;if(VN.test(e)){if(r.length===0)return n+"/";if(r.charCodeAt(0)!==47)throw new Nt("Invalid URL");return!HN.test(r)||BN.test(r)?(Fp(r),new URL(n).href):n}else{Fp(r);let o=new URL(n);if(o.hostname.length!==e.length&&o.hostname!==(e.includes(":")?e.replace(/:\d+$/,""):e).toLowerCase())throw new Nt("Invalid host header");return o.href}},WN=t=>t instanceof Nt?t:new Nt(t.message,{cause:t}),KN=global.Request,ko=class extends KN{constructor(t,e){if(typeof t=="object"&&Lr in t){let r=e!==void 0&&"body"in e&&e.body!=null;if(t[hr]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Lr]()}typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Eb=Symbol("wrapBodyStream"),GN=new Set(["latin1","binary","hex","base64","base64url"]),XN=t=>t===null||GN.has(t),qp=Symbol("bodyBufferedBeforeDisconnect"),Hp=Symbol("bodyBufferedLengthBeforeDisconnect"),zb=(t,e)=>Buffer.isBuffer(t)?t:Buffer.from(t,e??"utf8"),Yp=t=>!(t instanceof mr)&&!!t.complete&&!!t.readableAborted&&typeof t.read=="function"&&XN(t.readableEncoding),vb=t=>{if(t.readableDidRead||!Yp(t))return;let e=t;e[Hp]??=t.readableLength},sc=(t,e)=>{if(t.readableDidRead&&!e||!Yp(t))return;let r=t;if(r[qp]!==void 0)return r[qp];let n,o=t.errored;if(o&&o.code!=="ECONNRESET")n=o;else if(r[Hp]!==void 0&&t.readableLength!==r[Hp])n=ic();else{let s=e??[],i=t.read();i!==null&&s.push(zb(i,t.readableEncoding));let a=s.length===1?s[0]:Buffer.concat(s);n=a;let c=t.headers["content-length"];if(typeof c=="string"&&/^\d+$/.test(c)){let u=Number(c);Number.isSafeInteger(u)&&a.length!==u&&(n=ic())}}return r[qp]=n,n},xb=(t,e)=>{if(e instanceof Error){t.error(e);return}e.length>0&&t.enqueue(e),t.close()},YN=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ko(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Eb]){let i;s.body=new ReadableStream({async pull(a){try{if(!i){let l=sc(n);if(l!==void 0){xb(a,l);return}}i||=gb.toWeb(n).getReader();let{done:c,value:u}=await i.read();c?a.close():a.enqueue(u)}catch(c){a.error(c)}}})}else{let i=sc(n);i!==void 0?s.body=new ReadableStream({start(a){xb(a,i)}}):s.body=gb.toWeb(n)}return new ko(e,s)},Lr=Symbol("getRequestCache"),fr=Symbol("requestCache"),So=Symbol("incomingKey"),Zs=Symbol("urlKey"),Rb=Symbol("methodKey"),Pb=Symbol("headersKey"),Ms=Symbol("abortControllerKey"),Bp=Symbol("getAbortController"),Vp=Symbol("abortRequest"),Dr=Symbol("bodyBuffer"),oc=Symbol("bodyReadPromise"),hr=Symbol("bodyConsumedDirectly"),bb=Symbol("bodyLockReader"),js=Symbol("abortReason"),ic=()=>new TypeError("Body is unusable"),Ds=()=>Promise.reject(ic()),QN=new TextDecoder,eM=t=>{if(t[hr])return Ds();t[hr]=!0},tM=t=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),rM=t=>(t[Pb]||=Tb(t[So])).get("content-type")||"",nM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,oM=t=>{if(typeof t!="string"||t.length===0)return"GET";switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return t}let e=t.toUpperCase();switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e;default:return t}},sM=t=>{if(!nM.test(t))return new TypeError(`'${t}' is not a valid HTTP method.`);let e=t.toUpperCase();if(e==="CONNECT"||e==="TRACK"||e==="TRACE"&&t!=="TRACE")return new TypeError(`'${t}' HTTP method is unsupported.`)},Qp=(t,e,r)=>{if(t[hr])return Ds();let n=t.method;if(n==="GET"||n==="HEAD")return t[Lr]()[e]();let o=sM(n);if(o)return Promise.reject(o);if(t[fr]&&n!=="TRACE")return t[fr][e]();let s=eM(t);if(s)return s;let i=iM(t);if(i){let a=Promise.resolve(r(i,t));return t[Dr]=void 0,a}return aM(t).then(a=>{let c=r(a,t);return t[Dr]=void 0,c})},iM=t=>{let e=t[So];if("rawBody"in e&&e.rawBody instanceof Buffer)return e.rawBody},wb=(t,e)=>{if(e.errored)return e.errored;let r=t[js];return r!==void 0?r instanceof Error?r:new Error(String(r)):new Error("Client connection prematurely closed.")},aM=t=>{if(t[Dr])return Promise.resolve(t[Dr]);if(t[oc])return t[oc];let e=t[So];if(e.readableDidRead)return Ds();let r=sc(e);if(r!==void 0)return r instanceof Error?Promise.reject(r):(t[Dr]=r,Promise.resolve(r));let n=new Promise((o,s)=>{let i=[],a=!1,c=g=>{a||(a=!0,f(),g())},u=g=>{let h=e.errored??g;return!Yp(e)||h&&h.code!=="ECONNRESET"?!1:(c(()=>{let _=sc(e,i);_ instanceof Error?s(_):_===void 0?s(g??wb(t,e)):(t[Dr]=_,o(_))}),!0)},l=g=>{i.push(zb(g,e.readableEncoding))},d=()=>{c(()=>{let g=i.length===1?i[0]:Buffer.concat(i);t[Dr]=g,o(g)})},m=g=>{u(g)||c(()=>{s(g)})},p=()=>{if(e.readableEnded){d();return}u()||c(()=>{s(wb(t,e))})},f=()=>{e.off("data",l),e.off("end",d),e.off("error",m),e.off("close",p),t[oc]=void 0};e.on("data",l),e.on("end",d),e.on("error",m),e.on("close",p),queueMicrotask(()=>{a||(e.readableEnded?d():e.errored?m(e.errored):e.destroyed&&p())})});return t[oc]=n,n},Xt={get method(){return this[Rb]},get url(){return this[Zs]},get headers(){return this[Pb]||=Tb(this[So])},[Vp](t){this[js]===void 0&&(this[js]=t);let e=this[Ms];e&&!e.signal.aborted&&e.abort(t)},[Bp](){return this[Ms]||=new AbortController,this[js]!==void 0&&!this[Ms].signal.aborted&&this[Ms].abort(this[js]),this[Ms]},[Lr](){let t=this[Bp]();if(this[fr])return this[fr];let e=this.method;if(this[hr]&&!(e==="GET"||e==="HEAD")){this[Dr]=void 0;let r={method:e==="TRACE"?"GET":e,headers:this.headers,signal:t.signal};e!=="TRACE"&&(r.body=new ReadableStream({start(o){o.close()}}),r.duplex="half");let n=new ko(this[Zs],r);return e==="TRACE"&&Object.defineProperty(n,"method",{get(){return"TRACE"}}),this[fr]=n}return this[fr]=YN(this.method,this[Zs],this.headers,this[So],t)},get body(){if(!this[hr])return this[Lr]().body;let t=this[Lr]();return!this[bb]&&t.body&&(this[bb]=t.body.getReader()),t.body},get bodyUsed(){return this[hr]?!0:this[fr]?this[fr].bodyUsed:!1}};Object.defineProperty(Xt,"signal",{get(){return this[Bp]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(t=>{Object.defineProperty(Xt,t,{get(){return this[Lr]()[t]}})});["clone","formData"].forEach(t=>{Object.defineProperty(Xt,t,{value:function(){if(this[hr]){if(t==="clone")throw ic();return Ds()}return this[Lr]()[t]()}})});Object.defineProperty(Xt,"text",{value:function(){return Qp(this,"text",t=>QN.decode(t))}});Object.defineProperty(Xt,"arrayBuffer",{value:function(){return Qp(this,"arrayBuffer",t=>tM(t))}});Object.defineProperty(Xt,"blob",{value:function(){return Qp(this,"blob",(t,e)=>{let r=rM(e),n=r?{headers:{"content-type":r}}:void 0;return new Response(t,n).blob()})}});Object.defineProperty(Xt,"json",{value:function(){return this[hr]?Ds():this.text().then(JSON.parse)}});Object.defineProperty(Xt,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[fr]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Xt,ko.prototype);cM=(t,e)=>{let r=Object.create(Xt);r[So]=t,r[Rb]=oM(t.method);let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof mr)throw new Nt("Absolute URL for :path is not allowed in HTTP/2");try{Fp(n),r[Zs]=new URL(n).href}catch(i){throw new Nt("Invalid absolute URL",{cause:i})}return r}let o=(t instanceof mr?t.authority:t.headers.host)||e;if(!o)throw new Nt("Missing host header");let s;if(t instanceof mr){if(s=t.scheme,!(s==="http"||s==="https"))throw new Nt("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";try{r[Zs]=JN(s,o,n)}catch(i){throw i instanceof Nt?i:new Nt("Invalid URL",{cause:i})}return r},Rn="text/plain; charset=UTF-8",Jp=Symbol("responseCache"),$o=Symbol("getResponseCache"),pr=Symbol("cache"),ac=global.Response,Gt=class Ib{#e;#t;[$o](){let e=this[pr],r=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[pr],this[Jp]||=new ac(this.#e,r?{status:this.#t?.status,statusText:this.#t?.statusText,headers:r}:this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof ac){let o=r[Jp];if(o){this.#t=o,this[$o]();return}this.#t=r instanceof Ib?r.#t:r,n=new Headers(r.headers)}else this.#t=r;(e==null||typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[pr]=[r?.status||200,e??null,n||r?.headers])}get headers(){let e=this[pr];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Rn}))),e[2]):this[$o]().headers}get status(){return this[pr]?.[0]??this[$o]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Gt.prototype,t,{get(){return this[$o]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Gt.prototype,t,{value:function(){return this[$o]()[t]()}})});Object.defineProperty(Gt.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(t,e,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Jp]},{...e,depth:t==null?null:t-1})}`}});Object.setPrototypeOf(Gt,ac);Object.setPrototypeOf(Gt.prototype,ac.prototype);uM=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,lM=t=>t instanceof URL?t.href:uM.test(t)?t:new URL(t).href,dM=new Set([301,302,303,307,308]);Object.defineProperty(Gt,"redirect",{value:function(e,r=302){if(!dM.has(r))throw new RangeError("Invalid status code");return new Gt(null,{status:r,headers:{location:lM(e)}})},writable:!0,configurable:!0});Object.defineProperty(Gt,"json",{value:function(e,r){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("The data is not JSON serializable");let o=r?.headers,s;return o?(s=new Headers(o),s.has("content-type")||s.set("content-type","application/json")):s={"content-type":"application/json"},new Gt(n,{status:r?.status??200,statusText:r?.statusText,headers:s})},writable:!0,configurable:!0});Wp=(t,e)=>{let r={};if(t instanceof Headers||(t=new Headers(t??void 0)),t.has("set-cookie")){let n=[];for(let[o,s]of t)o==="set-cookie"?n.push(s):r[o]=s;n.length>0&&(r["set-cookie"]=n)}else for(let[n,o]of t)r[n]=o;return e&&(r["content-type"]??=e),r},cc=Symbol("outgoingEnded"),kb=Symbol("incomingDraining"),pM=500,mM=64*1024*1024,Ab=t=>{let e=t;if(t.destroyed||e[kb])return;if(e[kb]=!0,t instanceof mr){try{t.stream?.close?.(qN.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),t.off("data",i),t.off("end",n),t.off("error",n)},o=()=>{n();let a=t.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},s=setTimeout(o,pM);s.unref?.();let i=a=>{r+=a.length,r>mM&&o()};t.on("data",i),t.on("end",n),t.on("error",n),t.resume()},hM=(t,e,r,n)=>()=>{e.errored?(vb(e),t[Vp](e.errored.toString())):(!r.writableFinished||e instanceof mr&&e.aborted)&&(vb(e),t[Vp]("Client connection prematurely closed.")),n&&!e.readableEnded&&setTimeout(()=>{e.readableEnded||setTimeout(()=>{Ab(e)})})},gM=t=>{if(!(pr in t))return!1;let e=t[pr][1];return e===null||typeof e=="string"||e instanceof Uint8Array},yM=()=>new Response(null,{status:400}),Ob=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),uc=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||(e instanceof LN&&(e._contentLength=null),e.writeHead(500,{"Content-Type":"text/plain"})),e.end(`Error: ${r.message}`),e.destroy(r))},Kp=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},Nb=(t,e,r)=>{let n=t;return n._contentLength===null&&n._hasBody&&n.useChunkedEncodingByDefault&&!n._removedContLen&&e>=200&&e!==204&&e!==304&&!t.hasHeader("content-length")&&!t.hasHeader("transfer-encoding")&&!t.hasHeader("trailer")?(n._contentLength=r,!0):!1},Up=(t,e,r)=>{Nb(t,e,r)?t.writeHead(e,{"Content-Type":Rn}):t.writeHead(e,{"Content-Type":Rn,"Content-Length":r})},Mb=async(t,e)=>{let[r,n,o]=t[pr];if(!o){n===null?(e.writeHead(r),e.end()):typeof n=="string"?(Up(e,r,Buffer.byteLength(n)),e.end(n)):n instanceof Uint8Array?(Up(e,r,n.byteLength),e.end(n)):n instanceof Blob?(Up(e,r,n.size),e.end(new Uint8Array(await n.arrayBuffer()))):(e.writeHead(r,{"Content-Type":Rn}),Kp(e),await $b(n,e)?.catch(c=>uc(c,e))),e[cc]?.();return}let s=!1,i=!1,a=!0;if(o instanceof Headers)s=o.has("content-length"),o=Wp(o,n===null?void 0:Rn);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=Wp(c,n===null?void 0:Rn)}else{i=!0;for(let c in o){if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}(c.length===17&&c.toLowerCase()==="transfer-encoding"||c.length===7&&c.toLowerCase()==="trailer")&&(a=!1)}}if(!s){let c;typeof n=="string"?c=Buffer.byteLength(n):n instanceof Uint8Array?c=n.byteLength:n instanceof Blob&&(c=n.size),c!==void 0&&(!i||!a||!Nb(e,r,c))&&(i&&(o={...o}),o["Content-Length"]=c)}e.writeHead(r,o),n==null?e.end():typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(Kp(e),await $b(n,e)?.catch(c=>uc(c,e))),e[cc]?.()},jb=t=>typeof t.then=="function",_M=async(t,e,r={})=>{if(jb(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(Ob);if(pr in t)return Mb(t,e);let n=Wp(t.headers,t.body===null?void 0:Rn);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let u=0;u<c;u++){a||=o.read();let l=await fM(a).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,l.value&&s.push(l.value),l.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&Kp(e),await Cb(o,e,a))}else n[fb]||(e.writeHead(t.status,n),e.end());e[cc]?.()},em=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ko&&(Object.defineProperty(global,"Request",{value:ko}),Object.defineProperty(global,"Response",{value:Gt})),async(n,o)=>{let s,i,a=!1,c=!1,u=()=>{!i||c||(c=!0,o.on("close",hM(i,n,o,a)))};try{if(i=cM(n,e.hostname),a=r&&!(n.method==="GET"||n.method==="HEAD"),a&&(n[Eb]=!0,n instanceof mr&&(o[cc]=()=>{n.readableEnded||setTimeout(()=>{n.readableEnded||setTimeout(()=>{n.destroy(),o.destroy()})})})),s=t(i,{incoming:n,outgoing:o}),!jb(s)&&gM(s))return a&&!n.readableEnded&&o.once("finish",()=>{n.readableEnded||Ab(n)}),Mb(s,o);u()}catch(l){if(s)return uc(l,o);if(e.errorHandler){if(u(),s=await e.errorHandler(i?l:WN(l)),!s)return}else i?s=Ob(l):s=yM()}try{return await _M(s,o,e)}catch(l){return uc(l,o)}}},vM=globalThis.CloseEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},xM=globalThis.ErrorEvent??class extends Event{#e;constructor(t,e={}){super(t,e),this.#e=e}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},bM=()=>Symbol("connection"),wM=Symbol("CONNECTION_SYMBOL_KEY"),$M=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),JU=mb(async(t,e,r)=>{if(t.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=t.env,o=n[$M];if(!o||!n.incoming)return new Response(null,{status:500});let s=bM();return n[wM]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,m)=>{a.push([d,m])};i.on("message",c);let u={binaryType:"arraybuffer",close(d,m){i.close(d,m)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,m){i.send(d,{compress:m?.compress})},url:new URL(t.req.url)};try{e?.onOpen?.(new Event("open"),u)}catch(d){(r?.onError??console.error)(d)}let l=(d,m)=>{let p=Array.isArray(d)?d:[d];for(let f of p)try{e?.onMessage?.(new MessageEvent("message",{data:m?f instanceof ArrayBuffer?f:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength):typeof f=="string"?f:Buffer.from(f).toString("utf-8")}),u)}catch(g){(r?.onError??console.error)(g)}};i.off("message",c);for(let d of a)l(...d);i.on("message",(d,m)=>{l(d,m)}),i.on("close",(d,m)=>{try{e?.onClose?.(new vM("close",{code:d,reason:m.toString()}),u)}catch(p){(r?.onError??console.error)(p)}}),i.on("error",d=>{try{e?.onError?.(new xM("error",{error:d}),u)}catch(m){(r?.onError??console.error)(m)}})})(),new Response})});var Ub=z(tm=>{"use strict";var Db=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,kM=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Lb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,SM=/\\([\u000b\u0020-\u00ff])/g,TM=/([\\"])/g,qb=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;tm.format=EM;tm.parse=zM;function EM(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!qb.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!Lb.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+PM(e[o])}return n}function zM(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?RM(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!qb.test(n))throw new TypeError("invalid media type");var o=new IM(n.toLowerCase());if(r!==-1){var s,i,a;for(Db.lastIndex=r;i=Db.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(SM,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function RM(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function PM(t){var e=String(t);if(Lb.test(e))return e;if(e.length>0&&!kM.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(TM,"\\$1")+'"'}function IM(t){this.parameters=Object.create(null),this.type=t}});function CM(t){if(t)try{return Fb.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Hb(t){return t==="application/json"?!0:CM(t)==="application/json"}var Fb,Bb=X(()=>{Fb=pc(Ub(),1)});function Vb(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function Jb(t){if(t===void 0)return 4194304;if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function Wb(t,e=4194304){if(Number(t.headers.get("content-length"))>e)return{tooLarge:!0};if(t.body===null)return{tooLarge:!1,text:""};let r=t.body.getReader(),n=new TextDecoder,o=0,s="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(o+=a.byteLength,o>e)return{tooLarge:!0};s+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:s+n.decode()}}var Kb=X(()=>{});function Gb(t,e){if(!Number.isFinite(t)||t<1)return;let r=setInterval(e,Math.min(t,2147483647));return r.unref?.(),r}var Xb=X(()=>{});var lc,Yb=X(()=>{Bb();Kb();Xb();Sr();lc=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??15e3,this._maxRequestBodySize=Jb(e.maxRequestBodySize)}startKeepAlive(e,r){if(this._closed)return;let n=Gb(this._keepAliveMs,()=>{try{e.enqueue(r.encode(`: keepalive
39
39
 
40
40
  `))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
41
41
  data:
@@ -48,75 +48,75 @@ data:
48
48
  `;return o&&(s+=`id: ${o}
49
49
  `),s+=`data: ${JSON.stringify(n)}
50
50
 
51
- `,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!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(!Hb(o))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{let v=await Wb(e,this._maxRequestBodySize);if(v.tooLarge){let y=Vb(this._maxRequestBodySize);return this.onerror?.(new Error(y)),this.createJsonErrorResponse(413,-32e3,y)}i=JSON.parse(v.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(i)&&i.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);let a;try{Array.isArray(i)?a=i.map(v=>Bo.parse(v)):a=[Bo.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c=a.some(Dl);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let y=this.validateProtocolVersion(e);if(y)return y}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!a.some(nr)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(v=>Dl(v)),m=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??pg;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)nr(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let p=new TextEncoder,f,g,h=new ReadableStream({start:v=>{f=v},cancel:()=>{g!==void 0&&clearInterval(g),this._streamMapping.get(l)?.controller===f&&this._streamMapping.delete(l)}}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of a)nr(v)&&(this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));try{await this.writePrimingEvent(f,p,l,m);for(let v of a){let y,x;nr(v)&&this._eventStore&&m>="2025-11-25"&&(y=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:y,closeStandaloneSSEStream:x})}}catch(v){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let y of a)nr(y)&&this._requestToStreamMapping.delete(y.id);throw v}return this._streamMapping.get(l)?.controller===f&&(g=this.startKeepAlive(f,p)),new Response(h,{status:200,headers:_})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!Vn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Vn.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((or(e)||Jn(e))&&(n=e.id),n===void 0){if(or(e)||Jn(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i))&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e),s=this._streamMapping.get(o)),s?.controller&&s?.encoder&&(i===void 0||!s.replayedEventIds?.has(i))&&this.writeSSEEvent(s.controller,s.encoder,e,i)&&i!==void 0&&this._resumableStreams.add(o)}if(or(e)||Jn(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s){if(this._closed){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(o)){for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o);return}for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);throw new Error(`No connection established for request ID: ${String(n)}`)}if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(l=>this._requestResponseMap.get(l));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c);this._resumableStreams.delete(o)}}}}});var Qb={};To(Qb,{StreamableHTTPServerTransport:()=>nm});var nm,ew=X(()=>{Zb();Yb();nm=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new lc(e),this._requestListener=em(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await em(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var D={};To(D,{BRAND:()=>Mw,DIRTY:()=>Fr,EMPTY_PATH:()=>mw,INVALID:()=>L,NEVER:()=>v$,OK:()=>Ze,ParseStatus:()=>Ie,Schema:()=>J,ZodAny:()=>_r,ZodArray:()=>tr,ZodBigInt:()=>Br,ZodBoolean:()=>Vr,ZodBranded:()=>zo,ZodCatch:()=>nn,ZodDate:()=>Jr,ZodDefault:()=>rn,ZodDiscriminatedUnion:()=>Fs,ZodEffects:()=>ft,ZodEnum:()=>en,ZodError:()=>Xe,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Bs,ZodIntersection:()=>Xr,ZodIssueCode:()=>k,ZodLazy:()=>Yr,ZodLiteral:()=>Qr,ZodMap:()=>Mn,ZodNaN:()=>Zn,ZodNativeEnum:()=>tn,ZodNever:()=>kt,ZodNull:()=>Kr,ZodNullable:()=>Dt,ZodNumber:()=>Hr,ZodObject:()=>Qe,ZodOptional:()=>Ye,ZodParsedType:()=>P,ZodPipeline:()=>Ro,ZodPromise:()=>vr,ZodReadonly:()=>on,ZodRecord:()=>Hs,ZodSchema:()=>J,ZodSet:()=>jn,ZodString:()=>yr,ZodSymbol:()=>On,ZodTransformer:()=>ft,ZodTuple:()=>Zt,ZodType:()=>J,ZodUndefined:()=>Wr,ZodUnion:()=>Gr,ZodUnknown:()=>er,ZodVoid:()=>Nn,addIssueToContext:()=>E,any:()=>Bw,array:()=>Kw,bigint:()=>Lw,boolean:()=>gm,coerce:()=>_$,custom:()=>pm,date:()=>qw,datetimeRegex:()=>dm,defaultErrorMap:()=>Yt,discriminatedUnion:()=>Yw,effect:()=>l$,enum:()=>a$,function:()=>o$,getErrorMap:()=>In,getParsedType:()=>jt,instanceof:()=>Zw,intersection:()=>Qw,isAborted:()=>qs,isAsync:()=>Cn,isDirty:()=>Us,isValid:()=>gr,late:()=>jw,lazy:()=>s$,literal:()=>i$,makeIssue:()=>Eo,map:()=>r$,nan:()=>Dw,nativeEnum:()=>c$,never:()=>Jw,null:()=>Hw,nullable:()=>f$,number:()=>hm,object:()=>yc,objectUtil:()=>mc,oboolean:()=>y$,onumber:()=>g$,optional:()=>d$,ostring:()=>h$,pipeline:()=>m$,preprocess:()=>p$,promise:()=>u$,quotelessJson:()=>dw,record:()=>t$,set:()=>n$,setErrorMap:()=>pw,strictObject:()=>Gw,string:()=>mm,symbol:()=>Uw,transformer:()=>l$,tuple:()=>e$,undefined:()=>Fw,union:()=>Xw,unknown:()=>Vw,util:()=>Y,void:()=>Ww});var Y;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Y||(Y={}));var mc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(mc||(mc={}));var P=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),jt=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var k=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),dw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Xe=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Xe.create=t=>new Xe(t);var fw=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}},Yt=fw;var im=Yt;function pw(t){im=t}function In(){return im}var Eo=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},mw=[];function E(t,e){let r=In(),n=Eo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Yt?void 0:Yt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return L;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return L;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),Fr=t=>({status:"dirty",value:t}),Ze=t=>({status:"valid",value:t}),qs=t=>t.status==="aborted",Us=t=>t.status==="dirty",gr=t=>t.status==="valid",Cn=t=>typeof Promise<"u"&&t instanceof Promise;var M;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(M||(M={}));var dt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},am=(t,e)=>{if(gr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Xe(t.common.issues);return this._error=r,this._error}}};function B(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var J=class{get description(){return this._def.description}_getType(e){return jt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:jt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:jt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Cn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:jt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return am(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:jt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return gr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>gr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:jt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Cn(o)?o:Promise.resolve(o));return am(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new ft({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ye.create(this,this._def)}nullable(){return Dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tr.create(this)}promise(){return vr.create(this,this._def)}or(e){return Gr.create([this,e],this._def)}and(e){return Xr.create(this,e,this._def)}transform(e){return new ft({...B(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new rn({...B(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new zo({typeName:S.ZodBranded,type:this,...B(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new nn({...B(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ro.create(this,e)}readonly(){return on.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},hw=/^c[^\s-]{8,}$/i,gw=/^[0-9a-z]+$/,yw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_w=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vw=/^[a-z0-9_-]{21}$/i,xw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ww=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hc,kw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Sw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Tw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ew=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,um="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Pw=new RegExp(`^${um}$`);function lm(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Iw(t){return new RegExp(`^${lm(t)}$`)}function dm(t){let e=`${um}T${lm(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Cw(t,e){return!!((e==="v4"||!e)&&kw.test(t)||(e==="v6"||!e)&&Tw.test(t))}function Aw(t,e){if(!xw.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Ow(t,e){return!!((e==="v4"||!e)&&Sw.test(t)||(e==="v6"||!e)&&Ew.test(t))}var yr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.string,received:s.parsedType}),L}let n=new Ie,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?E(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&E(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ww.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")hc||(hc=new RegExp($w,"u")),hc.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")_w.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")vw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")hw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")gw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")yw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),E(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?dm(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Pw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Iw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?bw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Cw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Aw(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Ow(e.data,s.version)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?zw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Rw.test(e.data)||(o=this._getOrReturnCtx(e,o),E(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):Y.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...M.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...M.errToObj(e)})}url(e){return this._addCheck({kind:"url",...M.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...M.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...M.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...M.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...M.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...M.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...M.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...M.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...M.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...M.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...M.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...M.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...M.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...M.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...M.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...M.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...M.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...M.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...M.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...M.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...M.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...M.errToObj(r)})}nonempty(e){return this.min(1,M.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};yr.create=t=>new yr({checks:[],typeName:S.ZodString,coerce:t?.coerce??!1,...B(t)});function Nw(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Hr=class t extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.number){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.number,received:s.parsedType}),L}let n,o=new Ie;for(let s of this._def.checks)s.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Nw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_finite,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:M.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:M.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Hr.create=t=>new Hr({checks:[],typeName:S.ZodNumber,coerce:t?.coerce||!1,...B(t)});var Br=class t extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let n,o=new Ie;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),E(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,M.toString(r))}gt(e,r){return this.setLimit("min",e,!1,M.toString(r))}lte(e,r){return this.setLimit("max",e,!0,M.toString(r))}lt(e,r){return this.setLimit("max",e,!1,M.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:M.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Br.create=t=>new Br({checks:[],typeName:S.ZodBigInt,coerce:t?.coerce??!1,...B(t)});var Vr=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.boolean,received:n.parsedType}),L}return Ze(e.data)}};Vr.create=t=>new Vr({typeName:S.ZodBoolean,coerce:t?.coerce||!1,...B(t)});var Jr=class t extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_type,expected:P.date,received:s.parsedType}),L}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return E(s,{code:k.invalid_date}),L}let n=new Ie,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),E(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Y.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:M.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:M.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Jr.create=t=>new Jr({checks:[],coerce:t?.coerce||!1,typeName:S.ZodDate,...B(t)});var On=class extends J{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.symbol,received:n.parsedType}),L}return Ze(e.data)}};On.create=t=>new On({typeName:S.ZodSymbol,...B(t)});var Wr=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.undefined,received:n.parsedType}),L}return Ze(e.data)}};Wr.create=t=>new Wr({typeName:S.ZodUndefined,...B(t)});var Kr=class extends J{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.null,received:n.parsedType}),L}return Ze(e.data)}};Kr.create=t=>new Kr({typeName:S.ZodNull,...B(t)});var _r=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return Ze(e.data)}};_r.create=t=>new _r({typeName:S.ZodAny,...B(t)});var er=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ze(e.data)}};er.create=t=>new er({typeName:S.ZodUnknown,...B(t)});var kt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return E(r,{code:k.invalid_type,expected:P.never,received:r.parsedType}),L}};kt.create=t=>new kt({typeName:S.ZodNever,...B(t)});var Nn=class extends J{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.void,received:n.parsedType}),L}return Ze(e.data)}};Nn.create=t=>new Nn({typeName:S.ZodVoid,...B(t)});var tr=class t extends J{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==P.array)return E(r,{code:k.invalid_type,expected:P.array,received:r.parsedType}),L;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(E(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(E(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(E(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new dt(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new dt(r,i,r.path,a)));return Ie.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:M.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:M.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:M.toString(r)}})}nonempty(e){return this.min(1,e)}};tr.create=(t,e)=>new tr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...B(e)});function An(t){if(t instanceof Qe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ye.create(An(n))}return new Qe({...t._def,shape:()=>e})}else return t instanceof tr?new tr({...t._def,type:An(t.element)}):t instanceof Ye?Ye.create(An(t.unwrap())):t instanceof Dt?Dt.create(An(t.unwrap())):t instanceof Zt?Zt.create(t.items.map(e=>An(e))):t}var Qe=class t extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let u=this._getOrReturnCtx(e);return E(u,{code:k.invalid_type,expected:P.object,received:u.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof kt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new dt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof kt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(E(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new dt(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,m=await l.value;u.push({key:d,value:m,alwaysSet:l.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(n,u)):Ie.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return M.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:M.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return An(this)}partial(e){let r={};for(let n of Y.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ye;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return fm(Y.objectKeys(this.shape))}};Qe.create=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...B(e)});Qe.strictCreate=(t,e)=>new Qe({shape:()=>t,unknownKeys:"strict",catchall:kt.create(),typeName:S.ZodObject,...B(e)});Qe.lazycreate=(t,e)=>new Qe({shape:t,unknownKeys:"strip",catchall:kt.create(),typeName:S.ZodObject,...B(e)});var Gr=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Xe(a.ctx.common.issues));return E(r,{code:k.invalid_union,unionErrors:i}),L}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Xe(c));return E(r,{code:k.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Gr.create=(t,e)=>new Gr({options:t,typeName:S.ZodUnion,...B(e)});var Qt=t=>t instanceof Yr?Qt(t.schema):t instanceof ft?Qt(t.innerType()):t instanceof Qr?[t.value]:t instanceof en?t.options:t instanceof tn?Y.objectValues(t.enum):t instanceof rn?Qt(t._def.innerType):t instanceof Wr?[void 0]:t instanceof Kr?[null]:t instanceof Ye?[void 0,...Qt(t.unwrap())]:t instanceof Dt?[null,...Qt(t.unwrap())]:t instanceof zo||t instanceof on?Qt(t.unwrap()):t instanceof nn?Qt(t._def.innerType):[],Fs=class t extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return E(r,{code:k.invalid_type,expected:P.object,received:r.parsedType}),L;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Qt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...B(n)})}};function gc(t,e){let r=jt(t),n=jt(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=gc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=gc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Xr=class extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qs(s)||qs(i))return L;let a=gc(s.value,i.value);return a.valid?((Us(s)||Us(i))&&r.dirty(),{status:r.value,value:a.data}):(E(n,{code:k.invalid_intersection_types}),L)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xr.create=(t,e,r)=>new Xr({left:t,right:e,typeName:S.ZodIntersection,...B(r)});var Zt=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return E(n,{code:k.invalid_type,expected:P.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return E(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new dt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Zt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:S.ZodTuple,rest:null,...B(e)})};var Hs=class t extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return E(n,{code:k.invalid_type,expected:P.object,received:n.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new dt(n,a,n.path,a)),value:i._parse(new dt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof J?new t({keyType:e,valueType:r,typeName:S.ZodRecord,...B(n)}):new t({keyType:yr.create(),valueType:e,typeName:S.ZodRecord,...B(r)})}},Mn=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.map)return E(n,{code:k.invalid_type,expected:P.map,received:n.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new dt(n,a,n.path,[u,"key"])),value:s._parse(new dt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return L;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return L;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Mn.create=(t,e,r)=>new Mn({valueType:e,keyType:t,typeName:S.ZodMap,...B(r)});var jn=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return E(n,{code:k.invalid_type,expected:P.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(E(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(E(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return L;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new dt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:M.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:M.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};jn.create=(t,e)=>new jn({valueType:t,minSize:null,maxSize:null,typeName:S.ZodSet,...B(e)});var Bs=class t extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return E(r,{code:k.invalid_type,expected:P.function,received:r.parsedType}),L;function n(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,In(),Yt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return Eo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,In(),Yt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof vr){let a=this;return Ze(async function(...c){let u=new Xe([]),l=await a._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw u.addIssue(o(d,p)),u})})}else{let a=this;return Ze(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Xe([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Xe([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Zt.create(e).rest(er.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Zt.create([]).rest(er.create()),returns:r||er.create(),typeName:S.ZodFunction,...B(n)})}},Yr=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Yr.create=(t,e)=>new Yr({getter:t,typeName:S.ZodLazy,...B(e)});var Qr=class extends J{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return E(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Qr.create=(t,e)=>new Qr({value:t,typeName:S.ZodLiteral,...B(e)});function fm(t,e){return new en({values:t,typeName:S.ZodEnum,...B(e)})}var en=class t extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{expected:Y.joinValues(n),received:r.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return E(r,{received:r.data,code:k.invalid_enum_value,options:n}),L}return Ze(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};en.create=fm;var tn=class extends J{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=Y.objectValues(r);return E(n,{expected:Y.joinValues(o),received:n.parsedType,code:k.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return E(n,{received:n.data,code:k.invalid_enum_value,options:o}),L}return Ze(e.data)}get enum(){return this._def.values}};tn.create=(t,e)=>new tn({values:t,typeName:S.ZodNativeEnum,...B(e)});var vr=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return E(r,{code:k.invalid_type,expected:P.promise,received:r.parsedType}),L;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Ze(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};vr.create=(t,e)=>new vr({type:t,typeName:S.ZodPromise,...B(e)});var ft=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Fr(c.value):r.value==="dirty"?Fr(c.value):c});{if(r.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?Fr(a.value):r.value==="dirty"?Fr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?L:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?L:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gr(i))return L;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>gr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):L);Y.assertNever(o)}};ft.create=(t,e,r)=>new ft({schema:t,typeName:S.ZodEffects,effect:e,...B(r)});ft.createWithPreprocess=(t,e,r)=>new ft({schema:e,effect:{type:"preprocess",transform:t},typeName:S.ZodEffects,...B(r)});var Ye=class extends J{_parse(e){return this._getType(e)===P.undefined?Ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:S.ZodOptional,...B(e)});var Dt=class extends J{_parse(e){return this._getType(e)===P.null?Ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:S.ZodNullable,...B(e)});var rn=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rn.create=(t,e)=>new rn({innerType:t,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var nn=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Cn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};nn.create=(t,e)=>new nn({innerType:t,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Zn=class extends J{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return E(n,{code:k.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};Zn.create=t=>new Zn({typeName:S.ZodNaN,...B(t)});var Mw=Symbol("zod_brand"),zo=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ro=class t extends J{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?L:s.status==="dirty"?(r.dirty(),Fr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:S.ZodPipeline})}},on=class extends J{_parse(e){let r=this._def.innerType._parse(e),n=o=>(gr(o)&&(o.value=Object.freeze(o.value)),o);return Cn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};on.create=(t,e)=>new on({innerType:t,typeName:S.ZodReadonly,...B(e)});function cm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function pm(t,e={},r){return t?_r.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=cm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=cm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):_r.create()}var jw={object:Qe.lazycreate},S;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(S||(S={}));var Zw=(t,e={message:`Input not instance of ${t.name}`})=>pm(r=>r instanceof t,e),mm=yr.create,hm=Hr.create,Dw=Zn.create,Lw=Br.create,gm=Vr.create,qw=Jr.create,Uw=On.create,Fw=Wr.create,Hw=Kr.create,Bw=_r.create,Vw=er.create,Jw=kt.create,Ww=Nn.create,Kw=tr.create,yc=Qe.create,Gw=Qe.strictCreate,Xw=Gr.create,Yw=Fs.create,Qw=Xr.create,e$=Zt.create,t$=Hs.create,r$=Mn.create,n$=jn.create,o$=Bs.create,s$=Yr.create,i$=Qr.create,a$=en.create,c$=tn.create,u$=vr.create,l$=ft.create,d$=Ye.create,f$=Dt.create,p$=ft.createWithPreprocess,m$=Ro.create,h$=()=>mm().optional(),g$=()=>hm().optional(),y$=()=>gm().optional(),_$={string:(t=>yr.create({...t,coerce:!0})),number:(t=>Hr.create({...t,coerce:!0})),boolean:(t=>Vr.create({...t,coerce:!0})),bigint:(t=>Br.create({...t,coerce:!0})),date:(t=>Jr.create({...t,coerce:!0}))};var v$=L;He();He();He();He();var zk=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");le.init(t,e),t.def=e,t.parse=(r,n)=>Cc(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>cn(t,r,n),t.parseAsync=async(r,n)=>Oc(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>un(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var Rk=w("ZodMiniObject",(t,e)=>{ni.init(t,e),zk.init(t,e),ee.defineLazy(t,"shape",()=>e.shape)});function xl(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new Rk(r)}He();si();function Ut(t){return!!t._zod}function fn(t){let e=Object.values(t);if(e.length===0)return xl({});let r=e.every(Ut),n=e.every(o=>!Ut(o));if(r)return xl(t);if(n)return yc(t);throw new Error("Mixed Zod versions detected in object shape.")}function wr(t,e){return Ut(t)?cn(t,e):t.safeParse(e)}async function pi(t,e){return Ut(t)?await un(t,e):await t.safeParseAsync(e)}function $r(t){if(!t)return;let e;if(Ut(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Fn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return fn(t)}}if(Ut(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Ik(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function mi(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${Ik(e.path)}`:e.message).join(`
52
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Zh(t){return t.description}function Dh(t){if(Ut(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Hn(t){if(Ut(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}Sr();function Tr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Pg=Symbol("Let zodToJsonSchema decide on which parser to use");var Rg={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ig=t=>typeof t=="string"?{...Rg,name:t}:{...Rg,...t};var Cg=t=>{let e=Ig(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Gl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function re(t,e,r,n,o){t[e]=r,Gl(t,e,n,o)}var Di=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Di(e,t.currentPath):e.join("/")}}function Ag(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==S.ZodAny&&(r.items=U(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&re(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&re(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(re(r,"minItems",t.exactLength.value,t.exactLength.message,e),re(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Og(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Ng(){return{type:"boolean"}}function Li(t,e){return U(t.type._def,e)}var Mg=(t,e)=>U(t.innerType._def,e);function Xl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Xl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return nE(t,e)}}var nE=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":re(r,"minimum",n.value,n.message,e);break;case"max":re(r,"maximum",n.value,n.message,e);break}return r};function jg(t,e){return{...U(t.innerType._def,e),default:t.defaultValue()}}function Zg(t,e){return e.effectStrategy==="input"?U(t.schema._def,e):ke(e)}function Dg(t){return{type:"string",enum:Array.from(t.values)}}var oE=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Lg(t,e){let r=[U(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),U(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(oE(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function qg(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Yl,Tt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Yl===void 0&&(Yl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yl),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Et(r,"email",n.message,e);break;case"format:idn-email":Et(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,Tt.email,n.message,e);break}break;case"url":Et(r,"uri",n.message,e);break;case"uuid":Et(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,Tt.cuid,n.message,e);break;case"cuid2":Ve(r,Tt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${Ql(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${Ql(n.value,e)}$`),n.message,e);break;case"datetime":Et(r,"date-time",n.message,e);break;case"date":Et(r,"date",n.message,e);break;case"time":Et(r,"time",n.message,e);break;case"duration":Et(r,"duration",n.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(Ql(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Et(r,"ipv4",n.message,e),n.version!=="v4"&&Et(r,"ipv6",n.message,e);break}case"base64url":Ve(r,Tt.base64url,n.message,e);break;case"jwt":Ve(r,Tt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,Tt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,Tt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,Tt.emoji(),n.message,e);break;case"ulid":{Ve(r,Tt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Et(r,"binary",n.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,Tt.base64,n.message,e);break}}break}case"nanoid":Ve(r,Tt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ql(t,e){return e.patternStrategy==="escape"?iE(t):t}var sE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iE(t){let e="";for(let r=0;r<t.length;r++)sE.has(t[r])||(e+="\\"),e+=t[r];return e}function Et(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):re(t,"format",e,r,n)}function Ve(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Ug(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):re(t,"pattern",Ug(e,n),r,n)}function Ug(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
53
53
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
54
54
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
55
55
  `:`[${n[c]}\r
56
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function 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 Ui(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=qi(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===S.ZodBranded&&t.keyType._def.type._def.typeName===S.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Li(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Fg(t,e){if(e.mapStrategy==="record")return Ui(t,e);let r=U(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Hg(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Bg(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function Vg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var es={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wg(t,e){if(e.target==="openApi3")return Jg(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in es&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=es[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Jg(t,e)}var Jg=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>U(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Kg(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:es[t.innerType._def.typeName],nullable:!0}:{type:[es[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=U(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Gg(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Gl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}function Xg(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=cE(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=U(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=aE(t,e);return i!==void 0&&(n.additionalProperties=i),n}function aE(t,e){if(t.catchall._def.typeName!=="ZodNever")return U(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function cE(t){try{return t.isOptional()}catch{return!0}}var Yg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return U(t.innerType._def,e);let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)};var Qg=(t,e)=>{if(e.pipeStrategy==="input")return U(t.in._def,e);if(e.pipeStrategy==="output")return U(t.out._def,e);let r=U(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=U(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function ey(t,e){return U(t.type._def,e)}function ty(t,e){let n={type:"array",uniqueItems:!0,items:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function ry(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:U(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ny(t){return{not:ke(t)}}function oy(t){return ke(t)}var sy=(t,e)=>U(t.innerType._def,e);var iy=(t,e,r)=>{switch(e){case S.ZodString:return qi(t,r);case S.ZodNumber:return Gg(t,r);case S.ZodObject:return Xg(t,r);case S.ZodBigInt:return Og(t,r);case S.ZodBoolean:return Ng();case S.ZodDate:return Xl(t,r);case S.ZodUndefined:return ny(r);case S.ZodNull:return Vg(r);case S.ZodArray:return Ag(t,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Wg(t,r);case S.ZodIntersection:return Lg(t,r);case S.ZodTuple:return ry(t,r);case S.ZodRecord:return Ui(t,r);case S.ZodLiteral:return qg(t,r);case S.ZodEnum:return Dg(t);case S.ZodNativeEnum:return Hg(t);case S.ZodNullable:return Kg(t,r);case S.ZodOptional:return Yg(t,r);case S.ZodMap:return Fg(t,r);case S.ZodSet:return ty(t,r);case S.ZodLazy:return()=>t.getter()._def;case S.ZodPromise:return ey(t,r);case S.ZodNaN:case S.ZodNever:return Bg(r);case S.ZodEffects:return Zg(t,r);case S.ZodAny:return ke(r);case S.ZodUnknown:return oy(r);case S.ZodDefault:return jg(t,r);case S.ZodBranded:return Li(t,r);case S.ZodReadonly:return sy(t,r);case S.ZodCatch:return Mg(t,r);case S.ZodPipeline:return Qg(t,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(e)}};function U(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Pg)return a}if(n&&!r){let a=uE(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=iy(t,t.typeName,e),i=typeof s=="function"?U(s(),e):s;if(i&&lE(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var uE=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Di(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},lE=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ed=(t,e)=>{let r=Cg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:U(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=U(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function dE(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function td(t,e){return Ut(t)?vl(t,{target:dE(e?.target),io:e?.pipeStrategy??"input"}):ed(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function rd(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function nd(t,e){let r=wr(t,e);if(!r.success)throw r.error;return r.data}var fE=6e4,Fi=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(bi,r=>{this._oncancel(r)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler($i,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Si,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ei,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new C(O.InvalidParams,`Task not found: ${s}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,m=new C(d.error.code,d.error.message,d.error.data);l(m)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new C(O.InvalidParams,`Task not found: ${s}`);if(!Tr(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(Tr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[kr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(zi,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new C(O.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Pi,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tr(o.status))throw new C(O.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new C(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(O.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),C.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),or(s)||Jn(s)?this._onresponse(s):nr(s)?this._onrequest(s,i):vg(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=C.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[kr]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new C(O.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:f,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>o?.send(f)).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(f).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=gg(e.params)?e.params.task:void 0,m=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(f,g)},sendRequest:async(f,g,h)=>{if(l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};s&&!_.relatedTask&&(_.relatedTask={taskId:s});let v=_.relatedTask?.taskId??s;return v&&m&&await m.updateTaskStatus(v,"input_required"),await this.request(f,g,_)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:m,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new C(O.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async f=>{if(l.signal.aborted)return;let g={result:f,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async f=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:O.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),or(e))n(e);else{let i=new C(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(or(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),or(e))o(e);else{let i=C.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof C?i:new C(O.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Wn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Tr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new C(O.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(O.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof C?i:new C(O.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[kr]:c}});let f=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=v instanceof C?v:new C(O.RequestTimeout,String(v));l(y)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=wr(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??fE,h=()=>f(C.fromError(O.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,h,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let v=y=>{let x=this._responseHandlers.get(m);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(m),l(y)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ti,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ri,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},bg,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[kr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[kr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[kr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=rd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=nd(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=rd(e);this._notificationHandlers.set(n,o=>{let s=nd(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n??this._transport?.sessionId,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&nr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new C(O.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new C(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new C(O.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Go.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Tr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new C(O.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Tr(a.status))throw new C(O.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Go.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function ay(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cy(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];ay(i)&&ay(s)?r[o]={...i,...s}:r[o]=s}return r}Sr();var lv=pc(Kf(),1),dv=pc(uv(),1);function SC(){let t=new lv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dv.default)(t),t}var za=class{constructor(e){this._ajv=e??SC()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};Sr();var Ra=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),d=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==d.size||![...l].every(m=>d.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Qo,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Xn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function fv(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function pv(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Pa=class extends Fi{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Yo.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new za,this.setRequestHandler(wi,n=>this._oninitialize(n)),this.setNotificationHandler(Ll,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Jl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Yo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ra(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=cy(this._capabilities,e)}setRequestHandler(e,r){let o=$r(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Hn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=wr(Gn,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new C(O.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let f=wr(Wn,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new C(O.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let p=wr(ji,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new C(O.InvalidParams,`Invalid tools/call result: ${f}`)}return p.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){pv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&fv(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Vn.includes(r)?r:Nl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},xi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Wl,r):this.request({method:"sampling/createMessage",params:e},Qo,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Xn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Xn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new C(O.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof C?i:new C(O.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Kl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Sr();var hv=Symbol.for("mcp.completable");function np(t){return!!t&&typeof t=="object"&&hv in t}function gv(t){return t[hv]?.complete}var mv;(function(t){t.Completable="McpCompletable"})(mv||(mv={}));var Ia=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",o=0,s=0;for(;o<e.length;)if(e[o]==="{"){n&&(r.push(n),n="");let i=e.indexOf("}",o);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(o+1,i),c=this.getOperator(a),u=a.includes("*"),l=this.getNames(a),d=l[0];for(let m of l)t.validateLength(m,1e6,"Variable name");r.push({name:d,operator:c,names:l,exploded:u}),o=i+1}else n+=e[o],o++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let u=r[c];if(u===void 0)return"";let l=Array.isArray(u)?u.map(d=>this.encodeValue(d,e.operator)).join(","):this.encodeValue(u.toString(),e.operator);return`${c}=${l}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[e.name];if(n===void 0)return"";let s=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(e){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let s=this.expandPart(o,e);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let s of e.names)t.validateLength(s,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){let i=e.names[s],a=s===0?"\\"+e.operator:"&";r.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n,o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let a of this.parts)if(typeof a=="string")r+=this.escapeRegExp(a);else{let c=this.partToRegExp(a);for(let{pattern:u,name:l}of c)r+=u,n.push({name:l,exploded:a.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let o=new RegExp(r),s=e.match(o);if(!s)return null;let i={};for(let a=0;a<n.length;a++){let{name:c,exploded:u}=n[a],l=s[a+1],d=c.replace("*","");u&&l.includes(",")?i[d]=l.split(","):i[d]=l}return i}};var TC=/^[A-Za-z0-9._-]{1,128}$/;function EC(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TC.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function zC(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function op(t){let e=EC(t);return zC(t,e.warnings),e.isValid}var Ca=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};function RC(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function PC(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var Aa=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Pa(e,r),this._maxToolInputElements=PC(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new Ca(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Mi)),this.server.assertCanSetRequestHandler(Nr(Gn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mi,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Fn(r.inputSchema);return o?td(o,{strictUnions:!0,pipeStrategy:"input"}):IC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Fn(r.outputSchema);o&&(n.outputSchema=td(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new C(O.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new C(O.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new C(O.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof C&&n.code===O.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(this._maxToolInputElements!==void 0&&RC(r,this._maxToolInputElements)>this._maxToolInputElements)throw new C(O.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Fn(e.inputSchema)??e.inputSchema,i=await pi(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=mi(a);throw new C(O.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new C(O.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Fn(e.outputSchema),s=await pi(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=mi(i);throw new C(O.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,l));let d=await n.taskStore.getTask(c);if(!d)throw new C(O.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Nr(Zi)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zi,async e=>{switch(e.params.ref.type){case"ref/prompt":return Eg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return zg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(O.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new C(O.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Is;let s=$r(n.argsSchema)?.[e.params.argument.name];if(!np(s))return Is;let i=gv(s);if(!i)return Is;let a=await i(e.params.argument.value,e.params.context);return _v(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Is;throw new C(O.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Is;let s=await o(e.params.argument.value,e.params.context);return _v(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Ii)),this.server.assertCanSetRequestHandler(Nr(Ci)),this.server.assertCanSetRequestHandler(Nr(Ai)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ii,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ci,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ai,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new C(O.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new C(O.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Nr(Oi)),this.server.assertCanSetRequestHandler(Nr(Ni)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oi,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?CC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ni,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new C(O.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new C(O.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Fn(n.argsSchema),s=await pi(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",u=mi(c);throw new C(O.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:fn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=fn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Ye?c._def?.innerType:c;return np(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){op(e);let l={title:r,description:n,inputSchema:yv(o),outputSchema:yv(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&op(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=fn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=fn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(sp(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!sp(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Oa=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Ia(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},IC={type:"object",properties:{}};function vv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function xv(t){return"_def"in t||"_zod"in t||vv(t)}function sp(t){return typeof t!="object"||t===null||xv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vv)}function yv(t){if(t){if(sp(t))return fn(t);if(!xv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function CC(t){let e=$r(t);return e?Object.entries(e).map(([r,n])=>{let o=Zh(n),s=Dh(n);return{name:r,description:o,required:!s}}):[]}function Nr(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Hn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function _v(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Is={completion:{values:[],hasMore:!1}};import wv from"node:process";Sr();var AC=10*1024*1024,Na=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??AC}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
57
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),OC(r)}clear(){this._buffer=void 0}};function OC(t){return Bo.parse(JSON.parse(t))}function bv(t){return JSON.stringify(t)+`
58
+ `}var Ma=class{constructor(e=wv.stdin,r=wv.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Na({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=bv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};Sr();function ja(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(t==null)return{text:"",hasBinary:!1};if(!Array.isArray(t))return{text:JSON.stringify(t??""),hasBinary:!1};let e="",r=!1,n,o,s="",i;for(let a of t){if(a==null||typeof a!="object"){e+=String(a??"");continue}let c=a;switch(c.type){case"text":case"input_text":case"output_text":e+=c.text??"";break;case"tool_use":{o="tool_call",n=c.name??n;let u=`[tool call: ${c.name}] ${JSON.stringify(c.input??{})}`;e+=u,s+=u;break}case"tool_result":{o="tool_result";let u=ja(c.content);r=r||u.hasBinary,e+=u.text,c.is_error===!0&&(i=!0);break}case"image":case"document":r=!0,e+=`[${c.type}]`;break;case"image_url":case"input_image":r=!0,e+="[image]";break;case"input_audio":r=!0,e+="[audio]";break;case"file":case"input_file":r=!0,e+="[file]";break;case"thinking":e+=c.thinking??"";break;case"redacted_thinking":e+="[redacted thinking]";break;default:e+=JSON.stringify(c)}}return{text:e,hasBinary:r,toolName:n,kind:o,toolCallText:s||void 0,isError:i}}function cp(t,e){let r=t&&typeof t=="object"?t:{},n=String(r.role??"user"),o=ja(r.content),s=o.kind??(n==="developer"?"system":["system","user","assistant"].includes(n)?n:"other"),i=o.toolName,a=o.text,c=o.toolCallText;n==="tool"&&(s="tool_result");let u=r.tool_calls,l=Array.isArray(u)?u.filter(d=>d&&typeof d=="object"):void 0;if(l&&l.length>0){s="tool_call",i=l[0]?.function?.name??l[0]?.name;let d=l.map(m=>`[tool call: ${m.function?.name??m.name}] ${m.function?.arguments??JSON.stringify(m.input??{})}`).join(`
59
+ `);a+=d,c=(c??"")+d}return{index:e,role:n,kind:s,text:a,toolName:i,toolCallText:c,hasBinary:o.hasBinary,isError:o.isError}}function ip(t,e){let r=t.trimStart()[0];return{sourceFormat:"text",parseWarning:t.trim()===""?"Input is empty \u2014 nothing to profile.":e&&(r==="{"||r==="[")?`Input starts like JSON but does not parse (${e.message}), so it is not a conversation file.`:void 0,messages:t.trim()===""?[]:[{index:0,role:"user",kind:"user",text:t,hasBinary:!1}]}}function NC(t){if(typeof t=="string")return{text:t,hasBinary:!1};if(!t||typeof t!="object")return{text:"",hasBinary:!1};let e=t;if(typeof e.text=="string")return{text:e.text,hasBinary:!1};if(e.inlineData||e.fileData)return{text:"[file]",hasBinary:!0};if(e.functionCall){let r=`[tool call: ${e.functionCall.name}] ${JSON.stringify(e.functionCall.args??{})}`;return{text:r,hasBinary:!1,kind:"tool_call",toolName:e.functionCall.name,call:r}}if(e.functionResponse){let r=e.functionResponse.response;return{text:typeof r?.output=="string"?r.output:typeof r?.content=="string"?r.content:JSON.stringify(r??{}),hasBinary:!1,kind:"tool_result",toolName:e.functionResponse.name}}return e.executableCode?{text:String(e.executableCode.code??""),hasBinary:!1}:e.codeExecutionResult?{text:String(e.codeExecutionResult.output??""),hasBinary:!1}:{text:JSON.stringify(e),hasBinary:!1}}function ap(t,e){let r=t&&typeof t=="object"?t:{},n=r.role==="model"?"assistant":String(r.role??"user"),o=Array.isArray(r.parts)?r.parts:[],s="",i=!1,a,c,u="";for(let d of o){let m=NC(d);s+=(s&&m.text?`
60
+ `:"")+m.text,i||=m.hasBinary,m.kind&&(a=m.kind),c??=m.toolName,m.call&&(u+=m.call)}let l=["system","user","assistant"].includes(n)?n:"other";return{index:e,role:n,kind:a??l,text:s,toolName:c,toolCallText:u||void 0,hasBinary:i}}function MC(t,e){if(typeof t=="string")return{index:e,role:"user",kind:"user",text:t,hasBinary:!1};let r=t&&typeof t=="object"?t:{},n=r.type;if(n==="function_call"||n==="custom_tool_call"||n==="local_shell_call"){let o=r.name??(n==="local_shell_call"?"local_shell":void 0),s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.input??r.action??{}),i=`[tool call: ${o}] ${s}`;return{index:e,role:"assistant",kind:"tool_call",text:i,toolName:o,toolCallText:i,hasBinary:!1}}if(n==="function_call_output"||n==="custom_tool_call_output"||n==="local_shell_call_output"){let o=r.output,s=typeof o=="string"?{text:o,hasBinary:!1}:ja(o);return{index:e,role:"tool",kind:"tool_result",text:s.text,hasBinary:s.hasBinary}}if(n==="reasoning"){let o=Array.isArray(r.summary)?r.summary.map(s=>s?.text??"").join(`
61
+ `):"";return{index:e,role:"assistant",kind:"assistant",text:o,hasBinary:!1}}return cp(r,e)}function $v(t){if(typeof t!="string")if(t!==null&&typeof t=="object")try{t=JSON.stringify(t)}catch{return ip("")}else t=t==null?"":String(t);let e;try{e=JSON.parse(t)}catch(l){return ip(t,l)}if(e===null||typeof e!="object")return ip(t);if(Array.isArray(e)){let l=e.length===0||e.some(d=>d&&typeof d=="object"&&("role"in d||"parts"in d));return e.length>0&&e.every(d=>d&&typeof d=="object"&&Array.isArray(d.parts))?{sourceFormat:"gemini",messages:e.map((d,m)=>ap(d,m))}:{sourceFormat:"array",parseWarning:l?void 0:"This is a JSON array, but no element has a `role` field \u2014 it does not look like a conversation.",messages:e.map((d,m)=>cp(d,m))}}let r=e,n=typeof r.model=="string"&&r.model?r.model:void 0;if(r.messages==null&&Array.isArray(r.contents)){let l=[],d=r.systemInstruction??r.system_instruction;if(d!=null){let m=typeof d=="string"?{text:d,hasBinary:!1}:ap(d,-1);l.push({index:-1,role:"system",kind:"system",text:m.text,hasBinary:m.hasBinary})}return l.push(...r.contents.map((m,p)=>ap(m,p))),{sourceFormat:"gemini",messages:l,model:n}}if(r.messages==null&&(typeof r.input=="string"||Array.isArray(r.input))){let l=[];typeof r.instructions=="string"&&r.instructions&&l.push({index:-1,role:"system",kind:"system",text:r.instructions,hasBinary:!1});let d=typeof r.input=="string"?[r.input]:r.input;return l.push(...d.map((m,p)=>MC(m,p))),{sourceFormat:"responses",messages:l,model:n}}let o=r.messages,s=Array.isArray(o)?o:[],i=o!=null&&!Array.isArray(o),a=[];if(r.system!=null){let l=ja(r.system);a.push({index:-1,role:"system",kind:"system",text:l.text,hasBinary:l.hasBinary})}a.push(...s.map((l,d)=>cp(l,d)));let c=r.system!=null||s.some(l=>Array.isArray(l?.content)&&l.content.some(d=>d?.type==="tool_use"||d?.type==="tool_result")),u=i?`\`messages\` is a ${typeof o}, not an array \u2014 this file is malformed.`:a.length===0?'This JSON has no `messages` array (and no `system`) \u2014 it does not look like a conversation. Expected {"messages":[{"role":\u2026,"content":\u2026}]}.':void 0;return{sourceFormat:c?"anthropic":"openai",parseWarning:u,messages:a,model:n}}import{createHash as pA}from"node:crypto";var kv=[[/claude.*haiku/i,2e5],[/claude.*(fable|mythos)|claude.*opus-?(5|4-[678])|claude.*sonnet-?(5|4-6)/i,1e6],[/claude.*sonnet|claude.*opus|claude-\d/i,2e5],[/gpt-5/i,4e5],[/gpt-4o|gpt-4-turbo|gpt-4\.1|o[134](-|$)/i,128e3],[/gpt-4(?!o|\.|-turbo)/i,8192],[/gpt-3\.5/i,16385],[/gemini.*(1\.5|2\.|2-5)/i,1e6],[/gemini-?3/i,1048576],[/llama.*3/i,128e3],[/mistral|mixtral/i,32e3]],Mq=Math.max(...kv.map(([,t])=>t));function Za(t){if(t){for(let[e,r]of kv)if(e.test(t))return r}}function Mr(t){return t?/claude/i.test(t)?"anthropic":/gpt|^o\d/i.test(t)?"openai":/gemini/i.test(t)?"google":"generic":"generic"}function jC(t){return t.length===0?0:(t.match(/[{}[\]()<>;:=_\/\\|"'`#$%&*+^~-]/g)?.length??0)/t.length}var Cs={anthropic:{prose:2.75,code:2.4},openai:{prose:4,code:3.2},google:{prose:4,code:3.2},generic:{prose:4,code:3.2}};function Sv(t){return jC(t)>.08}function up(t,e){let r=Cs[Mr(e)];return Sv(t)?r.code:r.prose}function At(t,e){return typeof t!="string"&&(t=String(t??"")),t?ZC(t.length,Sv(t),e):0}function ZC(t,e,r){if(!(t>0))return 0;let n=Cs[Mr(r)];return Math.ceil(t/(e?n.code:n.prose))}var lp=4;function R(t){if(!Number.isFinite(t))return"0";if(t<0)return`-${R(-t)}`;let e=Math.round(t);if(e<1e3)return String(e);let r=Math.round(e/100);if(r<100)return`${(r/10).toFixed(1)}k`;let n=Math.round(e/1e3);if(n<1e3)return`${n}k`;let o=Math.round(e/1e5);return o<1e4?`${(o/10).toFixed(1)}M`:`${(Math.round(e/1e8)/10).toFixed(1)}B`}var T=(t,e,r)=>({inputPerM:t,outputPerM:e,cacheReadPerM:r});function je(t,e,r){return r===void 0?new RegExp(`claude-(?:${t})-${e}(?![.\\d]|-\\d{1,2}(?!\\d))`,"i"):new RegExp(`claude-(?:${t})-${e}[-.]${r}(?!\\d)`,"i")}var Da=[/claude.*fable|claude.*mythos/i,/claude.*opus/i,/claude.*sonnet/i,/claude.*haiku/i],Tv=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Q(t){return new RegExp(`(?<![\\w.-])${Tv(t)}(?:-\\d{4}-\\d{2}-\\d{2})?(?![\\w.-])`,"i")}function Wt(t){return new RegExp(`(?<![\\w.-])${Tv(t)}(?![\\w.])(?!-(?:[\\w.]+-)*(?:lite|image|tts|live|audio|transcribe|translate)\\b)`,"i")}var Ke={fallback:!0},Ot={geo:!0},dp=t=>({over:272e3,rates:T(t.inputPerM*2,t.outputPerM*1.5,t.cacheReadPerM*2)}),vt=(t,e,r)=>{let n=T(t,e,r);return[n,{long:dp(n)}]},DC=[[je("fable|mythos",5,1),T(10,50,.25),Ot],[je("fable|mythos",5),T(10,50,1),Ot],[je("opus",5,5),T(4,20,.2),{geo:!0,fast:T(8,40,.4)}],[je("opus",5),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[je("opus",4,8),T(5,25,.5),{geo:!0,fast:T(10,50,1)}],[je("opus",4,7),T(5,25,.5),Ot],[je("opus",4,6),T(5,25,.5),Ot],[je("opus",4,5),T(5,25,.5)],[je("opus",4,1),T(15,75,1.5)],[je("opus",4),T(15,75,1.5)],[je("sonnet",5,5),T(2,10,.1),Ot],[je("sonnet",5),T(2,10,.2),Ot],[je("haiku",5,5),T(.1,.5,.01),{geo:!0,long:{over:1e5,rates:T(.5,2.5,.05)}}],[je("haiku",4,5),T(1,5,.1)],[je("sonnet",4,6),T(3,15,.3),Ot],[je("sonnet",4,5),T(3,15,.3)],[je("sonnet",4),T(3,15,.3)],[/claude-3-opus/i,T(15,75,1.5)],[/claude-3-5-haiku/i,T(.8,4,.08)],[/claude-3-haiku/i,T(.25,1.25,.03)],[/claude-3-[57]-sonnet/i,T(3,15,.3)],[Da[0],T(10,50,1),{...Ke,...Ot}],[Da[1],T(5,25,.5),{...Ke,...Ot}],[Da[2],T(3,15,.3),{...Ke,...Ot}],[Da[3],T(1,5,.1),{...Ke,...Ot}],[Q("gpt-6-astra"),...vt(10,50,1)],[Q("gpt-6-astra-law"),T(10,50,1)],[Q("gpt-6.1-sol"),...vt(2,10,.1)],[Q("gpt-6.1-terra"),...vt(1,5,.05)],[Q("gpt-6-sol"),...vt(2,10,.2)],[Q("gpt-6-luna"),...vt(.1,.5,.01)],[Q("gpt-6-cyber"),T(20,100,2)],[Q("gpt-6-rosalind"),...vt(15,75,1.5)],[Q("gpt-rosalind-research"),T(5,25,.5)],[Q("gpt-rosalind-discovery"),T(5,25,.5)],[Q("gpt-5.6-sol"),T(4,20,.4),{long:dp(T(4,20,.4)),changes:"2026-12-01"}],[Q("gpt-5.6"),T(4,20,.4),{long:dp(T(4,20,.4)),changes:"2026-12-01"}],[Q("gpt-5.6-terra"),...vt(2,12,.2)],[Q("gpt-5.6-luna"),...vt(.2,1.2,.02)],[Q("gpt-5.6-cyber"),T(12.5,75,1.25)],[Q("gpt-5.5"),...vt(5,30,.5)],[Q("gpt-5.5-pro"),...vt(30,180,30)],[Q("gpt-5.5-cyber"),T(12.5,75,1.25)],[Q("gpt-5.4"),...vt(2.5,15,.25)],[Q("gpt-5.4-mini"),T(.75,4.5,.075)],[Q("gpt-5.4-nano"),T(.2,1.25,.02)],[Q("gpt-5.4-pro"),...vt(30,180,30)],[Q("gpt-5.3-codex"),T(1.75,14,.175)],[Q("gpt-5.2"),T(1.75,14,.175)],[Q("gpt-5.2-pro"),T(21,168,21)],[Q("gpt-5.1"),T(1.25,10,.125)],[Q("gpt-5"),T(1.25,10,.125)],[Q("gpt-5-mini"),T(.25,2,.025)],[Q("gpt-5-nano"),T(.05,.4,.005)],[Q("gpt-5-pro"),T(15,120,15)],[Q("gpt-4.1"),T(2,8,.5)],[Q("gpt-4.1-mini"),T(.4,1.6,.1)],[Q("gpt-4o"),T(2.5,10,1.25)],[Q("gpt-4o-mini"),T(.15,.6,.075)],[Q("o3"),T(2,8,.5)],[Q("o3-pro"),T(20,80,20)],[Q("chat-latest"),T(5,30,.5)],[/gpt-5.*(mini|nano)/i,T(.25,2,.025),Ke],[/gpt-5/i,T(1.25,10,.125),Ke],[/gpt-4o-mini/i,T(.15,.6,.075),Ke],[/gpt-4o|gpt-4\.1/i,T(2.5,10,1.25),Ke],[/gpt-4-turbo/i,T(10,30,10),Ke],[/o[13](-|$)/i,T(2,8,1),Ke],[Wt("gemini-4-argon"),T(2,10,.1),{changes:"2026-12-01",then:T(4,20,.2)}],[Wt("gemini-3.8-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Wt("gemini-3.6-flash"),T(.75,3.75,.075),{changes:"2027-01-01",then:T(1.5,7.5,.15)}],[Wt("gemini-3.5-flash-lite"),T(.3,2.5,.03)],[Wt("gemini-3.1-flash-lite"),T(.25,1.5,.025)],[Wt("gemini-3.1-pro"),T(2,12,.2),{long:{over:2e5,rates:T(4,18,.4)}}],[Wt("gemini-3-flash"),T(.5,3,.05)],[Wt("gemini-2.5-pro"),T(1.25,10,.125),{long:{over:2e5,rates:T(2.5,15,.25)},changes:"2026-12-01",then:T(.75,3.75,.075)}],[Wt("gemini-2.5-flash"),T(.3,2.5,.03)],[Wt("gemini-2.5-flash-lite"),T(.1,.4,.01)],[/gemini-3[.\d]*-flash-lite/i,T(.3,2.5,.03),Ke],[/gemini-3[.\d]*-flash/i,T(.75,3.75,.075),Ke],[/gemini-3[.\d]*-pro/i,T(2,12,.2),Ke],[/gemini.*flash/i,T(.1,.4,.025),Ke],[/gemini.*pro/i,T(1.25,5,.31),Ke]];function LC(t){if(t)return DC.find(([e])=>e.test(t))}function go(t){return LC(t)?.[1]}function jr(t,e){return t/1e6*e.inputPerM}var Zq=10/1e3;var Dq=Object.freeze({fastUsd:0,geoUsd:0,longUsd:0,webSearchUsd:0,webSearches:0});function fp(t){return t/25e3}function Kt(t){return Number.isFinite(t)?t>=1?`$${t.toFixed(2)}`:t>=.01?`$${t.toFixed(3)}`:`$${t.toFixed(4)}`:"$0.00"}var Ev=/(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g,qC="[context-doctor: base64 blob removed \u2014 use file/image APIs instead]";function zv(t){if(t.startsWith("data:"))return!0;let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);if(e.size<24)return!1;let r=0;for(let n of e.values())n>r&&(r=n);return r/t.length<.35}function yo(t){for(let e of t.matchAll(Ev))if(zv(e[0]))return!0;return!1}function pp(t){return t.replace(Ev,e=>zv(e)?qC:e)}import{mkdirSync as Xq,readFileSync as oA,writeFileSync as Yq}from"node:fs";import{dirname as sA,join as iA}from"node:path";import{appendFileSync as FC,existsSync as hp,mkdirSync as HC,readFileSync as BC,statSync as VC,writeFileSync as JC}from"node:fs";import{homedir as Cv}from"node:os";import{dirname as Ov,join as _o}from"node:path";import{homedir as mp}from"node:os";import{join as Rv,resolve as UC}from"node:path";function Pv(t,e){if(t!==void 0&&t!==mp())return;let r=e.CLAUDE_CONFIG_DIR?.trim();return r?UC(r):void 0}function ur(t,e=process.env){return Pv(t,e)??Rv(t??mp(),".claude")}function Iv(t,e=process.env){return Rv(Pv(t,e)??t??mp(),".claude.json")}var WC={optimizeSaved:0,optimizeUsd:0,proxySaved:0,proxyUsd:0,proxyRequests:0,checks:0,warnings:0,shrinkage:0};function KC(t){let e={...WC},r=new Map;for(let n of t){if(n.ev==="rollup"&&n.carried){e.optimizeSaved+=n.carried.optimizeSaved,e.optimizeUsd+=n.carried.optimizeUsd,e.proxySaved+=n.carried.proxySaved,e.proxyUsd+=n.carried.proxyUsd,e.proxyRequests+=n.carried.proxyRequests,e.checks+=n.carried.checks,e.warnings+=n.carried.warnings,e.shrinkage+=n.carried.shrinkage,n.carried.since&&(e.since=Math.min(e.since??n.carried.since,n.carried.since));continue}e.since=Math.min(e.since??n.ts,n.ts),n.ev==="optimize"?(e.optimizeSaved+=n.saved??0,e.optimizeUsd+=n.usd??0):n.ev==="proxy"?(e.proxySaved+=n.saved??0,e.proxyUsd+=n.usd??0,e.proxyRequests+=n.requests??0):(n.ev==="check"||n.ev===void 0)&&n.sid!=="doctor-probe"&&(e.checks++,n.warn&&e.warnings++,n.sid&&n.sid!=="mcp-sketch"&&typeof n.tok=="number"&&r.set(n.sid,[...r.get(n.sid)??[],n.tok]))}for(let n of r.values())for(let o=1;o<n.length;o++)n[o]<n[o-1]&&(e.shrinkage+=n[o-1]-n[o]);return e}function GC(){let t=process.env.XDG_STATE_HOME?.trim();return t?_o(t,"context-doctor"):process.platform==="win32"?_o(process.env.LOCALAPPDATA?.trim()||_o(Cv(),"AppData","Local"),"context-doctor"):_o(Cv(),".local","state","context-doctor")}function XC(){let t=GC();if(hp(t))return t;let e=ur();return hp(e)?e:t}function gp(){return process.env.CONTEXT_DOCTOR_HOOK_STATE??_o(XC(),".context-doctor-hook-state.json")}function YC(){return _o(Ov(gp()),".context-doctor-ledger.jsonl")}var Av=100,QC=256*1024,eA=128*1024,tA=500,rA=4*1024;function nA(t){if(typeof t!="string")return;let e=t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return e.length>Av?e.slice(0,Av):e}function La(t){let e=YC();try{if(HC(Ov(e),{recursive:!0}),hp(e)&&VC(e).size>QC){let n=BC(e,"utf8").trimEnd().split(`
62
+ `),o=d=>{try{return[JSON.parse(d)]}catch{return[]}},s=new Set,i=0;for(let d=n.length-1;d>=0&&s.size<tA;d--){let m=Buffer.byteLength(n[d])+1;if(!(m>rA)){if(i+m>eA)break;s.add(d),i+=m}}let a=n.filter((d,m)=>s.has(m)),c=n.filter((d,m)=>!s.has(m)).flatMap(o),u=KC(c),l={ts:Date.now(),ev:"rollup",carried:u};JC(e,[JSON.stringify(l),...a].join(`
63
63
  `)+`
64
- `)}let r={...t};for(let n of["model","sid","cv","app"])if(n in r){let o=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=nA(r[n]);o===void 0?delete r[n]:r[n]=o}FC(e,JSON.stringify({ts:Date.now(),...r})+`
65
+ `)}catch{}}var aA=2,cA=.5,uA=2;function lA(){return iA(sA(gp()),".context-doctor-calibration.json")}function dA(t){let e=(t??"").toLowerCase();return e.includes("claude")?"claude":/gpt|^o\d/.test(e)?"gpt":e.includes("gemini")?"gemini":e?e.split(/[-_/]/)[0]:"unknown"}function fA(){try{return JSON.parse(oA(lA(),"utf8"))}catch{return{}}}function Nv(t){if(process.env.CONTEXT_DOCTOR_NO_CALIBRATION)return{factor:1,samples:0};let e=fA()[dA(t)];if(!e||e.v!==aA||e.samples<1||e.heuristicSum<=0)return{factor:1,samples:0};let r=e.exactSum/e.heuristicSum;return!Number.isFinite(r)||r<cA||r>uA?{factor:1,samples:0}:{factor:r,samples:e.samples}}function mA(t){switch(t.kind){case"system":return"system";case"user":return"user";case"assistant":return"assistant";case"tool_call":return"tool_calls";case"tool_result":return"tool_results";default:return"other"}}function hA(t,e){let r=new Map,n=0;for(let a of t){if(a.estSavings<=0)continue;if(a.messages.length===0){n+=a.estSavings;continue}let c=a.id==="near_duplicate"&&a.messages.length>2?a.messages.slice(1):[a.messages[a.messages.length-1]],u=a.estSavings/c.length;for(let l of c)r.set(l,Math.max(r.get(l)??0,u))}let o=Math.round([...r.values()].reduce((a,c)=>a+c,0)),s=Math.max(0,e-o),i=o+Math.min(n,s);return Math.min(i,Math.round(e*.9))}function gA(t,e=90){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e)+"\u2026":r}function Mv(t){return pA("sha1").update(t.replace(/\s+/g," ").trim()).digest("hex")}function yA(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function _A(t){let e=t.toLowerCase().replace(/\s+/g," ").trim().split(" "),r=e.length>1500,n=new Set;for(let o=0;o+8<=e.length;o++){let s=yA(e.slice(o,o+8).join(" "));(!r||s%8===0)&&n.add(s)}return n}var jv=.6;function vA(t,e){if(t.size===0||e.size===0)return 0;let r=0,[n,o]=t.size<=e.size?[t,e]:[e,t];for(let s of n)o.has(s)&&r++;return r/(t.size+e.size-r)}var Zv=/\b(?:cat|bat|head|tail|less|more|nl)\s+((?:-[^\s;|&]+\s+)*)([^\s|;&><'"`]{3,})/g;function xA(t){return/[*?$]/.test(t)||t.startsWith("-")||t==="EOF"||t==="<<"||!/^[\w./~@+-]+$/.test(t)?!1:t.includes("/")||/\.[A-Za-z0-9]{1,8}$/.test(t)}function bA(t,e){if(/read|open|cat|view|get_file/i.test(t??"")){let n=/"(?:file_path|filePath|path|file)"\s*:\s*"([^"]{3,})"/.exec(e);if(n)return[n[1]]}if(!/bash|shell|terminal|exec|run_command/i.test(t??""))return[];let r=new Set;Zv.lastIndex=0;for(let n of e.matchAll(Zv)){let o=n[2].replace(/\\+$/,"");xA(o)&&r.add(o)}return[...r]}function Dv(t,e){e=e??t.model;let r=e??(t.sourceFormat==="anthropic"?"claude":t.sourceFormat==="gemini"?"gemini":void 0),n=Nv(r),o=t.messages.map(y=>({msg:y,tokens:Math.round(At(y.text,r)*n.factor)+lp})),s=o.reduce((y,x)=>y+x.tokens,0),i={system:0,user:0,assistant:0,tool_calls:0,tool_results:0,other:0};for(let y of o)i[mA(y.msg)]+=y.tokens;let a=[];for(let y of o)y.msg.kind==="tool_result"&&y.tokens>2e3&&a.push({id:"large_tool_result",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool result at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} is ~${R(y.tokens)} tokens.`,suggestion:"Truncate or summarize large tool outputs before they enter history; keep only the fields the model actually used.",messages:[y.msg.index]});for(let y of o)y.msg.kind==="tool_call"&&y.tokens>2e3&&a.push({id:"large_tool_call",severity:y.tokens>8e3?"high":"warn",estSavings:Math.round(y.tokens*.8),message:`Tool call at message #${y.msg.index}${y.msg.toolName?` (${y.msg.toolName})`:""} carries ~${R(y.tokens)} tokens of arguments.`,suggestion:'Usually a whole file being written inline. Once it has run, replace the arguments with a reference ("wrote <path>") \u2014 or write files in smaller pieces so no single call carries the entire content.',messages:[y.msg.index]});let c=new Map;for(let y of o){if(y.msg.text.length<300)continue;let x=Mv(y.msg.text),$=c.get(x);$!==void 0?a.push({id:"duplicate_content",severity:"warn",estSavings:y.tokens-lp,message:`Message #${y.msg.index} duplicates the content of message #${$} (~${R(y.tokens)} tokens).`,suggestion:"Replace repeated content with a short reference to the first occurrence.",messages:[$,y.msg.index]}):c.set(x,y.msg.index)}{let y=o.filter(H=>H.msg.text.length>=300).sort((H,xe)=>xe.tokens-H.tokens).slice(0,150),x=y.map(H=>_A(H.msg.text)),$=x.map(H=>H.size),N=new Set(a.filter(H=>H.id==="duplicate_content").flatMap(H=>H.messages)),A=y.map((H,xe)=>xe),ae=H=>{for(;A[H]!==H;)H=A[H]=A[A[H]];return H},ce=y.map(()=>({sim:0,partnerTokens:0}));for(let H=0;H<y.length;H++)for(let xe=H+1;xe<y.length;xe++){let Mt=y[H],qr=y[xe];if(N.has(Mt.msg.index)&&N.has(qr.msg.index))continue;let Ls=Math.min($[H],$[xe]),Pn=Math.max($[H],$[xe]);if(Pn===0||Ls/Pn<jv)continue;let wt=vA(x[H],x[xe]);wt<jv||(A[ae(H)]=ae(xe),wt>ce[H].sim&&(ce[H]={sim:wt,partnerTokens:qr.tokens}),wt>ce[xe].sim&&(ce[xe]={sim:wt,partnerTokens:Mt.tokens}))}let Re=new Map;y.forEach((H,xe)=>{if(ce[xe].sim===0)return;let Mt=ae(xe);Re.set(Mt,[...Re.get(Mt)??[],xe])});for(let H of Re.values()){if(H.length<2)continue;H.sort(($t,Ur)=>y[$t].msg.index-y[Ur].msg.index);let xe=H.slice(1),Mt=xe.reduce(($t,Ur)=>$t+Math.round(Math.min(y[Ur].tokens,ce[Ur].partnerTokens)*ce[Ur].sim*.9),0),qr=H.map($t=>ce[$t].sim),Ls=Math.round(Math.min(...qr)*100),Pn=Math.round(Math.max(...qr)*100),wt=H.map($t=>y[$t].msg.index),sm=Ls===Pn?`~${Pn}%`:`${Ls}-${Pn}%`,ow=xe.reduce(($t,Ur)=>$t+y[Ur].tokens,0);a.push({id:"near_duplicate",severity:"warn",estSavings:Mt,message:H.length===2?`Messages #${wt[0]} and #${wt[1]} are ${sm} similar (~${R(Math.min(y[H[0]].tokens,y[H[1]].tokens))} tokens repeated with different framing).`:`${H.length} messages are ${sm} similar to each other (${wt.slice(0,6).map($t=>`#${$t}`).join(", ")}${wt.length>6?", \u2026":""}): ~${R(ow)} tokens in the ${xe.length} later copies repeat the first with different framing.`,suggestion:"Replace the later copies with a short reference to the first \u2014 repeats survive even when the surrounding words differ.",messages:wt})}}let u=new Map;for(let y of o){if(y.msg.kind!=="tool_call"||!y.msg.toolCallText)continue;let x=Mv(y.msg.toolCallText),$=u.get(x)??[];$.push(y.msg.index),u.set(x,$)}let l=y=>o.find(x=>x.msg.index>y&&x.msg.kind==="tool_result")?.msg;for(let[,y]of u){if(y.length<2)continue;let x=y.slice(1).filter((N,A)=>l(y[A])?.isError===!0).length,$=y.length-1-x;x>0&&a.push({id:"retried_tool_call",severity:x>=3?"warn":"info",estSavings:0,message:`The same tool call was retried ${x} time(s) after it failed (messages #${y.join(", #")}).`,suggestion:x>=3?"Three or more identical retries of a failing command is a loop. Each attempt keeps its error output in context; the answer is in the first error, not in the fourth attempt.":"A retry after a failure is normal once. The failed attempt's output stays in context though, so once the fix is understood the earlier error can go.",messages:y}),$>0&&a.push({id:"repeated_tool_call",severity:"info",estSavings:0,message:`The same tool call (with identical arguments) was repeated ${$} time(s) after it had already succeeded (messages #${y.join(", #")}).`,suggestion:"Repeating a call that already succeeded means the earlier result scrolled out of the model's attention \u2014 keep results in a compact recap instead of re-calling.",messages:y})}{let y=new Map;for(let x of o)if(!(x.msg.kind!=="tool_call"||!x.msg.toolCallText))for(let $ of bA(x.msg.toolName,x.msg.toolCallText))y.set($,[...y.get($)??[],x.msg.index]);for(let[x,$]of y){if($.length<3)continue;let N=o.filter(ae=>ae.msg.kind==="tool_result"&&$.some(ce=>ae.msg.index===ce+1)).reduce((ae,ce)=>ae+ce.tokens,0),A=Math.round(N*($.length-1)/$.length);a.push({id:"repeated_file_read",severity:A>4e3?"high":"warn",estSavings:A,message:`${x.split("/").pop()} was read ${$.length} times (messages #${$.join(", #")}), keeping ${$.length} copies in context.`,suggestion:"Re-read a file only after it changes; otherwise refer back to the copy already in context.",messages:$})}}for(let y of o)y.msg.kind!=="tool_result"||y.tokens<500||!/Traceback \(most recent call last\)|command not found|npm error|ERR!|\bexit code [1-9]|Exception in thread|FAILED|error TS\d+/i.test(y.msg.text)||a.push({id:"retained_error_output",severity:"warn",estSavings:Math.round(y.tokens*.85),message:`Message #${y.msg.index} holds ~${R(y.tokens)} tokens of failed tool output (errors, stack trace or non-zero exit).`,suggestion:"Keep the one line that identifies the failure and drop the rest \u2014 a full trace has no value once the fix is understood.",messages:[y.msg.index]});for(let y of o)yo(y.msg.text)&&a.push({id:"base64_blob",severity:"high",estSavings:Math.round(y.tokens*.9),message:`Message #${y.msg.index} contains a base64/binary blob (~${R(y.tokens)} tokens of mostly meaningless characters).`,suggestion:"Never put base64 in text content \u2014 use the provider's file/image APIs or replace with a file reference.",messages:[y.msg.index]});let d=t.messages.filter(y=>y.kind==="user"||y.kind==="assistant").length;if(d>40){let x=o.slice(0,Math.floor(o.length/2)).reduce(($,N)=>$+N.tokens,0);a.push({id:"long_history",severity:"warn",estSavings:Math.round(x*.7),message:`Conversation has ${d} turns; the older half holds ~${R(x)} tokens.`,suggestion:"Summarize the older half of the conversation into a compact recap and drop the raw turns (context-doctor optimize --strategy prune-history).",messages:[]})}s>0&&i.system/s>.25&&i.system>2e3&&a.push({id:"large_system_prompt",severity:"info",estSavings:0,message:`System prompt is ~${R(i.system)} tokens (${Math.round(i.system/s*100)}% of the context).`,suggestion:"A big system prompt is fine IF it is stable \u2014 put it first and use prompt caching (Anthropic: cache_control; OpenAI: automatic prefix caching) so you stop paying full price for it every call.",messages:[]}),(Mr(e)==="anthropic"||Mr(e)==="openai")&&a.push({id:"cache_ordering",severity:"info",estSavings:0,message:"Prompt caching only matches a byte-identical prefix.",suggestion:"Keep stable content (system prompt, tool definitions, reference docs) at the start and never interleave it with per-request content \u2014 a single changed byte early in the prompt invalidates the cache for everything after it.",messages:[]});let m=Za(e),p=m?s/m*100:void 0;p!==void 0&&p>70&&a.push({id:"near_window_limit",severity:p>90?"high":"warn",estSavings:0,message:`Context is at ~${p.toFixed(0)}% of ${e}'s window.`,suggestion:"Models degrade well before the hard limit (lost-in-the-middle). Compact now rather than when the request fails.",messages:[]});let f=o.map(y=>({index:y.msg.index,role:y.msg.role,kind:y.msg.kind,tokens:y.tokens,preview:gA(y.msg.text),toolName:y.msg.toolName})).sort((y,x)=>x.tokens-y.tokens).slice(0,5),g={high:0,warn:1,info:2};a.sort((y,x)=>g[y.severity]-g[x.severity]||x.estSavings-y.estSavings);let h=hA(a,s),_=go(e),v;if(_){let y=jr(s,_),x=jr(h,_);v={perCallUsd:y,per1kCallsUsd:y*1e3,savingsPerCallUsd:x,savingsPer1kCallsUsd:x*1e3,ttftSeconds:fp(s),ttftSavedSeconds:fp(h)}}return{totalTokens:s,model:e,contextWindow:m,usagePct:p,messageCount:t.messages.length,categories:i,largestMessages:f,findings:a,totalEstSavings:h,cost:v,sourceFormat:t.sourceFormat,calibration:n.samples>0?n:void 0,parseWarning:t.parseWarning}}import{createHash as wA}from"node:crypto";var Uv=10,qa={strategies:["dedupe","trim-tool-results","strip-base64"],keepRecent:6,maxToolResultTokens:300,trimBoundaryStep:Uv};function $A(t){if(t?.name==="Write"&&typeof t.input?.file_path=="string")return t.input.file_path;let e=t?.name==="Bash"?String(t.input?.command??""):"",r=/(?:cat|tee)\s*>+\s*([^\s<]+)\s*<</.exec(e);return r?r[1]:null}function kA(t,e,r){if(!r)return!1;for(let n=e+1;n<t.length;n++){let o=t[n]?.content;if(Array.isArray(o))for(let s of o){if(s?.type!=="tool_use")continue;let i=s.input?.file_path,a=s.name==="Bash"?String(s.input?.command??""):"";if(i===r||a.includes(r)){if(s.name==="Read"||/\b(cat|head|tail|sed|less)\b/.test(a))return!1;if(s.name==="Edit"||s.name==="MultiEdit")return!0}}}return!1}function Lv(t,e,r){let n=Math.round(e*up("",r)),o={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length>n?o[s]=i.slice(0,n)+`
66
+ [context-doctor: ${i.length-n} more chars trimmed \u2014 this call already ran]`:o[s]=i;return o}function yp(t,e,r=Uv){let n=t-e;return n<=0?0:n<r?n:Math.floor(n/r)*r}function SA(t){return wA("sha1").update(t.trim()).digest("hex")}function vo(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?e.text??"":e?.type==="tool_result"?vo(e.content):e?.type==="tool_use"?JSON.stringify(e.input??{}):"").join(`
67
+ `):JSON.stringify(t)}function _p(t,e){let r=t?.content,n=t?.role==="tool"?"tool_result":"text",o=(s,i)=>{let a=s.filter(d=>d?.type==="text"&&typeof d.text=="string");if(a.length===0)return s;let c=a.map(d=>d.text).join(`
68
+ `),u=e(c,i);if(u===c)return s;let l=!1;return s.map(d=>d?.type==="text"&&typeof d.text=="string"?l?null:(l=!0,{...d,text:u}):d).filter(d=>d!==null)};return typeof r=="string"?e(r,n):Array.isArray(r)?n==="tool_result"?o(r,n):r.map(s=>{if(s?.type==="text"&&typeof s.text=="string"){let i=e(s.text,"text");return i===s.text?s:{...s,text:i}}if(s?.type==="tool_result"){if(typeof s.content=="string"){let i=e(s.content,"tool_result");return i===s.content?s:{...s,content:i}}if(Array.isArray(s.content)){let i=o(s.content,"tool_result");return i===s.content?s:{...s,content:i}}}return s}):r}function vp(t){return typeof t=="string"?yo(t)?pp(t):t:Array.isArray(t)?t.map(vp):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,vp(r)])):t}function TA(t,e,r){let n=Math.round(e*up(t,r));if(t.length<=n)return t;let o=t.slice(0,n),s=t.length-n;return`${o}
69
+ \u2026[context-doctor: trimmed ${s} chars of stale tool output]`}function EA(t){let e=new Set;for(let r of t)if(Array.isArray(r?.content))for(let n of r.content)n?.type==="tool_use"&&n.id&&e.add(n.id);for(let r of t){if(!Array.isArray(r?.content))continue;let n=r.content.filter(o=>o?.type!=="tool_result"||o.tool_use_id&&e.has(o.tool_use_id));n.length!==r.content.length&&(r.content=n.length>0?n:[{type:"text",text:"[context-doctor: earlier tool result dropped with the pruned history]"}])}}function qv(t){return t?.role==="tool"?!0:Array.isArray(t?.content)?t.content.some(e=>e?.type==="tool_result"):!1}function Fv(t,e={}){let r={strategies:e.strategies??qa.strategies,keepRecent:e.keepRecent??qa.keepRecent,maxToolResultTokens:e.maxToolResultTokens??qa.maxToolResultTokens,trimBoundaryStep:e.trimBoundaryStep&&e.trimBoundaryStep>0?Math.floor(e.trimBoundaryStep):qa.trimBoundaryStep},n;try{n=JSON.parse(t)}catch{throw new Error("optimize requires a JSON conversation (message array, or object with a `messages` field)")}let o=Array.isArray(n)?n:n?.messages;if(!Array.isArray(o))throw Array.isArray(n?.contents)||typeof n?.input=="string"||Array.isArray(n?.input)?new Error(`optimize rewrites a \`messages\` array (Anthropic or OpenAI chat); this is ${Array.isArray(n?.contents)?"a Gemini `contents`":"an OpenAI Responses `input`"} request. Profile it with analyze (or profile_context); the autopilot proxy slims these requests live.`):new Error("No `messages` array found in input");for(let h=o.length-1;h>=0;h--)(!o[h]||typeof o[h]!="object")&&o.splice(h,1);let s=!Array.isArray(n)&&n?.system!=null||o.some(h=>Array.isArray(h?.content)&&h.content.some(_=>_?.type==="tool_use"||_?.type==="tool_result")),i=e.model??(!Array.isArray(n)&&typeof n?.model=="string"?n.model:void 0)??(s?"claude":void 0),a=h=>At(h,i),c=Array.isArray(n)?0:(n?.system!=null?a(typeof n.system=="string"?n.system:vo(n.system)):0)+(n?.tools!=null?a(JSON.stringify(n.tools)):0),u=h=>{let _=a(vo(h.content));for(let v of Array.isArray(h.tool_calls)?h.tool_calls:[]){let y=v?.function;y&&(_+=a(`${y.name??""} ${typeof y.arguments=="string"?y.arguments:JSON.stringify(y.arguments??{})}`))}return h.function_call&&(_+=a(`${h.function_call.name??""} ${h.function_call.arguments??""}`)),_},l=c+o.reduce((h,_)=>h+u(_),0),d=[];if(r.strategies.includes("strip-base64")&&o.forEach((h,_)=>{let v=vo(h.content);if(!yo(v))return;let y=a(v),x=_p(h,N=>yo(N)?pp(N):N);Array.isArray(x)&&(x=x.map(N=>N?.type==="tool_use"&&N.input!=null?{...N,input:vp(N.input)}:N));let $=y-a(vo(x));$>50&&(h.content=x,d.push({strategy:"strip-base64",messageIndex:_,tokensSaved:$,note:"Removed inline base64 data"}))}),r.strategies.includes("dedupe")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep),_=new Map;o.forEach((v,y)=>{let x=0,$,N=_p(v,A=>{if(A.length<300)return A;let ae=SA(A),ce=_.get(ae);if(ce===void 0)return _.set(ae,y),A;if(y>=h)return A;let Re=`[context-doctor: identical to message #${ce} \u2014 content removed]`;return x+=a(A)-a(Re),$??=ce,Re});x<=0||(v.content=N,d.push({strategy:"dedupe",messageIndex:y,tokensSaved:x,note:`Duplicate of message #${$}`}))})}if(r.strategies.includes("trim-tool-results")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h||!qv(_))return;let y=0,x=_p(_,($,N)=>{if(N!=="tool_result")return $;let A=a($);if(A<=r.maxToolResultTokens)return $;let ae=TA($,r.maxToolResultTokens,i),ce=a(ae);return ce>=A?$:(y+=A-ce,ae)});y<=0||(_.content=x,d.push({strategy:"trim-tool-results",messageIndex:v,tokensSaved:y,note:"Stale tool result truncated"}))})}if(r.strategies.includes("trim-tool-calls")){let h=yp(o.length,r.keepRecent,r.trimBoundaryStep);o.forEach((_,v)=>{if(v>=h)return;let y=0;if(Array.isArray(_.content))for(let x of _.content){if(x?.type!=="tool_use"||x.input==null||typeof x.input!="object"||kA(o,v,$A(x)))continue;let $=a(JSON.stringify(x.input));if($<=r.maxToolResultTokens)continue;let N=Lv(x.input,r.maxToolResultTokens,i),A=a(JSON.stringify(N));A>=$||(x.input=N,y+=$-A)}for(let x of _.tool_calls??[]){let $=x?.function?.arguments;if(typeof $!="string")continue;let N=a($);if(N<=r.maxToolResultTokens)continue;let A;try{A=JSON.parse($)}catch{continue}if(!A||typeof A!="object"||Array.isArray(A))continue;let ae=JSON.stringify(Lv(A,r.maxToolResultTokens,i)),ce=a(ae);ce>=N||(x.function.arguments=ae,y+=N-ce)}y>0&&d.push({strategy:"trim-tool-calls",messageIndex:v,tokensSaved:y,note:"Arguments of a completed tool call truncated"})})}let m,p=0;for(;p<o.length&&(o[p]?.role==="system"||o[p]?.role==="developer");)p++;let f=Math.max(2,r.keepRecent);if(r.strategies.includes("prune-history")&&o.length-p>f*2){let h=o.length-f;for(;h<o.length&&qv(o[h]);)h++;if(o.length-h>=2){EA(o.slice(h));let _=o.slice(p,h),v=_.reduce((x,$)=>x+u($),0);m=_.map((x,$)=>`[${p+$}:${x.role}] ${vo(x.content).replace(/\s+/g," ").slice(0,200)}`).join(`
70
+ `);let y={role:"user",content:`[context-doctor: ${_.length} earlier messages (~${v} tokens) pruned. Replace this stub with an LLM-written summary of those turns for best results.]`};o.splice(p,h-p,y),d.push({strategy:"prune-history",messageIndex:p,tokensSaved:v-a(y.content),note:`Pruned ${_.length} old messages`})}}let g=c+o.reduce((h,_)=>h+u(_),0);return{conversation:n,tokensBefore:l,tokensAfter:g,applied:d,prunedDigest:m}}var Hv={system:"System prompt",user:"User messages",assistant:"Assistant replies",tool_calls:"Tool calls",tool_results:"Tool results",other:"Other"},zA={high:"\u2716",warn:"\u25B2",info:"\u2139"};function RA(t,e=28){let r=Math.round(t*e);return"\u2588".repeat(r)+"\u2591".repeat(e-r)}function PA(t){return t.replace(/(?:[A-Za-z]:)?(?:~|\.{1,2})?(?:[\\/][\w.@+-]+)+|[\w.@~+-]+(?:[\\/][\w.@+-]+)+/g,"[path]").replace(/(?<![\w.@+-])[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]{0,9}(?![\w@+-]|\.\w)/g,"[file]")}function Bv(t,e={}){let r=[],n=t;if(r.push("CONTEXT DOCTOR \u2014 profile"),r.push("\u2550".repeat(56)),n.parseWarning&&(r.push(`\u26A0 ${n.parseWarning}${n.sourceFormat==="text"&&n.messageCount>0?" Profiled as raw text below, which is almost certainly not what you want.":""}`),r.push("")),r.push(`Total: ~${R(n.totalTokens)} tokens across ${n.messageCount} messages (${n.sourceFormat} format)`),n.calibration){let i=Math.round((n.calibration.factor-1)*100);r.push(` estimates calibrated ${i>=0?"+":""}${i}% from ${n.calibration.samples} exact count(s) you ran on this machine (analyze --exact)`)}if(n.model){let i=n.contextWindow?` of ${R(n.contextWindow)} window (${n.usagePct.toFixed(1)}%)`:" (unknown window size)";r.push(`Model: ${n.model}${i}`)}n.cost&&r.push(`Cost: ~${Kt(n.cost.perCallUsd)} input per call \xB7 ~${Kt(n.cost.per1kCallsUsd)} per 1k calls \xB7 ~${n.cost.ttftSeconds.toFixed(1)}s of latency per call (estimates)`),r.push(""),r.push("Where the tokens go"),r.push("\u2500".repeat(56));let o=Object.entries(n.categories).filter(([,i])=>i>0).sort((i,a)=>a[1]-i[1]),s=Math.max(...o.map(([i])=>Hv[i].length));for(let[i,a]of o){let c=n.totalTokens>0?a/n.totalTokens:0;r.push(`${Hv[i].padEnd(s)} ${RA(c)} ${String(Math.round(c*100)).padStart(3)}% ~${R(a)}`)}r.push(""),r.push("Largest messages"),r.push("\u2500".repeat(56));for(let i of n.largestMessages){let a=i.toolName?`${i.kind}:${i.toolName}`:i.kind,c=e.redact?"[redacted]":i.preview;r.push(` #${i.index} [${a}] ~${R(i.tokens)} ${c}`)}if(r.push(""),n.findings.length>0){r.push(`Findings (${n.findings.length})`),r.push("\u2500".repeat(56));let i=3,a=new Map,c=new Map;for(let u of n.findings){let l=a.get(u.id)??0;if(l>=i){let p=c.get(u.id)??{count:0,savings:0};c.set(u.id,{count:p.count+1,savings:p.savings+u.estSavings});continue}a.set(u.id,l+1);let d=u.estSavings>0?` [save ~${R(u.estSavings)}]`:"";r.push(`${zA[u.severity]} ${e.redact?PA(u.message):u.message}${d}`),r.push(` \u2192 ${u.suggestion}`);let m=c.get(u.id);l+1===i&&m===void 0&&c.set(u.id,{count:0,savings:0})}for(let[u,l]of c){if(l.count===0)continue;let d=Math.min(l.savings,n.totalEstSavings),m=d>0?`, up to ~${R(d)} more recoverable`:"";r.push(` \u2026 and ${l.count} more of the same kind (${u})${m}. Use --json for the full list.`)}if(r.push(""),n.totalEstSavings>0){let u=n.totalTokens>0?Math.round(n.totalEstSavings/n.totalTokens*100):0,l=`Potential recovery: ~${R(n.totalEstSavings)} tokens (~${u}% of context)`;n.cost&&n.cost.savingsPerCallUsd>0&&(l+=` \u2248 ${Kt(n.cost.savingsPer1kCallsUsd)} per 1k calls, ${n.cost.ttftSavedSeconds.toFixed(1)}s faster per call`),r.push(l),r.push("Run `context-doctor optimize <file>` to apply the safe fixes automatically.")}}else r.push("No issues found \u2014 this context is in good shape.");return r.join(`
71
+ `)}var IA=2060,CA={code:42,tool_result:56,paste:56,text:80,base64:76,image:0},AA=6.3,OA={paste:2400,code:2400,tool_result:2400,text:900,base64:12e3,image:0},NA=1500,Vv=2e3,MA=30,xp=400,jA=1e4,ZA=6;function DA(t,e){let r=Cs[Mr(e)];return t==="code"||t==="tool_result"||t==="base64"?r.code:r.prose}function LA(t,e){if(t.kind==="image")return t.approx_tokens&&t.approx_tokens>0?Math.round(t.approx_tokens):NA;if(t.approx_tokens&&t.approx_tokens>0)return Math.round(t.approx_tokens);let r=t.approx_chars&&t.approx_chars>0?t.approx_chars:t.approx_lines&&t.approx_lines>0?t.approx_lines*CA[t.kind]:t.approx_words&&t.approx_words>0?t.approx_words*AA:OA[t.kind];return Math.round(r/DA(t.kind,e))}function bp(t){return Math.round(IA/Cs[Mr(t)].prose)}var Jv=60;function qA(t){let e=String(t??"").replace(/\s+/g," ").trim()||"unnamed block";return e.length>Jv?e.slice(0,Jv-1)+"\u2026":e}function UA(t){let e=Math.max(0,Math.floor(t.turns||0)),r=(Array.isArray(t.blocks)?t.blocks:[]).map(_=>({..._,label:qA(_?.label)})),n=bp(t.model),o=e*n,s=r.map(_=>({block:_,tokens:LA(_,t.model),copies:Math.max(1,Math.floor(_.repeated??1))})),i=s.reduce((_,v)=>_+v.tokens*v.copies,0),a=o+i,c=[];for(let{block:_,tokens:v,copies:y}of s){if(y>1&&c.push({id:"duplicate_block",severity:"warn",estSavings:v*(y-1),message:`"${_.label}" appears ${y} times (~${R(v)} each).`,action:`Refer to "${_.label}" by name from now on; never re-quote it.`}),_.kind==="base64"){c.push({id:"base64_blob",severity:"high",estSavings:Math.max(0,v-50),message:`"${_.label}" is inline base64 (~${R(v)}), which the model cannot read anyway.`,action:`Drop it: describe "${_.label}" in one line and ask the user to attach it as a file if needed.`});continue}if(_.kind!=="image"&&v>=Vv){let x=_.stale?Math.max(0,v-100):Math.round(v*.7);c.push({id:"large_block",severity:v>=4*Vv?"high":"warn",estSavings:x,message:`"${_.label}" (turn ${_.turn}, ${_.kind}) is ~${R(v)}${_.stale?" and already acted on":""}.`,action:_.stale?`Replace "${_.label}" with a one-line note of what it was and what came of it.`:`Summarize "${_.label}" into the points still needed (facts, identifiers, decisions) and work from the summary.`})}}let u=s.filter(_=>_.block.kind==="image");if(u.length>=3){let _=u.reduce((v,y)=>v+y.tokens*y.copies,0);c.push({id:"many_images",severity:"info",estSavings:0,message:`${u.length} images (~${R(_)}) ride along on every turn.`,action:"Once an image has been read, describe what it showed in a sentence so it need not be looked at again; new chats should get only the images still needed."})}if(e>=MA){let _=ZA*n+xp;c.push({id:"long_history",severity:a>1e5?"high":"warn",estSavings:Math.max(0,a-_),message:`${e} turns: every new message re-reads ~${R(a)}.`,action:`Offer a handoff once: with the user's agreement, write a \u2264${xp}-token brief (goal, decisions, current state, open items, key identifiers) and call save_handoff, or the user picks the \`handoff\` prompt. A new chat re-reads ~${R(_)} of conversation instead, plus the app's own system prompt, which every chat carries.`})}let l=Za(t.model),d=l?Math.round(a/l*100):void 0;d!==void 0&&d>=70&&c.push({id:"near_window_limit",severity:"high",estSavings:0,message:`~${d}% of the ${R(l)} window. Quality drops and the app may start dropping early turns.`,action:"Do the handoff now rather than at the next problem."});let m={high:0,warn:1,info:2};c.sort((_,v)=>m[_.severity]-m[v.severity]||v.estSavings-_.estSavings);let p=c.find(_=>_.id==="long_history")?.estSavings??0,f=c.filter(_=>_.id!=="long_history").reduce((_,v)=>_+v.estSavings,0),g=Math.min(a,Math.max(p,f)),h=go(t.model);return{totalTokens:a,baselineTokens:o,blockTokens:i,turns:e,model:t.model,contextWindow:l,usagePct:d,findings:c,totalEstSavings:g,perTurnUsd:h?jr(a,h):void 0,perTurnCachedUsd:h?a/1e6*h.cacheReadPerM:void 0}}function Wv(t){let e=[],r=t.usagePct!==void 0?` (~${t.usagePct}% of ${R(t.contextWindow)})`:"";return e.push(`Context estimate from sketch: ~${R(t.totalTokens)} tokens${r}, ${t.turns} turns.`),e.push(` ${R(t.baselineTokens)} plain conversation + ${R(t.blockTokens)} in pastes, tool output and images. Estimate, usually within \xB120%.`),t.perTurnUsd!==void 0?e.push(` Re-read on every turn: ${Kt(t.perTurnUsd)} at list price, ${Kt(t.perTurnCachedUsd)} when cached. On a subscription this is what spends the usage limit.`):e.push(" Re-read on every turn. On a subscription this is what spends the usage limit."),t.findings.length===0?(e.push("No findings: nothing large, repeated, or stale in the sketch. Keep going."),e.join(`
72
+ `)):(e.push(""),e.push(`Findings (recoverable ~${R(t.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`),t.findings.forEach((o,s)=>{let i=o.estSavings>0?` [~${R(o.estSavings)}]`:"";e.push(`${s+1}. ${o.severity.toUpperCase()}${i} ${o.message}`),e.push(` \u2192 ${o.action}`)}),e.push(""),e.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat."),!t.findings.some(o=>o.id==="long_history")&&t.totalEstSavings>=jA&&e.push(`To recover the ~${R(t.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a \u2264${xp}-token brief plus the blocks that must stay exact); a new chat starts from that.`),e.join(`
73
+ `))}function Kv(t,{record:e=!0}={}){let r=UA(t);return e&&La({ev:"check",src:"mcp",tok:r.totalTokens,warn:r.findings.some(n=>n.severity!=="info"),model:t.model}),r}import{spawnSync as vx}from"node:child_process";import{existsSync as xx,lstatSync as cO,readdirSync as uO,readFileSync as lO,realpathSync as zp,statSync as dO}from"node:fs";import{homedir as bx}from"node:os";import{basename as Rp,extname as Wa,isAbsolute as fO,join as pe,relative as wx,resolve as pO,sep as mO}from"node:path";import{execFile as FA,spawnSync as Gv}from"node:child_process";import{existsSync as Xv,mkdtempSync as Yv,readFileSync as $p,rmSync as Qv}from"node:fs";import{tmpdir as ex}from"node:os";import{dirname as tx,extname as rx,join as Ua,resolve as HA}from"node:path";var Fa=new Set([".pdf",".docx",".doc",".rtf",".odt",".pptx"]),nx={encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024};function As(t,e){try{let r=Gv(t,e,nx);return r.status===0&&typeof r.stdout=="string"&&r.stdout.trim()?r.stdout:void 0}catch{return}}var ox=["-convert","txt","-noload","-nostore","-stdout"],sx='ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';function BA(t){let e=As("pdftotext",["-enc","UTF-8",t,"-"])??As("pdftotext",[t,"-"]);if(e)return e;let r=Ua(Yv(Ua(ex(),"cd-pdf-")),"out.txt");try{Gv("pdftotext",[t,r],nx);let n=Xv(r)?$p(r,"utf8"):"";return n.trim()?n:void 0}catch{return}finally{Qv(tx(r),{recursive:!0,force:!0})}}function VA(t,e){let r=As("unzip",["-p",t,...e]);return r?ix(r):void 0}function ix(t){return t.replace(/<\/(w:p|a:p|text:p|text:h)>/g,`
74
74
 
75
75
  `).replace(/<(w:tab|w:br)\/>/g," ").replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&").replace(/\n{3,}/g,`
76
76
 
77
- `).trim()}function 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 ax(t){return HA(t)}function cx(t){let e=ax(t),r=rx(e).toLowerCase(),n=process.platform==="darwin",o;if(r===".pdf"){if(o=BA(e)?.replace(/\f/g,`
78
78
 
79
- `),!n&&r&&(n=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
+ `),!o&&n&&(o=As("osascript",["-l","JavaScript","-e",sx,e])),!o)return{error:n?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}else{if(n&&r!==".pptx"&&(o=As("textutil",[...ox,e])),!o){let s=r===".docx"?["word/document.xml"]:r===".pptx"?["ppt/slides/*.xml"]:r===".odt"?["content.xml"]:[];s.length&&(o=VA(e,s))}if(!o)return{error:n?"unreadable document":`needs unzip${r===".doc"||r===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}return{text:o}}var Os=2e4,lt=()=>performance.now();function JA(t){return Math.min(t,3e4,Math.max(2e3,t/2))}function wp(t,e,r){let n=Math.ceil(r-lt());if(n<=0)return Promise.resolve({timedOut:!0});let o=Math.ceil(JA(n));return new Promise(s=>{let i=!1,a=l=>{i||(i=!0,clearTimeout(u),s(l))},c,u=setTimeout(()=>{c?.kill("SIGKILL"),a({timedOut:lt()>=r-50})},o);try{c=FA(t,e,{encoding:"utf8",timeout:o,killSignal:"SIGKILL",maxBuffer:64*1024*1024,windowsHide:!0},(l,d)=>{if(l)return a({timedOut:lt()>=r-50});a({out:typeof d=="string"&&d.trim()?d:void 0,timedOut:!1})}),c.on("error",()=>a({timedOut:!1})),c.stdin?.on("error",()=>{}),c.stdin?.end()}catch{a({timedOut:!1})}})}async function Ha(t,e=lt()+Os){let r=ax(t),n=rx(r).toLowerCase(),o=process.platform==="darwin",s,i=!1,a=async(u,l)=>{if(s||i)return;let d=await wp(u,l,e);d.timedOut?i=!0:s=d.out},c=()=>({error:"not read: the time allowed for reading documents in this call ran out"});if(n===".pdf"){if(await a("pdftotext",["-enc","UTF-8",r,"-"]),await a("pdftotext",[r,"-"]),!s&&!i){let u=Ua(Yv(Ua(ex(),"cd-pdf-")),"out.txt");try{(await wp("pdftotext",[r,u],e)).timedOut?i=!0:Xv(u)&&(s=$p(u,"utf8").trim()?$p(u,"utf8"):void 0)}finally{Qv(tx(u),{recursive:!0,force:!0})}}return s=s?.replace(/\f/g,`
80
80
 
81
- `),!o&&n&&await i("osascript",["-l","JavaScript","-e",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
+ `),!s&&o&&await a("osascript",["-l","JavaScript","-e",sx,r]),s?{text:s}:i?c():{error:o?"no text layer (scanned PDF?) or unreadable":"needs pdftotext (install poppler-utils), or the PDF has no text layer"}}if(o&&n!==".pptx"&&await a("textutil",[...ox,r]),!s&&!i){let u=n===".docx"?["word/document.xml"]:n===".pptx"?["ppt/slides/*.xml"]:n===".odt"?["content.xml"]:[];if(u.length){let l=await wp("unzip",["-p",r,...u],e);l.timedOut?i=!0:l.out&&(s=ix(l.out))}}return s?{text:s}:i?c():{error:o?"unreadable document":`needs unzip${n===".doc"||n===".rtf"?" (and .doc/.rtf need macOS textutil; save as .docx)":""}`}}import{homedir as ux}from"node:os";import{join as WA,resolve as KA}from"node:path";function Sn(t,e=process.env){if(t===void 0||t===ux()){let r=e.CODEX_HOME?.trim();if(r)return KA(r)}return WA(t??ux(),".codex")}var hO=4e3,gO=400,yO="claude",_O=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".h",".cc",".cpp",".hpp",".cs",".php",".scala",".sh",".bash",".zsh",".sql",".lua",".dart",".vue",".svelte"]),vO=new Set([".md",".mdx",".markdown",".rst",".adoc"]);function xO(t,e){let r=Wa(t).toLowerCase();return vO.has(r)?"markdown":_O.has(r)?"code":/^#{1,6}\s+\S/m.test(e)&&!/^#!/.test(e)?"markdown":"prose"}var bO=/^(?![\s})\]]|$)/,gx=/^(\/\*\*?|\*\/?|\/\/|#(?!include|define|!)|"""|\'\'\'|--|@\w+)/;function wO(t,e){let r=[],n=[],o="",s=0,i=!1,a=!1,c=(u,l)=>{u>s&&t.slice(s,u).some(d=>d.trim())&&r.push({start:s,end:u,heading:o,hard:i}),s=u,i=l};for(let u=0;u<t.length;u++){let l=t[u];if(e==="markdown"){/^\s*(```|~~~)/.test(l)&&(a=!a);let d=!a&&/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l);if(d){c(u,!0);let m=d[1].length;n.length=m-1,n[m-1]=d[2],o=n.filter(Boolean).join(" > ");continue}!a&&!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}else e==="code"?u>0&&!t[u-1].trim()&&l.trim()&&bO.test(l)&&c(u,!1):!l.trim()&&u+1<t.length&&t[u+1].trim()&&c(u+1,!1)}if(c(t.length,!1),e!=="markdown")for(let u of r){let l=t.slice(u.start,u.end).map(p=>p.trim()).filter(Boolean),d=l.map(p=>p.replace(gx,"").trim()).find(Boolean),m=e==="code"&&(l.find(p=>!gx.test(p))||d)||l[0]||"";u.heading=m.slice(0,80)}return r}var $O=t=>t>=55296&&t<=56319,kO=t=>t>=56320&&t<=57343;function $x(t,e={}){let r=Math.max(50,e.maxChunkTokens??gO),n=e.model??yO,o=xO(t.name,t.text),s=[],i=[],a=Math.floor(r*2.4);t.text.replace(/\r\n?/g,`
82
82
  `).split(`
83
- `).forEach((m,p)=>{for(;m.length>a;){let f=m.lastIndexOf(" ",a),g=f>a/2?f+1:a;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;$O(m.charCodeAt(g-1))&&kO(m.charCodeAt(g))&&g--,s.push(m.slice(0,g)),i.push(p+1),m=m.slice(g)}s.push(m),i.push(p+1)});let c=[0];for(let m of s)c.push(c[c.length-1]+At(m+`
84
+ `,n));let u=(m,p)=>c[p]-c[m],l=[];for(let m of wO(s,o)){if(u(m.start,m.end)<=r){l.push(m);continue}let p=m.start;for(let f=m.start+1;f<=m.end;f++)if(f===m.end||u(p,f+1)>r){let g=p===m.start;l.push({start:p,end:f,heading:g?m.heading:`${m.heading} (cont.)`,hard:g&&m.hard}),p=f}}let d=[];for(let m of l){let p=d[d.length-1];p&&!m.hard&&p.heading===m.heading&&u(p.start,m.end)<=r||p&&!m.hard&&o!=="markdown"&&u(p.start,m.end)<=r?p.end=m.end:d.push({...m})}return d.map((m,p)=>{let f=m.start,g=m.end;for(;f<g&&!s[f].trim();)f++;for(;g>f&&!s[g-1].trim();)g--;let h=s.slice(f,g).join(`
85
+ `);return{id:`${t.name}#${p+1}`,source:t.name,startLine:i[f]??f+1,endLine:i[g-1]??g,heading:m.heading,text:h,tokens:At(h,n),score:0}})}var SO=new Set("a an and are as at be but by can do does for from has have how i if in into is it its of on or our so that the their them then there these they this to was we were what when where which who why will with you your about should would could not no yes all any my me get set use using used".split(" "));function Va(t){let e=[],r=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u);for(let n of r)n.length<2||SO.has(n)||(n.length>4&&n.endsWith("ies")?n=n.slice(0,-3)+"y":n.length>3&&n.endsWith("s")&&!n.endsWith("ss")&&(n=n.slice(0,-1)),e.push(n));return e}function kx(t,e){let r=[...new Set(Va(e))];if(r.length===0||t.length===0)return;let n=t.map(i=>{let a=[...Va(i.text),...Va(i.heading),...Va(i.heading)],c=new Map;for(let u of a)c.set(u,(c.get(u)??0)+1);return{len:a.length,tf:c}}),o=n.reduce((i,a)=>i+a.len,0)/n.length||1,s=n.length;for(let i of r){let a=n.filter(u=>u.tf.has(i)).length;if(a===0)continue;let c=Math.log(1+(s-a+.5)/(a+.5));n.forEach((u,l)=>{let d=u.tf.get(i)??0;d&&(t[l].score+=c*(d*2.2/(d+1.2*(1-.75+.75*u.len/o))))})}}function Sx(t,e={}){let r=t.map(o=>$x(o,e)),n=e.query?.trim()||void 0;return n&&kx(r.flat(),n),Ex(t,r,n,e)}async function Tx(t,e={}){let r=t.map(s=>$x(s,e)),n=e.query?.trim()||void 0,o;if(n&&(kx(r.flat(),n),e.semantic)){let{semanticRerank:s}=await Promise.resolve().then(()=>(hx(),mx));o=(await s(r.flat(),n,{model:typeof e.semantic=="string"?e.semantic:void 0})).note}return{...Ex(t,r,n,e),semanticNote:o}}function Ex(t,e,r,n){let o=Math.max(1,n.budget??hO),s=e.flat(),i=[],a=[],c=[],u=0,l=(p,f)=>{if(!i.includes(p)){if(u+p.tokens>o){c.some(g=>g.id===p.id)||c.push({id:p.id,tokens:p.tokens,requested:f});return}i.push(p),u+=p.tokens}},d="outline";if(n.ids?.length){d="ids";let p=new Map(s.map(f=>[f.id,f]));for(let f of n.ids){let g=p.get(f);g?l(g,!0):a.push(f)}}if(r){d==="outline"&&(d="query");for(let p of[...s].filter(f=>f.score>0).sort((f,g)=>g.score-f.score))l(p,!1)}let m=new Map(s.map((p,f)=>[p,f]));return i.sort((p,f)=>m.get(p)-m.get(f)),{mode:d,query:r,budget:o,totalTokens:s.reduce((p,f)=>p+f.tokens,0),packedTokens:u,selected:i,chunks:s,missingIds:a,unfit:c,sources:t.map((p,f)=>({name:p.name,tokens:e[f].reduce((g,h)=>g+h.tokens,0),chunks:e[f].length,selected:e[f].filter(g=>i.includes(g)).length}))}}function Tp(t,e){let r=t.slice(0,e).map(n=>` ${n.id} L${n.startLine}-${n.endLine} ~${R(n.tokens)} ${n.heading}`);return t.length>e&&r.push(` \u2026 ${t.length-e} more`),r}function zx(t,{outlineLimit:e=60}={}){let r=[],n=t.totalTokens>0?Math.round(t.packedTokens/t.totalTokens*100):0,o=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`;if(t.mode==="outline")return r.push(`OUTLINE of ${o}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks. Nothing packed: pass a query, or chunk ids from this list.`),r.push(...Tp(t.chunks,e)),r.join(`
86
+ `);r.push(`PACKED ~${R(t.packedTokens)} of ~${R(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${R(t.budget)}.`),t.missingIds.length&&r.push(`Unknown ids: ${t.missingIds.join(", ")}.`),t.semanticNote&&r.push(`(${t.semanticNote})`);let s=(t.unfit??[]).filter(a=>a.requested);if(t.selected.length>0&&s.length>0&&r.push(`Did not fit the budget of ${R(t.budget)}: ${s.map(a=>`${a.id} (~${R(a.tokens)})`).join(", ")}. Ask for it alone or with a larger budget (--max-tokens; MCP max_tokens).`),t.selected.length===0&&(t.unfit??[]).length>0){let a=t.unfit[0],c=t.chunks.find(u=>u.id===a.id);return r.push(`Nothing fit the budget of ${R(t.budget)} tokens: ${a.requested?"the requested chunk":"the best match"} ${a.id}${c?.heading?` (${c.heading})`:""} is ~${R(a.tokens)} tokens. Raise the budget to at least ${a.tokens} (--max-tokens; MCP max_tokens), or use smaller chunks (--chunk-tokens).`),r.push(...Tp(t.chunks,e)),r.join(`
87
+ `)}if(t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...Tp(t.chunks,e)),r.join(`
88
+ `);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 TO=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),Ja={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024},Rx=["-c","core.fsmonitor=false"];function EO(t){try{let e=vx("git",[...Rx,"-C",t,"ls-files","-z","--cached","--others","--exclude-standard"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status!==0||typeof e.stdout!="string"?void 0:e.stdout.split("\0").filter(r=>r&&xx(pe(t,r))).sort()}catch{return}}function zO(t){let e=vx("git",[...Rx,"-C",t,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status===0&&typeof e.stdout=="string"&&e.stdout.length>0}function Px(t,e){let r=wx(t,e);return r===""||r!==".."&&!r.startsWith(".."+mO)&&!fO(r)}var RO=new Set([".npmrc",".pypirc",".netrc","_netrc",".git-credentials",".pgpass",".htpasswd",".vault-token",".credentials.json","oauth_creds.json","credentials.tfrc.json"]),PO=[[".codex",["auth.json"]],[".cargo",["credentials","credentials.toml"]],[".gem",["credentials"]]],IO=new Set([".pem",".key",".p12",".pfx",".keystore",".jks"]);function yx(t){let e=Rp(t),r=e.toLowerCase();if(r===".env"||r.startsWith(".env."))return"an .env file";if(RO.has(r))return`a credentials file (${e})`;if(/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(r)||/^id_(rsa|dsa|ecdsa|ed25519)/.test(r)&&!r.endsWith(".pub"))return"a private SSH key";if(IO.has(Wa(r)))return`a key or certificate store (${Wa(r)})`;let n=t.split(/[\\/]+/),o=(n[n.length-2]??"").toLowerCase();if(r==="credentials"&&o===".aws")return"AWS credentials";if(PO.some(([s,i])=>s===o&&i.includes(r)))return`a credentials file (${o}/${e})`}function CO(){let t=bx(),e=[...[".ssh",".aws",".gnupg",".kube",".docker",".azure",pe(".config","gcloud"),pe(".config","gh"),pe(".config","github-copilot"),pe("Library","Keychains"),".password-store"].map(r=>pe(t,r)),pe(ur(),".credentials.json"),pe(Sn(),"auth.json"),"/etc/shadow","/etc/gshadow","/etc/sudoers","/etc/master.passwd","/etc/ssh"];return[...new Set([...e,...e.map(Tn)])]}function AO(){let t=bx(),e=[Iv(),pe(t,".claude.json"),...[ur(),pe(t,".claude")].flatMap(r=>[pe(r,"settings.json"),pe(r,"settings.local.json")]),pe(t,".cursor","mcp.json"),pe(Sn(),"config.toml"),pe(t,".codex","config.toml"),pe(t,".gemini","settings.json"),pe(t,".gemini","config","mcp_config.json"),pe(t,".gemini","antigravity","mcp_config.json"),pe(t,"Library","Application Support","Claude","claude_desktop_config.json"),pe(process.env.APPDATA||pe(t,"AppData","Roaming"),"Claude","claude_desktop_config.json"),pe(t,".config","Claude","claude_desktop_config.json"),pe(process.env.COPILOT_HOME||pe(t,".copilot"),"mcp-config.json"),pe(t,".copilot","mcp-config.json")];return[...new Set([...e,...e.map(Tn)])]}function Tn(t){for(let e of[zp.native,zp])try{return e(t)}catch{}return pO(t)}function _x(t,e){let r=process.platform==="darwin"||process.platform==="win32"?n=>n.toLowerCase():n=>n;return e.find(n=>Px(r(n),r(t)))}function Ep(t){let e=t?.code;return e==="ENOENT"?"not found":e==="EACCES"||e==="EPERM"?"permission denied":e==="ENOTDIR"?"not a directory":e==="EISDIR"?"is a directory":e==="ELOOP"?"too many symlinks":e?`unreadable (${e})`:`unreadable (${t?.message??t})`}function OO(t,e=process.cwd()){let r=typeof e=="string"?{cwd:e}:e,n=r.cwd??process.cwd(),o=r.includeSecrets===!0,s=r.secretsHint??"",i=o?[]:CO(),a=o?[]:AO(),c=[],u=[],l=0,d=new Set,m="",p=0,f=!1,g=(h,_)=>{if(c.length>=Ja.files){(_||u.length<20)&&u.push(`${h}: over ${Ja.files} files`);return}let v;try{v=_?dO(h):cO(h)}catch(A){u.push(`${h}: ${Ep(A)}`);return}if(v.isSymbolicLink()){let A;try{A=Tn(zp(h))}catch{return}Px(m,A)||u.push(`${h}: symlink pointing outside the folder (not followed)`);return}if(i.length>0){let A=Tn(h),ae=_x(A,i);if(ae){_&&u.push(`${h}: refused, ${ae} holds credentials${s}`);return}let ce=_x(A,a);if(ce){u.push(`${h}: refused, ${ce} can hold API keys (an MCP server's env)${s}`);return}}if(v.isDirectory()){let A=Rp(h);if(!_&&TO.has(A))return;if(!_&&A.startsWith(".")){p++;return}let ae=_?EO(h):void 0;if(_&&(f=ae!==void 0),ae){ae.length===0&&zO(h)&&u.push(`${h}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let Re of ae)g(pe(h,Re),!1);return}let ce;try{ce=uO(h).sort()}catch(Re){u.push(`${h}: ${Ep(Re)}`);return}for(let Re of ce)g(pe(h,Re),!1);return}if(!v.isFile()){_&&u.push(`${h}: not a regular file`);return}if(!o){let A=yx(h)??yx(Tn(h));if(A){u.push(`${h}: ${A}, likely holding secrets; not packed${s}`);return}}if(!_&&Rp(h).startsWith(".")&&!f){p++;return}let y=Tn(h);if(d.has(y))return;if(v.size>Ja.fileBytes||l+v.size>Ja.totalBytes){u.push(`${h}: too large (${Math.round(v.size/1024)} KB)`);return}let x=wx(n,h),$=x&&!x.startsWith("..")?x:h;if(Fa.has(Wa(h).toLowerCase())){if(r.defer){l+=v.size,d.add(y),c.push({name:$,text:""}),r.defer.push({slot:c.length-1,path:h});return}let A=cx(h);"error"in A?u.push(`${h}: ${A.error}`):(l+=v.size,d.add(y),c.push({name:$,text:A.text}));return}let N;try{N=lO(h)}catch(A){u.push(`${h}: ${Ep(A)}`);return}if(N.subarray(0,8e3).includes(0)){_&&u.push(`${h}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}l+=v.size,d.add(y),c.push({name:$,text:N.toString("utf8")})};for(let h of t){if(!xx(h)){u.push(`${h}: not found`);continue}m=Tn(h),p=0,f=!1,g(h,!0),p>0&&u.push(`${h}: ${p} hidden file(s) or folder(s) not read (name one to pack it)`)}return{sources:c,skipped:u}}async function Ix(t,e={}){let r=[],{sources:n,skipped:o}=OO(t,{...e,defer:r}),s=lt()+(e.budgetMs??Os),i=new Set;for(let a of r){let c=await Ha(a.path,s);"error"in c?(o.push(`${a.path}: ${c.error}`),i.add(a.slot)):n[a.slot].text=c.text}return{sources:n.filter((a,c)=>!i.has(c)),skipped:o}}var Cx=`Context hygiene rules (always on):
90
90
  1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a \`sketch\`. Act on its top finding. Do not estimate token counts yourself.
91
91
  2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
92
92
  3. Summarize any paste or tool result over ~2k tokens into the points you need.
93
93
  4. Refer to earlier content by name; never re-quote it or inline base64.
94
94
  5. For a big file you won't edit, call pack_context with the question; don't read it whole.
95
- 6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`;var 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 NO=["openai/session","openai/subject"];function Ax(t,e=process.env){let r=e.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();return r==="full"||r==="compact"?r:t&&typeof t=="object"&&NO.some(n=>typeof t[n]=="string")?"compact":"full"}var xo=t=>Math.round(t);function Ox(t,e){let r=t.findings[0],n=t.totalTokens>0?Math.round(t.totalEstSavings/t.totalTokens*100):0,o=[`~${R(t.totalTokens)} tokens in ${t.messageCount} messages (${t.sourceFormat})${t.usagePct!==void 0?`, ${t.usagePct.toFixed(0)}% of the window`:""}; ~${R(t.totalEstSavings)} recoverable (${n}%).`];t.parseWarning&&o.unshift(`\u26A0 ${t.parseWarning}`),o.push(r?"Act on #1 (first in structuredContent.findings).":"No findings.");let s=Object.fromEntries(Object.entries(t.categories).filter(([,a])=>a>0).sort((a,c)=>c[1]-a[1]).map(([a,c])=>[a,xo(c)])),i={total_tokens:xo(t.totalTokens),messages:t.messageCount,recoverable_tokens:xo(t.totalEstSavings),by_category:s,findings:t.findings.slice(0,6).map(a=>`${a.severity}${a.estSavings>0?` ~${R(a.estSavings)}`:""}: ${a.message} \u2192 ${a.suggestion}`)};return t.findings.length>6&&(i.more_findings=t.findings.length-6),t.model&&(i.model=t.model),t.usagePct!==void 0&&(i.window_pct=Number(t.usagePct.toFixed(1))),t.cost&&(i.usd_per_call=Number(t.cost.perCallUsd.toFixed(4))),{text:o.join(`
96
+ `),structured:i,meta:{"context-doctor/report":e,"context-doctor/largest":t.largestMessages.map(a=>({index:a.index,kind:a.kind,tokens:xo(a.tokens),preview:a.preview}))}}}function Nx(t,e){let[r,...n]=t.findings,o=[`~${R(t.totalTokens)} tokens, ${t.turns} turns${t.usagePct!==void 0?`, ~${t.usagePct}% of the window`:""} (estimate); ~${R(t.totalEstSavings)} recoverable, only in a new chat.`];r?(o.push(`Act on #1 now: ${r.message} \u2192 ${r.action}`),o.push("This chat's history cannot be edited: what is already here comes back only in a new chat (save_handoff).")):o.push("No findings. Keep going.");let s={total_tokens:t.totalTokens,recoverable_tokens:t.totalEstSavings,recoverable_by:"a new chat (handoff)"};return n.length&&(s.other_findings=n.map(i=>`${i.severity}${i.estSavings>0?` ~${R(i.estSavings)}`:""}: ${i.message}`)),t.usagePct!==void 0&&(s.window_pct=t.usagePct),t.perTurnUsd!==void 0&&(s.usd_per_turn=Number(t.perTurnUsd.toFixed(4))),{text:o.join(`
97
+ `),structured:s,meta:{"context-doctor/report":e}}}function MO(t,e){let r=n=>n.slice(n.lastIndexOf("#")+1);return t===e?`#${r(t)}`:`#${r(t)}-${r(e)}`}function jO(t){let e=t.replace(/\s*\(cont\.\)$/,""),r=e.split(" > ");return r[r.length-1]||e}function Mx(t,e,r=120){let n=new Map;for(let d of t.chunks){let m=n.get(d.source)??[],p=jO(d.heading),f=m[m.length-1];f&&f.heading===p?(f.last=d.id,f.tokens+=d.tokens):m.push({first:d.id,last:d.id,heading:p,tokens:d.tokens}),n.set(d.source,m)}let o=r,s=0,i=[...n.entries()].map(([d,m])=>{let p=m.slice(0,Math.max(0,o));o-=p.length,s+=m.length-p.length;let f=m.reduce((g,h)=>g+h.tokens,0);return{name:d,tokens:xo(f),sections:p.map(g=>`${MO(g.first,g.last)} ${g.heading} ~${R(g.tokens)}`)}}),a=t.sources.length===1?t.sources[0].name:`${t.sources.length} files`,c=t.chunks[0]?.id??"name#1",u=`OUTLINE of ${a}: ~${R(t.totalTokens)} tokens in ${t.chunks.length} chunks, as sections in structuredContent. Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${c}).`,l={total_tokens:xo(t.totalTokens),chunks:t.chunks.length,sources:i};return s>0&&(l.sections_not_shown=s),{text:u,structured:l,meta:{"context-doctor/outline":e}}}import{existsSync as ZO,lstatSync as dr,mkdirSync as Lx,readdirSync as DO,readFileSync as Pp,realpathSync as Ka,rmSync as LO,writeFileSync as jx}from"node:fs";import{homedir as wo}from"node:os";import{isAbsolute as qO,join as it,relative as UO,sep as FO}from"node:path";var bt={briefTargetTokens:400,briefChars:6e3,titleChars:80,modelChars:100,blocks:20,labelChars:80,blockChars:2e4,totalChars:6e4,kept:100,readBytes:512*1024};function Cp(t=wo()){return it(t,".context-doctor","handoffs")}var HO=/^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;function qx(t){return typeof t=="string"&&t.length<=80&&HO.test(t)}function BO(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/g,"")||"handoff"}function VO(t){let e=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}-${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function Ap(t){let e=[],r=bt;typeof t?.brief!="string"||!t.brief.trim()?e.push("`brief` is empty: write the handoff brief first."):t.brief.length>r.briefChars&&e.push(`\`brief\` is ${t.brief.length} characters; the limit is ${r.briefChars} (aim for \u2264${r.briefTargetTokens} tokens).`),t.title!==void 0&&(typeof t.title!="string"||t.title.length>r.titleChars)&&e.push(`\`title\` must be a string of at most ${r.titleChars} characters.`);let n=t.verbatim??[];if(!Array.isArray(n))e.push("`verbatim` must be a list of {label, text}.");else{n.length>r.blocks&&e.push(`${n.length} verbatim blocks; the limit is ${r.blocks}. Keep only what must stay exact.`);let o=typeof t.brief=="string"?t.brief.length:0;n.forEach((s,i)=>{(typeof s?.label!="string"||!s.label.trim()||s.label.length>r.labelChars)&&e.push(`verbatim[${i}].label must be 1-${r.labelChars} characters.`),typeof s?.text!="string"||!s.text.trim()?e.push(`verbatim[${i}].text is empty.`):s.text.length>r.blockChars?e.push(`verbatim[${i}] ("${String(s.label).slice(0,40)}") is ${s.text.length} characters; the limit is ${r.blockChars}. Summarize it, or keep only the exact lines needed.`):o+=s.text.length}),o>r.totalChars&&e.push(`The handoff is ${o} characters; the limit is ${r.totalChars}. A handoff that big is not a cut.`)}t.model!==void 0&&typeof t.model!="string"&&e.push("`model` must be a string.");for(let o of["chatTokens","turns"]){let s=t[o];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<0||s>1e8)&&e.push(`\`${o}\` must be a non-negative number.`)}return e}var bo="masked by context-doctor",Fe=(t,e,r=()=>!0)=>({kind:t,re:e,replace:n=>r(n[0])?`[${t.replace(/^an? /,"")} ${bo}]`:void 0}),JO=t=>/[0-9]/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t),WO=[Fe("a private key",/-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),Fe("an Anthropic key",/(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),Fe("an OpenAI key",/(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g,JO),Fe("an AWS access key",/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),Fe("a GitHub token",/(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),Fe("a GitLab token",/(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),Fe("a Slack token",/(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),Fe("a Slack webhook",/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),Fe("a Google API key",/(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),Fe("an npm token",/(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),Fe("a Stripe key",/(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),Fe("a Stripe webhook secret",/(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),Fe("a Hugging Face token",/(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),Fe("a SendGrid key",/(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),Fe("a Twilio key",/(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),Fe("a JWT",/(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g),{kind:"a password in a URL",re:/\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]*):([^\s@/]+)@/gi,replace:t=>`${t[1]}${t[2]}:[${bo}]@`},{kind:"a bearer token",re:/\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,replace:t=>`${t[1]}${t[2]}[${bo}]`},{kind:"a database password",re:/(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,replace:t=>`${t[1]}[${bo}]`}],Ux="(?:password|passwd|passphrase|pwd|secret|secret[_-]?key|secret[_-]?access[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|authtoken|refresh[_-]?token|bearer[_-]?token|token|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|credentials?)",KO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ux}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`,"gim"),GO=new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${Ux}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`,"gim"),XO=/^(?:string|str|number|int|integer|bool|boolean|any|null|nil|none|undefined|true|false|required|optional|empty|redacted|hidden|secret|password|\*+|x{3,}|\.{3,})$/i,YO=/^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;function Zx(t){return!(XO.test(t)||YO.test(t)||/^(?:\/|~\/|\.{1,2}\/|[A-Za-z]:\\)/.test(t)||/^(?:process\.env|os\.environ|env\.|ENV\[|getenv)/i.test(t)||/^[A-Za-z_$][\w$]*(?:\.[\w$]+)+$/.test(t)&&!/[0-9]/.test(t)||/^\d{1,7}$/.test(t))}function Zr(t){let e=0,r=new Set,n=String(t??"");for(let o of WO)n=n.replace(o.re,(...s)=>{let i=s.slice(0,-2).filter(c=>typeof c=="string"||c===void 0),a=o.replace(i);return a===void 0?i[0]:(e++,r.add(o.kind),a)});return n=n.replace(GO,(o,s,i,a)=>Zx(a.trim())?(e++,r.add("a password or secret assignment"),`${s}${i}[${bo}]${i}`):o),n=n.replace(KO,(o,s,i)=>Zx(i)?(e++,r.add("a password or secret assignment"),`${s}[${bo}]`):o),{text:n,count:e,kinds:[...r]}}function QO(t){let e=Math.max(0,...(t.match(/`+/g)??[]).map(r=>r.length));return"`".repeat(Math.max(3,e+1))}function Ip(t,e){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function eN(t,e,r,n){let o=[`# Handoff: ${t}`,"",`Continue from this handoff (written ${e.slice(0,16).replace("T"," ")} UTC, saved by context-doctor). It replaces the earlier chat; ask for anything it does not cover.`,"",r.trim()];if(n.length){o.push("","## Verbatim (keep exact)");for(let s of n){let i=QO(s.text);o.push("",`### ${Ip(s.label,bt.labelChars)}`,"",i,s.text.replace(/\s+$/,""),i)}}return o.join(`
98
98
  `)+`
99
- `}function $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.43.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 tN(t,e){let r={after:t};e.chatTokens!==void 0&&e.chatTokens>0?(r.now=Math.round(e.chatTokens),r.nowSource="given"):e.turns!==void 0&&e.turns>0&&(r.now=Math.round(e.turns)*bp(e.model),r.nowSource="turns");let n=go(e.model);return n&&(r.afterUsd=jr(r.after,n),r.afterCachedUsd=r.after/1e6*n.cacheReadPerM,r.now!==void 0&&(r.nowUsd=jr(r.now,n),r.nowCachedUsd=r.now/1e6*n.cacheReadPerM)),r}function Fx(t){let e=(o,s)=>o!==void 0?` (${Kt(o)} at list price, ${Kt(s??0)} cached)`:"";if(t.now===void 0)return`A new chat starts from ~${R(t.after)} tokens${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt. Pass chat_tokens (from profile_context) to see the per-turn saving.`;let r=t.nowSource==="turns"?" (estimated from the turn count)":"",n=Math.max(0,t.now-t.after);return[`Now: ~${R(t.now)} tokens re-read on every turn${r}${e(t.nowUsd,t.nowCachedUsd)}.`,`After: ~${R(t.after)} in a new chat${e(t.afterUsd,t.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,`Saves ~${R(n)} tokens per further turn${t.now>0?` (${Math.round(n/t.now*100)}%)`:""}; on a subscription that is usage limit.`].join(`
100
+ `)}function Ga(t,e){let r=UO(t,e);return r===""||r!==".."&&!r.startsWith(".."+FO)&&!qO(r)}var En=class extends Error{};function Xa(t,e){let r=i=>{if(e)throw new En(i)},n;try{n=Ka(t)}catch{return r("the home directory cannot be read")}let o=it(t,".context-doctor"),s=Cp(t);for(let i of[o,s]){let a;try{a=dr(i)}catch{if(!e)return;try{Lx(i,{mode:448}),a=dr(i)}catch(u){return r(`cannot create ${xt(i,t)} (${u.code??"error"})`)}}if(a.isSymbolicLink())return r(`${xt(i,t)} is a symbolic link; handoffs are only written to a real folder in the home directory`);if(!a.isDirectory())return r(`${xt(i,t)} is not a folder`);let c;try{c=Ka(i)}catch{return r(`${xt(i,t)} cannot be read`)}if(!Ga(n,c))return r(`${xt(i,t)} resolves outside the home directory`)}return s}function Dx(t,e){let r=Date.parse(t.created);return Number.isFinite(r)&&r<=e+6e4?r:0}function rN(t){let e=r=>typeof r.order=="number"&&Number.isFinite(r.order)?r.order:0;return(r,n)=>Dx(n,t)-Dx(r,t)||e(n)-e(r)||(r.id<n.id?1:r.id>n.id?-1:0)}var nN=0;function Ya(t=wo()){let e=Xa(t,!1);if(!e)return[];let r;try{r=DO(e)}catch{return[]}let n=[];for(let o of r){if(!qx(o))continue;let s=it(e,o);try{if(!dr(s).isDirectory())continue;let i=it(s,"meta.json");if(!dr(i).isFile())continue;let a=JSON.parse(Pp(i,"utf8"));if(a?.id!==o||typeof a.created!="string")continue;n.push(a)}catch{continue}}return n.sort(rN(Date.now()))}function Op(t,e=wo()){let r=t==="latest"?Ya(e)[0]?.id:t;if(!qx(r))return;let n=Xa(e,!1);if(!n)return;let o=it(n,r),s=it(o,"handoff.md");if(Ga(n,s))try{let i=dr(s);if(!i.isFile()||i.size>bt.readBytes||!dr(o).isDirectory()||!dr(it(o,"meta.json")).isFile())return;let a=JSON.parse(Pp(it(o,"meta.json"),"utf8"));return a?.id!==r?void 0:{meta:a,markdown:Pp(s,"utf8")}}catch{return}}function oN(t,e,r){let n=Xa(t,!1);if(!n)return 0;let o=Ya(t).filter(i=>i.id!==r),s=0;for(let i of o.slice(Math.max(0,e-1))){let a=it(n,i.id);try{if(!Ga(n,a)||!dr(a).isDirectory()||!dr(it(a,"meta.json")).isFile()||!Ga(Ka(n),Ka(a)))continue;LO(a,{recursive:!0,force:!0}),s++}catch{}}return s}function lr(t,{keepNewlines:e=!0}={}){let r=String(t??"").replace(/\r\n?/g,`
101
+ `);return e?r.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,""):r.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}function Hx(t,{home:e=wo(),now:r=new Date,store:n=!0}={}){let o=Ap(t);if(o.length)throw new Error(o.join(" "));let s=new Set,i=0,a=x=>{let $=Zr(x);return i+=$.count,$.kinds.forEach(N=>s.add(N)),$.text},c=a(lr(t.brief)),u=Ip(t.title?.trim()?a(lr(t.title,{keepNewlines:!1})):c.split(`
102
+ `).find(x=>x.trim())?.replace(/^#+\s*/,"")||"handoff",bt.titleChars),l=(t.verbatim??[]).map(x=>({label:Ip(a(lr(x.label,{keepNewlines:!1})),bt.labelChars),text:a(lr(x.text))})),d=t.model===void 0?void 0:a(lr(String(t.model),{keepNewlines:!1})).slice(0,bt.modelChars)||void 0,m=r.toISOString(),p=eN(u,m,c,l),f=`${VO(r)}-${BO(u)}`,g={id:f,title:u,created:m,model:d,tokens:At(p,d),briefTokens:At(c,d),blocks:l.map(x=>({label:x.label,tokens:At(x.text,d)})),masked:i,order:Date.now()*1e3+nN++%1e3},h=tN(g.tokens,{...t,model:d});if(!n)return{meta:g,markdown:p,maskedKinds:[...s],math:h,rotated:0};let _=Xa(e,!0),v="";for(let x=1;x<=200;x++){let $=x===1?f:`${f}-${x}`,N=it(_,$);try{Lx(N,{mode:448}),g.id=$,v=N;break}catch(A){if(A.code!=="EEXIST")throw new En(`cannot create a handoff folder in ${xt(_,e)} (${A.code??"error"})`)}}if(!v)throw new En(`too many handoffs saved in the same second in ${xt(_,e)}`);try{jx(it(v,"handoff.md"),p,{mode:384,flag:"wx"}),jx(it(v,"meta.json"),JSON.stringify(g,null,2)+`
103
+ `,{mode:384,flag:"wx"})}catch(x){throw new En(`cannot write the handoff in ${xt(v,e)} (${x.code??"error"})`)}let y=oN(e,bt.kept,g.id);if(!ZO(it(v,"handoff.md")))throw new En(`the handoff in ${xt(v,e)} is gone`);return{meta:g,markdown:p,dir:v,maskedKinds:[...s],math:h,rotated:y}}function xt(t,e=wo()){return e&&t.startsWith(e)?"~"+t.slice(e.length):t}function Bx(t,e=wo()){return e&&e.length>1?String(t).split(e).join("~"):String(t)}import{lookup as sN}from"node:dns";import{request as iN}from"node:http";import{request as aN}from"node:https";import{isIP as Jx}from"node:net";import{mkdtempSync as cN,rmSync as uN,writeFileSync as lN}from"node:fs";import{tmpdir as dN}from"node:os";import{extname as fN,join as Vx}from"node:path";var Ge={files:10,bytes:5*1024*1024,totalBytes:20*1024*1024,timeoutMs:2e4,redirects:3,callMs:6e4},pN={"application/pdf":".pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/msword":".doc","application/rtf":".rtf","text/rtf":".rtf","application/vnd.oasis.opendocument.text":".odt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx"};function Wx(t=process.env){return t.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES==="1"}function Np(t){let[e,r]=t.split(".").map(Number),n=Number(t.split(".")[2]);return e===0||e===10||e===127||e>=224||e===169&&r===254||e===172&&r>=16&&r<=31||e===192&&r===168||e===100&&r>=64&&r<=127||e===192&&r===0||e===198&&(r===18||r===19)||e===198&&r===51&&n===100||e===203&&r===0&&n===113||e===192&&r===88&&n===99}function mN(t){let e=t.toLowerCase().replace(/^\[|\]$/g,"").replace(/%.*$/,""),r=e.match(/(\d+\.\d+\.\d+\.\d+)$/);if(r){let[u,l,d,m]=r[1].split(".").map(Number);e=e.slice(0,-r[1].length)+`${(u<<8|l).toString(16)}:${(d<<8|m).toString(16)}`}let[n,o]=e.split("::"),s=n?n.split(":"):[],i=o!==void 0&&o?o.split(":"):[],a=e.includes("::")?8-s.length-i.length:0,c=[...s,...Array(Math.max(0,a)).fill("0"),...i].map(u=>parseInt(u||"0",16));return c.length===8&&c.every(u=>Number.isInteger(u)&&u>=0&&u<=65535)?c:void 0}function Kx(t){let e=t.replace(/^\[|\]$/g,""),r=Jx(e);if(r===4)return Np(e);if(r===6){let n=mN(e);return n?n.slice(0,5).every(o=>o===0)&&(n[5]===65535||n[5]===0)?n[5]===0&&n[6]===0&&n[7]<=1?!0:Np(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n.slice(0,4).every(o=>o===0)&&n[4]===65535&&n[5]===0?Np(`${n[6]>>8}.${n[6]&255}.${n[7]>>8}.${n[7]&255}`):n[0]===100&&n[1]===65435||n[0]===8194||n[0]===8193&&n[1]===0||(n[0]&65024)===64512||(n[0]&65472)===65152||(n[0]&65280)===65280||n[0]===8193&&n[1]===3512||n[0]===256&&n[1]===0&&n[2]===0&&n[3]===0:!0}return!0}function Mp(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127\./.test(e)}function hN(t,e=process.env){let r;try{r=new URL(t)}catch{return{error:"not a URL"}}if(r.username||r.password)return{error:"credentials in the URL"};let n=r.hostname.replace(/^\[|\]$/g,""),o=Wx(e)&&Mp(n);return r.protocol!=="https:"&&!(r.protocol==="http:"&&o)?{error:`only https downloads are allowed (got ${r.protocol.replace(":","")})`}:o?{url:r}:/^localhost$|\.localhost$|\.local$|\.internal$/i.test(n.replace(/\.$/,""))?{error:"a local host name"}:Jx(n)&&Kx(n)?{error:"a private or loopback address"}:{url:r}}function gN(t){return(e,r,n)=>{sN(e,r,(o,s,i)=>{if(o)return n(o);if((Array.isArray(s)?s:[{address:s,family:i??4}]).find(u=>Kx(u.address)&&!(t&&Mp(u.address))))return n(Object.assign(new Error(`${e} resolves to a private address`),{code:"EPRIVATE"}));Array.isArray(s)?n(null,s):n(null,s,i)})}}function yN(t,e,r,n){return new Promise(o=>{let s=Wx(e)&&Mp(t.hostname),i=t.protocol==="https:"?aN:iN,a=!1,c=m=>{a||(a=!0,clearTimeout(l),o(m))},u=Math.max(1,r-lt()),l=setTimeout(()=>{d.destroy(),c({status:0,error:"timed out"})},u),d=i(t,{method:"GET",lookup:gN(s),timeout:u,headers:{accept:"*/*","user-agent":"context-doctor"}},m=>{let p=m.statusCode??0;if(p>=300&&p<400)return m.resume(),c({status:p,location:typeof m.headers.location=="string"?m.headers.location:void 0});if(p!==200)return m.resume(),c({status:p,error:`HTTP ${p}`});let f=n<Ge.bytes?`over the ${Ge.totalBytes/1024/1024} MB total for one call`:`too large (over ${Ge.bytes/1024/1024} MB)`,g=Number(m.headers["content-length"]);if(Number.isFinite(g)&&g>n)return d.destroy(),c({status:p,error:f});let h=[],_=0;m.on("data",v=>{if(_+=v.length,_>n){d.destroy(),c({status:p,error:f});return}h.push(v)}),m.on("end",()=>c({status:p,body:Buffer.concat(h)})),m.on("error",v=>c({status:p,error:v.message}))});d.on("timeout",()=>{d.destroy(),c({status:0,error:"timed out"})}),d.on("error",m=>c({status:0,error:m.code==="EPRIVATE"?"refused: the host resolves to a private address":m.message})),d.end()})}async function _N(t,e=process.env,{deadline:r,maxBytes:n=Ge.bytes}={}){let o=Math.min(lt()+Ge.timeoutMs,r??1/0),s=Math.max(0,Math.min(n,Ge.bytes)),i=t;for(let a=0;a<=Ge.redirects;a++){let c=hN(i,e);if("error"in c)return{error:a===0?`refused: ${c.error}`:`refused a redirect: ${c.error}`};if(lt()>=o)return{error:"timed out"};let u=await yN(c.url,e,o,s);if(u.error)return{error:u.error};if(u.location!==void 0){if(!u.location)return{error:`HTTP ${u.status} without a location`};try{i=new URL(u.location,c.url).toString()}catch{return{error:"refused a redirect: not a URL"}}continue}return{body:u.body??Buffer.alloc(0)}}return{error:`more than ${Ge.redirects} redirects`}}function vN(t){return((t.file_name??"").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g,"_").trim()||String(t.file_id||"file").replace(/[^\w.-]+/g,"_")).slice(0,80)}async function Gx(t,e=process.env){let r=[],n=[],o=0,s=lt()+Ge.callMs;for(let i of t.slice(0,Ge.files)){let a=vN(i);if(lt()>=s){n.push(`${a}: not read, the ${Ge.callMs/1e3} s allowed for one call ran out`);continue}let c=await _N(String(i.download_url??""),e,{deadline:s,maxBytes:Ge.totalBytes-o});if("error"in c){n.push(`${a}: ${c.error}`);continue}o+=c.body.length;let u=fN(a).toLowerCase(),l=Fa.has(u)?u:pN[(i.mime_type??"").split(";")[0].trim().toLowerCase()];if(l){let d=cN(Vx(dN(),"cd-file-"));try{let m=Vx(d,`upload${l}`);lN(m,c.body,{mode:384});let p=await Ha(m,Math.min(lt()+Os,s));"error"in p?n.push(`${a}: ${p.error}`):r.push({name:a,text:p.text})}finally{uN(d,{recursive:!0,force:!0})}continue}if(c.body.subarray(0,8e3).includes(0)){n.push(`${a}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);continue}r.push({name:a,text:c.body.toString("utf8")})}return t.length>Ge.files&&n.push(`${t.length-Ge.files} more file(s): at most ${Ge.files} per call`),{sources:r,skipped:n}}import{isIP as xN}from"node:net";var Xx={bodyBytes:10*1024*1024,bodyMs:3e4},bN=["https://chatgpt.com","https://chat.openai.com"],Yx=["localhost","127.0.0.1","::1"];function Qa(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function ec(t){let e=t.trim().toLowerCase();return e.startsWith("[")?e=e.slice(1,e.indexOf("]")>0?e.indexOf("]"):void 0):e.split(":").length===2&&(e=e.split(":")[0]),e.replace(/\.$/,"")}function Qx(t,e,r,n=process.env,o={}){let s=[...Qa(e),...Qa(n.CONTEXT_DOCTOR_ALLOWED_HOSTS)],i=new Set([...bN,...Qa(r),...Qa(n.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map(u=>u.toLowerCase().replace(/\/+$/,"")));if(s.includes("*"))return{hosts:"*",origins:i,ipLiterals:o.ipLiterals};let a=ec(t),c=new Set([...Yx,...s.map(ec)]);return a&&a!=="0.0.0.0"&&a!=="::"&&c.add(a),{hosts:c,origins:i,ipLiterals:o.ipLiterals}}function eb(t,e){if(t.hosts!=="*"){let n=ec(String(e.host??""));if(!n)return"the request has no Host header";if(!t.hosts.has(n)&&!(t.ipLiterals&&xN(n)))return`Host "${n}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${n}`}let r=e.origin;if(r!==void 0){let n=String(r).toLowerCase().replace(/\/+$/,"");if(t.origins.has(n))return;let o;try{o=new URL(n)}catch{return`Origin "${n}" is not allowed`}let s=ec(o.host);if(!(Yx.includes(s)||t.hosts!=="*"&&t.hosts.has(s)))return`Origin "${n}" is not allowed. To let a web page call this server, start it with --allowed-origins ${n}`}}function tb(t,e=Xx.bodyBytes,r=Xx.bodyMs){return new Promise(n=>{let o=!1,s=setTimeout(()=>{o||(o=!0,n({status:408,code:-32600,message:`the request body did not arrive within ${Math.round(r/1e3)} s`}))},r),i=d=>{clearTimeout(s),n(d)},a={status:413,code:-32600,message:`request body over ${Math.round(e/1024/1024)} MB`},c=Number(t.headers["content-length"]);if(Number.isFinite(c)&&c>e)return t.resume(),i(a);let u=[],l=0;t.on("data",d=>{if(!o){if(l+=d.length,l>e)return o=!0,u.length=0,t.resume(),i(a);u.push(d)}}),t.on("end",()=>{if(!o){o=!0;try{i({value:JSON.parse(Buffer.concat(u).toString("utf8"))})}catch{i({status:400,code:-32700,message:"Parse error: the body is not JSON"})}}}),t.on("error",()=>{o||(o=!0,i({status:400,code:-32700,message:"the request body could not be read"}))})})}import{closeSync as zN,existsSync as tc,openSync as RN,readdirSync as rc,readSync as PN,statSync as Dp}from"node:fs";import{homedir as Lp}from"node:os";import{basename as ab,dirname as IN,isAbsolute as CN,join as zn,resolve as cb}from"node:path";import{readdirSync as yU,readFileSync as _U,statSync as vU,existsSync as xU,openSync as wN,readSync as $N,closeSync as kN}from"node:fs";import{StringDecoder as SN}from"node:string_decoder";import{homedir as TN}from"node:os";import{join as EN}from"node:path";function rb(t,e=TN()){return EN(ur(e),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function jp(t,e){let r=wN(t,"r"),n=new SN("utf8"),o=Buffer.allocUnsafe(4*1024*1024),s="";try{for(;;){let i=$N(r,o,0,o.length,null);if(i===0)break;s+=n.write(o.subarray(0,i));let a;for(;(a=s.indexOf(`
104
+ `))!==-1;)e(s.slice(0,a)),s=s.slice(a+1)}s+=n.end(),s&&e(s)}finally{kN(r)}}var Ns=2e5,AN=8e6,nb=16384;function Zp(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:e?.type==="image"||e?.type==="input_image"?"[image]":"").filter(Boolean).join(`
105
+ `):""}function ON(t){if(t.length<=Ns)return{whole:t};let e=Ns/2;return{head:t.slice(0,e+nb),tail:t.slice(-(e+nb)),length:t.length}}var ob=t=>"whole"in t?t.whole.length:Ns;function NN(t){if("whole"in t){let a=Zr(lr(t.whole));return{text:a.text,masked:a.count}}let e=Ns/2,r=Zr(lr(t.head)),n=lr(t.tail),o=0,s=/-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.exec(n);s&&!/-----BEGIN [A-Z0-9 ]*PRIVATE KEY/.test(n.slice(0,s.index))&&(n=`[private key masked by context-doctor]${n.slice(s.index+s[0].length)}`,o=1);let i=Zr(n);return{text:`${r.text.slice(0,e)}
106
+ [\u2026 ${t.length-Ns} characters \u2026]
107
+ ${i.text.slice(-e)}`,masked:r.count+i.count+o}}function sb(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function MN(t,e=AN){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=ON(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=ob(h);o>e&&n<r.length-1;)o-=ob(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};jp(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,Zp(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",sb(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,Zp(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,Zp(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",sb(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=NN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function jN(t){try{let e=RN(t,"r");try{let r=Buffer.alloc(65536),n=PN(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
108
+ `)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{zN(e)}}catch{return}}function ib(t){let e;try{for(let r of rc(t)){if(!r.endsWith(".jsonl"))continue;let n=zn(t,r),o=Dp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function ZN(t,e){let r=zn(Sn(e),"sessions");if(!tc(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=rc(i)}catch{return}for(let u of c){let l=zn(i,u),d;try{d=Dp(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>jN(i.path)===cb(t))}function ub(t=process.env,e=process.cwd(),r=Lp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=DN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=ib(IN(a));if(c&&c.path!==a&&c.at>Dp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${ab(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=ib(rb(e,r)),i=ZN(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function DN(t,e=Lp()){if((CN(t)||t.includes("/")||t.includes("\\"))&&tc(t))return cb(t);if(!/^[\w.-]+$/.test(t))return;let r=zn(ur(e),"projects"),n=[];try{n=rc(r)}catch{}for(let a of n){let c=zn(r,a,`${t}.jsonl`);if(tc(c))return c}let o=zn(Sn(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=rc(a)}catch{return}for(let l of u){let d=zn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return tc(o)&&i(o,0),s}function lb(t,e,r={}){let n=MN(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=Sx(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function db(t,e=Lp()){let r=ab(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${R(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
109
+ `);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 OM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],NM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function om(t,e,r){if(Ax(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function tw(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof C&&n.code===O.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function rw({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new Aa({name:"context-doctor",version:"0.45.0"},{instructions:Cx,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:D.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:D.object({turns:D.number().int().nonnegative().describe("Exchanges so far"),model:D.string().optional(),blocks:D.array(D.object({turn:D.number().int().positive(),kind:D.enum(["paste","code","tool_result","image","base64","text"]),label:D.string().describe("Short name"),approx_tokens:D.number().optional(),approx_lines:D.number().optional(),approx_words:D.number().optional(),approx_chars:D.number().optional(),repeated:D.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:D.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:D.string().optional().describe("e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(NM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",f=Kv({...a,model:a.model??c},{record:!t}),g=p+Wv(f);return om(u?._meta,g,()=>{let h=Nx(f,g);return{...h,text:p+h.text}})}if(!i)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let l=Dv($v(i),c),d=Bv(l);return om(u?._meta,d,()=>Ox(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:D.string().describe("Conversation JSON"),strategies:D.array(D.enum(OM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:D.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:D.number().int().positive().optional().describe("Per trimmed result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let l="";if(a?.includes("prune-history")){let _=await tw(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),l=`
111
+ prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=Fv(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&La({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${R(m)} tokens (${R(d.tokensBefore)} \u2192 ${R(d.tokensAfter)}) via ${d.applied.length} change(s):
112
+ `+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 Ix(c):{sources:[],skipped:[]};if(t&&g?.length){let N=await Gx(g);_.push(...N.sources),v.push(...N.skipped)}if(u&&_.push({name:"text",text:u}),_.length===0)return h(v.length?`Nothing readable: ${v.join("; ")}`:r?"Pass `paths` (files or folders) or `text`.":"This server runs over HTTP and reads no files from its own disk: pass the user's upload as `files`, or the document as `text`.");let y=await Tx(_,{query:l,budget:d,ids:m,model:p,semantic:t?void 0:f}),x=v.length?`
117
+ Skipped: ${v.slice(0,10).join("; ")}${v.length>10?` (+${v.length-10} more)`:""}`:"",$=zx(y)+x;return y.mode!=="outline"?{content:[{type:"text",text:$}]}:om(a?._meta,$,()=>{let N=Mx(y,$);return{...N,text:N.text+x}})}),n.prompt("context_checkup","Profile this conversation's context and apply the top fix. One click, no typing.",async()=>({messages:[{role:"user",content:{type:"text",text:"Run profile_context on our conversation so far: pass a `sketch` (turn count, the model you are running as, and every block over ~500 tokens, repeated, or an image; one size hint each). Report the total, the top three findings, and the estimated recoverable tokens in under 120 words. Then, if the top finding is recoverable, apply it: summarize the offending content into the points still needed and tell me what you dropped. Do not re-quote the content you are summarizing."}}]})),n.registerPrompt("handoff",{title:"Hand off to a new chat",description:"Write a short brief of this chat, save it, and continue in a new chat: the only way to cut a long chat's cost.",argsSchema:{focus:D.string().max(200).optional().describe("What the next chat should work on (optional)")}},async({focus:i})=>({messages:[{role:"user",content:{type:"text",text:`Hand this chat off to a new one. Write a dense brief of at most ${bt.briefTargetTokens} tokens: the goal, decisions made (with the reason in a few words), the current state, open items and the next step, and key identifiers (names, paths, IDs, versions, numbers). Leave out what is finished or no longer needed. Separately, list only the blocks that must stay exact (code, config, commands, figures), each with a short label. Then call save_handoff with the brief, those blocks as \`verbatim\`, a short title, the model you run as, and \`chat_tokens\` if you have a profile_context figure (else \`turns\`). Do not write the brief into this reply before the call. After it, tell me in two lines how to continue, as its result says.`+(i?.trim()?` The next chat will work on: ${i.trim()}`:"")}}]})),n.registerPrompt("ask_file",{title:"Ask a big file",description:"Answer from a big file or folder without reading it whole: pack_context returns only the parts the question needs.",argsSchema:{path:D.string().max(1e3).describe("Absolute path to the file or folder"),question:D.string().max(2e3).describe("What you want to know from it")}},async({path:i,question:a})=>({messages:[{role:"user",content:{type:"text",text:`Answer from ${JSON.stringify(i)} without pasting or reading it whole: ${a}
118
118
 
119
- Call pack_context with paths [${JSON.stringify(i)}] and the question as \`query\`. Answer from the chunks it returns and cite their ids. If they do not hold the answer, call it again with the ids it names as next best, or with no query for an outline to pick from; do not read the file whole. If pack_context cannot read paths here, ask me to attach or paste the file, and pass it as \`files\` or \`text\`.`}}]})),n.registerTool("save_handoff",{description:`Save a handoff for continuing in a new chat (a chat's history cannot be cut; a new chat can). Write \`brief\` yourself (\u2264${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${bt.briefTargetTokens} tokens: goal, decisions, state, open items, identifiers); put what must stay exact in \`verbatim\`. Only when the user agrees.`,inputSchema:{brief:D.string(),verbatim:D.array(D.object({label:D.string(),text:D.string()})).optional().describe("Code, config, figures"),title:D.string().optional(),chat_tokens:D.number().optional().describe("Chat size, from profile_context"),turns:D.number().optional(),model:D.string().optional()},annotations:{title:"Save handoff",readOnlyHint:!e,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async({brief:i,verbatim:a,title:c,chat_tokens:u,turns:l,model:d})=>{let m={brief:i,verbatim:a,title:c,model:d,chatTokens:u,turns:l},p=Ap(m);if(p.length)return{isError:!0,content:[{type:"text",text:`Not saved: ${p.join(" ")}`}]};let f=a;if(e){let y=a?.length??0,x=await tw(n,`Save a handoff of this chat on this computer (${xt(Cp())}) to start a new chat from? "${Zr(c??i.split(`
120
+ `)[0]).text.slice(0,80)}"${y?`, with ${y} verbatim block(s): ${Zr(a.map($=>$.label).join(", ")).text.slice(0,200)}`:""}.`,y?{include_verbatim:{type:"boolean",title:"Include the verbatim blocks",default:!0}}:{});if(x.asked&&!x.ok)return{content:[{type:"text",text:`Not saved: ${x.why}. Do not retry; ask the user in the chat if they still want a handoff.`}]};x.asked&&x.content.include_verbatim===!1&&(f=void 0)}let g;try{g=Hx({...m,verbatim:f},{store:e})}catch(y){let x=Bx(y.message);return{isError:!0,content:[{type:"text",text:`Not saved: ${t?"the server could not store the handoff":x}.`}]}}let h=g.meta,_=`brief ~${R(h.briefTokens)}${h.blocks.length?`, ${h.blocks.length} verbatim block(s) ~${R(h.blocks.reduce((y,x)=>y+x.tokens,0))}`:""}`,v=[g.dir?`Handoff saved: ${h.id} (~${R(h.tokens)} tokens: ${_}) in ${xt(g.dir)}.`:`Handoff ready (~${R(h.tokens)} tokens: ${_}), not stored: this server runs over HTTP and keeps nothing.`];return h.masked>0&&v.push(`Masked ${h.masked} secret-looking string(s) (${g.maskedKinds.join(", ")}) before saving; the user re-adds them by hand in the new chat if needed.`),h.briefTokens>bt.briefTargetTokens&&v.push(`The brief is ~${h.briefTokens} tokens; the target is \u2264${bt.briefTargetTokens}. It is saved; tighter is cheaper next time.`),v.push(Fx(g.math)),g.dir?(v.push(t?"Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message (or, on the machine running this server, `context-doctor handoff latest --copy`). Then stop working in this chat.":"Now tell the user, in two lines: open a new chat and attach the resource handoff://latest (Claude Desktop: + menu, context-doctor), or paste the handoff; `context-doctor handoff latest --copy` copies it. Where attaching is not possible (ChatGPT, the web, phones), print the brief and the verbatim blocks in one fenced block to paste. Then stop working in this chat."),t||n.server.sendResourceListChanged().catch(()=>{})):v.push("Now print the brief and the verbatim blocks in one fenced block, and tell the user to start a new chat with it as the first message. Then stop working in this chat."),{content:[{type:"text",text:v.join(`
121
+ `)}]}}),e&&!t){let i="No handoff saved yet. In a long chat, pick the `handoff` prompt (+ menu) or ask for a handoff; the assistant saves it with save_handoff.";n.registerResource("handoff-latest","handoff://latest",{title:"Latest handoff",description:"The newest saved handoff: attach it to a new chat to continue there.",mimeType:"text/markdown"},async a=>({contents:[{uri:a.href,mimeType:"text/markdown",text:Op("latest")?.markdown??i}]})),n.registerResource("handoff",new Oa("handoff://{id}",{list:async()=>({resources:Ya().slice(0,20).map(a=>({uri:`handoff://${a.id}`,name:a.id,title:a.title,description:`~${R(a.tokens)} tokens, saved ${a.created.slice(0,16).replace("T"," ")} UTC`,mimeType:"text/markdown"}))})}),{title:"Saved handoff",description:"A saved handoff, by id.",mimeType:"text/markdown"},async(a,{id:c})=>{let u=Op(String(Array.isArray(c)?c[0]:c));if(!u)throw new C(O.InvalidParams,`No saved handoff at ${a.href}. List them with resources/list, or run \`context-doctor handoff list\`.`);return{contents:[{uri:a.href,mimeType:"text/markdown",text:u.markdown}]}})}return r&&n.registerTool("recall",{description:"Search this session's transcript on disk (compacted turns, cleared tool output) for `query`: best excerpts with time and position. Use before asking the user again.",inputSchema:{query:D.string(),max_tokens:D.number().optional()},annotations:{title:"Recall",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({query:i,max_tokens:a})=>{let c=ub(process.env,process.cwd(),void 0,{envMayBeStale:!0});if(!c)return{isError:!0,content:[{type:"text",text:"No transcript of this session on disk (Claude Code and Codex keep one; chat apps do not)."}]};let u=Math.min(2e4,Math.max(200,Math.floor(Number(a)||2e3))),l=lb(c.path,i,{budget:u,how:c.how});return{content:[{type:"text",text:db(l)}]}}),n.tool("context_best_practices","Checklist for keeping context lean and prompts cacheable, optionally per provider.",{provider:D.enum(["general","anthropic","openai"]).optional().describe("Default: general")},{title:"Context best practices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({provider:i})=>({content:[{type:"text",text:[...nw.general,...i&&i!=="general"?nw[i]:[]].map((c,u)=>`${u+1}. ${c}`).join(`
122
+ `)}]})),MM(n),n}function MM(t){let e=t.server._requestHandlers,r=e?.get("tools/list");!e||!r||e.set("tools/list",async(n,o)=>{let s=await r(n,o);for(let i of s?.tools??[])i.inputSchema&&delete i.inputSchema.$schema;return s})}var nw={general:["Put stable content first (system prompt, tool definitions, reference docs) and volatile content last \u2014 prompt caches match byte-identical prefixes only.","Truncate or summarize tool results before they enter history; keep only what the model actually needs downstream.","Never inline base64/binary data in text content \u2014 use file/image APIs.","Summarize and drop conversation history past ~30-40 turns; models lose the middle of long contexts well before the hard limit.","Deduplicate: if the same document/result appears twice, replace later copies with a reference.","Measure before optimizing \u2014 profile the conversation to find the actual heavy hitters."],anthropic:["Use prompt caching with cache_control breakpoints after your stable prefix: cached reads cost 2.5-10% of input depending on the model, and cache writes 1.25x input (5-minute cache) or 2x (1-hour cache).","Current Claude generations have a 1M-token window (Haiku 200k), but quality degrades under heavy fill; aim to stay under ~70%.","For agents: prefer compact tool-result summaries in history and re-fetch details on demand."],openai:["Prefix caching is automatic for prompts >1024 tokens \u2014 but only on byte-identical prefixes, so keep the front of your prompt stable.","Use max_completion_tokens headroom math: input + output must fit the window together."]};function jM(t,e,r){t.headers[e]=r;let n=t.rawHeaders;for(let o=0;o<n.length;o+=2)if(n[o].toLowerCase()===e){n[o+1]=r;return}n.push(e,r)}var dc=process.argv.slice(2);if(dc.includes("--http")){let t=a=>{let c=dc.indexOf(a);return c>=0?dc[c+1]:void 0},e=Number(t("--port"))>0?Number(t("--port")):8808,r=t("--host")??"127.0.0.1",n=dc.includes("--store-handoffs"),o=Qx(r,t("--allowed-hosts"),t("--allowed-origins")),{createServer:s}=await import("node:http"),{StreamableHTTPServerTransport:i}=await Promise.resolve().then(()=>(ew(),Qb));s(async(a,c)=>{try{if(a.url==="/health"){c.setHeader("content-type","application/json"),c.end(JSON.stringify({ok:!0,service:"context-doctor-mcp"}));return}let u=(a.url??"").split("?")[0];if(u!=="/mcp"&&u!=="/mcp/"){c.statusCode=404,c.end(JSON.stringify({error:"MCP endpoint is /mcp"}));return}let l=(_,v,y)=>{let x=()=>{c.writableEnded||(c.statusCode=_,c.setHeader("content-type","application/json"),(_===413||_===408)&&c.setHeader("connection","close"),c.end(JSON.stringify({jsonrpc:"2.0",error:{code:v,message:y},id:null})),(_===413||_===408)&&setTimeout(()=>a.destroy(),1e3).unref())};if(_===413&&a.headers["content-length"]===void 0&&!a.complete){a.resume();let $=setTimeout(x,5e3);$.unref(),a.once("end",()=>{clearTimeout($),x()}),a.once("error",()=>{clearTimeout($),x()});return}x()},d=eb(o,a.headers);if(d)return l(403,-32e3,`Forbidden: ${d}.`);if(a.method!=="POST"){c.statusCode=405,c.setHeader("allow","POST"),c.end(JSON.stringify({error:"Stateless server: POST /mcp only"}));return}let m=await tb(a);if(!("value"in m))return l(m.status,m.code,m.message);let p=String(a.headers.accept??""),f=p.includes("text/event-stream");(!f||!p.includes("application/json"))&&jM(a,"accept","application/json, text/event-stream");let g=rw({http:!0,storeHandoffs:n}),h=new i({sessionIdGenerator:void 0,enableJsonResponse:!f});c.on("close",()=>{h.close(),g.close()}),await g.connect(h),await h.handleRequest(a,c,m.value)}catch(u){c.headersSent||(c.statusCode=500),c.end(JSON.stringify({error:u.message}))}}).listen(e,r,()=>{console.error(`context-doctor MCP (streamable HTTP) on http://${r}:${e}/mcp`),console.error("ChatGPT developer-mode connectors need a URL their servers can reach \u2014 expose this via your host or a tunnel."),console.error(o.hosts==="*"?"Host check off (--allowed-hosts '*').":`Answering Host: ${[...o.hosts].join(", ")}. Behind a tunnel, add its host name: --allowed-hosts <name>.`)})}else{let t=new Ma;await rw().connect(t)}