context-mode 1.0.158 → 1.0.159
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.openclaw-plugin/openclaw.plugin.json +1 -1
- package/.openclaw-plugin/package.json +1 -1
- package/build/adapters/codex/index.d.ts +4 -1
- package/build/adapters/codex/index.js +237 -45
- package/cli.bundle.mjs +181 -178
- package/hooks/session-loaders.mjs +218 -3
- package/hooks/sessionstart.mjs +52 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server.bundle.mjs +132 -129
package/cli.bundle.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function Ei(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function
|
|
4
|
-
`))}function
|
|
5
|
-
`)}function
|
|
2
|
+
var FR=Object.create;var _d=Object.defineProperty;var HR=Object.getOwnPropertyDescriptor;var UR=Object.getOwnPropertyNames;var BR=Object.getPrototypeOf,ZR=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),we=(t,e)=>{for(var r in e)_d(t,r,{get:e[r],enumerable:!0})},qR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of UR(e))!ZR.call(t,o)&&o!==r&&_d(t,o,{get:()=>e[o],enumerable:!(n=HR(e,o))||n.enumerable});return t};var xi=(t,e,r)=>(r=t!=null?FR(BR(t)):{},qR(e||!t||!t.__esModule?_d(r,"default",{value:t,enumerable:!0}):r,t));var Ed=L((vq,bx)=>{"use strict";var wd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},tC={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},rC={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?wd.up():"");return t&&(e+=wd.left),e}};bx.exports={cursor:wd,scroll:tC,erase:rC,beep:"\x07"}});var Tx=L((n4,Od)=>{var hc=process||{},Ex=hc.argv||[],fc=hc.env||{},TC=!(fc.NO_COLOR||Ex.includes("--no-color"))&&(!!fc.FORCE_COLOR||Ex.includes("--color")||hc.platform==="win32"||(hc.stdout||{}).isTTY&&fc.TERM!=="dumb"||!!fc.CI),PC=(t,e,r=t)=>n=>{let o=""+n,s=o.indexOf(e,t.length);return~s?t+RC(o,e,r,s)+e:t+o+e},RC=(t,e,r,n)=>{let o="",s=0;do o+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return o+t.substring(s)},$x=(t=TC)=>{let e=t?PC:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Od.exports=$x();Od.exports.createColors=$x});function Si(t,e){let r=process.execPath.replace(/\\/g,"/");if(Yn(e?.platform)){let o=r.split("/").pop().replace(/\.exe$/i,"");Id.has(o)||(r=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let n=t.replace(/\\/g,"/");return`"${r}" "${n}"`}function Xe(t,e){if(Yn(e?.platform))return Si(t,e);let n=Ad().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${n}" "${o}"`}function gc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Yn(t){return!!t&&CC.has(t)}var Id,CC,Cr=S(()=>{"use strict";Xo();Id=new Set(["node","bun","deno"]),CC=new Set(["opencode","kilo"])});var Ax={};we(Ax,{buildCommand:()=>Ld,detectRuntimes:()=>Qn,getAvailableLanguages:()=>Ei,getRuntimeSummary:()=>wi,hasBunRuntime:()=>_n,isAllowlistedShell:()=>Rx,resetHookRuntimeCache:()=>NC,resolveHookRuntime:()=>Ad,resolveJavascriptRuntime:()=>Ix});import{execFileSync as Md,execSync as Yo}from"node:child_process";import{existsSync as yc}from"node:fs";function Dd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function Rx(t){return OC.test(Dd(t))}function IC(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function tt(t){try{let e=ki?`where ${t}`:`command -v ${t}`;return Yo(e,{stdio:"pipe"}),!0}catch{return!1}}function Nd(t){if(ki)try{let r=Yo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!tt(t))return!1;try{return ki?Yo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Md(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function jd(){if(tt("bun"))return!0;for(let t of Ox())if(yc(t))return!0;return!1}function Cx(){for(let e of Ox())if(yc(e))return e;if(tt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return ki?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Ox(){let t=process.env.HOME??process.env.USERPROFILE??"";if(ki){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function AC(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(yc(e))return e;try{let r=Yo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Wt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Yo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Md(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Ix(t,e={}){if(t)return t;let r=e.execPath??process.execPath,n=e.commandExists??tt,o=r.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Id.has(o)?r:n("node")?"node":null}function Qn(){let e=jd()?Cx():null,r=process.env.SHELL,n=process.platform==="win32",o=r&&yc(r)&&Rx(r)&&!(n&&IC(r))?r:null;return{javascript:Ix(e),typescript:e||(tt("tsx")?"tsx":tt("ts-node")?"ts-node":null),python:Nd("python3")?"python3":Nd("python")?"python":Nd("py")?"py":null,shell:o??(n?AC()??(tt("sh")?"sh":tt("powershell")?"powershell":"cmd.exe"):tt("bash")?"bash":"sh"),ruby:tt("ruby")?"ruby":null,go:tt("go")?"go":null,rust:tt("rustc")?"rustc":null,php:tt("php")?"php":null,perl:tt("perl")?"perl":null,r:tt("Rscript")?"Rscript":tt("r")?"r":null,elixir:tt("elixir")?"elixir":null,csharp:tt("dotnet-script")?"dotnet-script":null}}function _n(){return jd()}function NC(){zt=null}function DC(t){let e=t.trim(),r=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!r)return!1;let n=Number(r[1]);return Number.isFinite(n)&&n>=1}function Ad(){if(zt)return zt;let t={path:process.execPath,isBun:!1};try{if(!jd())return zt=t,zt;let e=Cx(),r;try{if(process.platform==="win32"){let n=Yo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}else{let n=Md(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}}catch{return zt=t,zt}return DC(r)?(zt={path:e,isBun:!0},zt):(zt=t,zt)}catch{return zt=t,zt}}function wi(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Wt(t.javascript)})${r?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Wt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Wt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Wt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Wt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Wt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Wt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Wt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Wt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Wt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Wt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Wt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
3
|
+
`)}function Ei(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function Ld(t,e,r){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Px.test(Dd(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Px.test(Dd(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",r];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var OC,Px,ki,zt,Xo=S(()=>{"use strict";Cr();OC=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Px=/^bun(\.exe)?$/i;ki=process.platform==="win32";zt=null});function MC(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function jC(t){let e=gc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function _c(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of MC(s)){let a=jC(i);a&&r.add(a)}return[...r]}var zd=S(()=>{"use strict";Cr()});var Nx,Dx=S(()=>{"use strict";Nx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var Ud={};we(Ud,{BunSQLiteAdapter:()=>xc,NodeSQLiteAdapter:()=>bc,SQLiteBase:()=>Ti,applyWALPragmas:()=>es,cleanOrphanedWALFiles:()=>ts,closeDB:()=>rs,defaultDBPath:()=>Hd,deleteDBFiles:()=>vc,hasModernSqlite:()=>Lx,isSQLiteCorruptionError:()=>Sc,loadDatabase:()=>rt,nodeSqliteHasFts5:()=>jx,renameCorruptDB:()=>zx,withRetry:()=>xn});import{createRequire as LC}from"node:module";import{existsSync as zC,unlinkSync as Mx,renameSync as FC}from"node:fs";import{tmpdir as HC}from"node:os";import{join as UC}from"node:path";function jx(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function Lx(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function rt(){if(!Qo){let t=LC(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new xc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(Lx()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&jx(e)?Qo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new bc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Qo=t("better-sqlite3")}else Qo=t("better-sqlite3")}return Qo}function es(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function ts(t){if(!zC(t))for(let e of["-wal","-shm"])try{Mx(t+e)}catch{}}function vc(t){for(let e of["","-wal","-shm"])try{Mx(t+e)}catch{}}function rs(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Hd(t="context-mode"){return UC(HC(),`${t}-${process.pid}.db`)}function xn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Sc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function zx(t){let e=Date.now();for(let r of["","-wal","-shm"])try{FC(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var xc,bc,Qo,$i,Fd,Ti,bn=S(()=>{"use strict";xc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},bc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qo=null;$i=Symbol.for("__context_mode_live_dbs_v3__"),Fd=(()=>{let t=globalThis;return t[$i]||(t[$i]=new Set,process.on("exit",()=>{for(let e of t[$i])rs(e);t[$i].clear()})),t[$i]})(),Ti=class{#e;#t;constructor(e){let r=rt();this.#e=e,ts(e);let n;try{n=new r(e,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){zx(e),ts(e);try{n=new r(e,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,Fd.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Fd.delete(this.#t),rs(this.#t)}withRetry(e){return xn(e)}cleanup(){Fd.delete(this.#t),rs(this.#t),vc(this.#e)}}});var Qx={};we(Qx,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>sO,applyMissingSessionEventsColumns:()=>qd,clearStorageDirectoryCheckCacheForTests:()=>QC,describeStorageDirectorySource:()=>Ri,ensureSessionEventsSchema:()=>Vd,ensureWritableStorageDir:()=>Ir,formatStorageDirectoryError:()=>is,getWorktreeSuffix:()=>Ci,hashProjectDirCanonical:()=>nt,hashProjectDirLegacy:()=>Ar,normalizeWorktreePath:()=>as,resolveContentStorageDir:()=>Sn,resolveContentStorePath:()=>Zd,resolveDefaultSessionDir:()=>$c,resolveSessionDbPath:()=>cs,resolveSessionPath:()=>Yx,resolveSessionStorageDir:()=>Jr,resolveStatsStorageDir:()=>ss});import{createHash as Pi}from"node:crypto";import{execFileSync as BC}from"node:child_process";import{accessSync as ZC,constants as qC,existsSync as Ec,mkdirSync as VC,realpathSync as WC,renameSync as Bd}from"node:fs";import{homedir as qx}from"node:os";import{dirname as KC,isAbsolute as Vx,join as vn,resolve as os}from"node:path";function $c(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):vn(GC(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function GC(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?Hx(n.trim()):Hx(t,qx())}function Hx(t,e){return t.startsWith("~")?os(qx(),t.replace(/^~[/\\]?/,"")):Vx(t)?os(t):e?os(e,t):os(t)}function JC(t,e,r){return new Kt(t,e,Or,void 0,[`Invalid ${Or} for context-mode ${t} directory: ${r}`,Jx()].join(`
|
|
4
|
+
`))}function Kx(t){let e=process.env[Or];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:Or,ignoredReason:"empty"};if(!Vx(r))throw JC(t,r,`${Or} must be an absolute path.`);return{kind:"override",root:os(r)}}function XC(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function Gx(t,e){let r=Kx(t);return r.kind!=="override"?null:{kind:t,path:vn(r.root,e),envVar:Or,source:"override"}}function YC(t,e,r){return{kind:t,path:os(e()),envVar:null,source:"default",...r}}function Jr(t){let e=Kx("session");return e.kind==="override"?{kind:"session",path:vn(e.root,Wx),envVar:Or,source:"override"}:YC("session",t,XC(e))}function Sn(t){let e=Gx("content",Fx);if(e)return e;let r=Jr(t);return{kind:"content",path:vn(KC(r.path),Fx),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function ss(t){let e=Gx("stats",Wx);if(e)return e;let r=Jr(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function is(t){return t.message}function Ri(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function QC(){wc.clear()}function Ir(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=wc.get(e);if(r instanceof Kt)throw r;if(r===t.path)return r;try{return VC(t.path,{recursive:!0}),ZC(t.path,qC.W_OK),wc.set(e,t.path),t.path}catch(n){let o=new Kt(t.kind,rO(n)??t.path,Or,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw wc.set(e,o),o}}function eO(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,tO(r),Jx()].filter(Boolean).join(`
|
|
5
|
+
`)}function tO(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function Jx(){return`Set ${Or} to a writable absolute path.`}function rO(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function as(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function Ux(t){let e=t;try{e=WC.native(t)}catch{}let r=as(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function Xx(t,e){return BC("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function nO(t){let e=Xx(t,["rev-parse","--show-toplevel"]);return e.length>0?as(e):null}function oO(t){let e=Xx(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?as(e):null}function Ci(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ns&&ns.projectDir===t&&ns.envSuffix===e)return ns.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=nO(t),o=oO(t);if(n&&o){let s=Ux(n),i=Ux(o);s!==i&&(r=`__${Pi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return ns={projectDir:t,envSuffix:e,suffix:r},r}function sO(){ns=void 0}function Ar(t){return Pi("sha256").update(as(t)).digest("hex").slice(0,16)}function nt(t){let e=as(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Pi("sha256").update(r).digest("hex").slice(0,16)}function Zd(t){let{projectDir:e,contentDir:r}=t,n=nt(e),o=vn(r,`${n}.db`);if(Ec(o))return o;let s=Ar(e);if(s===n)return o;let i=vn(r,`${s}.db`);if(Ec(i))try{Bd(i,o);for(let a of["-wal","-shm"])try{Bd(i+a,o+a)}catch{}}catch{}return o}function cs(t){return Yx({...t,ext:".db"})}function Yx(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??Ci(e),s=nt(e),i=vn(r,`${s}${o}${n}`);if(Ec(i))return i;let a=Ar(e);if(a===s)return i;let c=vn(r,`${a}${o}${n}`);if(Ec(c))try{Bd(c,i)}catch{}return i}function kc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function qd(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(o=>o.name)),n=!1;for(let[o,s]of iO)r.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function Vd(t,e){let r=null;try{r=new e(t),qd(r)}catch{}finally{try{r?.close()}catch{}}}var Or,Wx,Fx,Kt,wc,ns,Bx,Zx,U,iO,Gt,Jt=S(()=>{"use strict";bn();Or="CONTEXT_MODE_DIR",Wx="sessions",Fx="content",Kt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=Or,o,s,i={}){super(s??eO(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},wc=new Map;Bx=1e3,Zx=5;U={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},iO=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];Gt=class extends Ti{constructor(e){super(e?.dbPath??Hd("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
6
6
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
7
7
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8
8
|
session_id TEXT NOT NULL,
|
|
@@ -52,7 +52,7 @@ var jR=Object.create;var yd=Object.defineProperty;var LR=Object.getOwnPropertyDe
|
|
|
52
52
|
);
|
|
53
53
|
|
|
54
54
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
55
|
-
`);try{
|
|
55
|
+
`);try{qd(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(U.insertEvent,`INSERT INTO session_events (
|
|
56
56
|
session_id, type, category, priority, data,
|
|
57
57
|
project_dir, attribution_source, attribution_confidence,
|
|
58
58
|
bytes_avoided, bytes_returned,
|
|
@@ -137,43 +137,46 @@ var jR=Object.create;var yd=Object.defineProperty;var LR=Object.getOwnPropertyDe
|
|
|
137
137
|
FROM tool_calls WHERE session_id = ?`),e(U.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
138
138
|
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(U.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
139
139
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
140
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=Pi("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=kc(s?.bytesAvoided),
|
|
140
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=Pi("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=kc(s?.bytesAvoided),p=kc(s?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(U.checkDuplicate).get(e,Zx,r.type,i))return;this.stmt(U.getEventCount).get(e).cnt>=Bx&&this.stmt(U.evictLowestPriority).run(e),this.stmt(U.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,l,d,p,n,i),this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let l=Pi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),h=String(d?.source??c.attribution_source??"unknown"),m=Number(d?.confidence??c.attribution_confidence??0),f=Number.isFinite(m)?Math.max(0,Math.min(1,m)):0,g=s?.[u],y=kc(g?.bytesAvoided),_=kc(g?.bytesReturned);return{event:c,dataHash:l,projectDir:p,attributionSource:h,attributionConfidence:f,bytesAvoided:y,bytesReturned:_}}),a=this.db.transaction(()=>{let c=this.stmt(U.getEventCount).get(e).cnt;for(let u of i)this.stmt(U.checkDuplicate).get(e,Zx,u.event.type,u.dataHash)||(c>=Bx?this.stmt(U.evictLowestPriority).run(e):c++,this.stmt(U.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(U.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(U.getEventsByType).all(e,o,n):s!==void 0?this.stmt(U.getEventsByPriority).all(e,s,n):this.stmt(U.getEvents).all(e,n)}getEventCount(e){return this.stmt(U.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(U.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(U.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(U.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}getSessionIdsForProject(e){try{return this.db.prepare(`SELECT DISTINCT session_id
|
|
141
141
|
FROM session_events
|
|
142
|
-
WHERE project_dir = ?`).all(e).map(n=>n.session_id)}catch{return[]}}ensureSession(e,r){this.stmt(U.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(U.getSessionStats).get(e)??null}getSessionRollup(e){let r=this.stmt(U.getSessionRollup).get(e),n=this.stmt(U.getMaxFileEdits).get(e),o=this.getSessionStats(e),s=(r?.tool_calls??0)>0?r?.unique_files??0:0,i=r?.errors??0,a=Math.min(s,i);return{tool_calls:r?.tool_calls??0,errors:r?.errors??0,unique_tools:r?.unique_tools??0,unique_files:r?.unique_files??0,max_file_edits:n?.max_file_edits??0,has_commit:r?.has_commit??0,edit_test_cycles:a,duration_min:r?.duration_min??0,compact_count:o?.compact_count??0,sources_indexed:r?.sources_indexed??0,total_chunks:r?.total_chunks??0,search_queries:r?.search_queries??0}}incrementCompactCount(e){this.stmt(U.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(U.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(U.getResume).get(e)??null}markResumeConsumed(e){this.stmt(U.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(U.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(U.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(U.getToolCallTotals).get(e),n=this.stmt(U.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(U.deleteEvents).run(e),this.stmt(U.deleteResume).run(e),this.stmt(U.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(U.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as us,resolve as
|
|
143
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,fr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,fr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(
|
|
144
|
-
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function
|
|
145
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[Oe.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Oe.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}getHealthChecks(e){return Object.entries(Rc).map(([r,n])=>{let o=
|
|
146
|
-
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var
|
|
147
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Xt(
|
|
148
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Yr(
|
|
149
|
-
`):null}function
|
|
142
|
+
WHERE project_dir = ?`).all(e).map(n=>n.session_id)}catch{return[]}}ensureSession(e,r){this.stmt(U.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(U.getSessionStats).get(e)??null}getSessionRollup(e){let r=this.stmt(U.getSessionRollup).get(e),n=this.stmt(U.getMaxFileEdits).get(e),o=this.getSessionStats(e),s=(r?.tool_calls??0)>0?r?.unique_files??0:0,i=r?.errors??0,a=Math.min(s,i);return{tool_calls:r?.tool_calls??0,errors:r?.errors??0,unique_tools:r?.unique_tools??0,unique_files:r?.unique_files??0,max_file_edits:n?.max_file_edits??0,has_commit:r?.has_commit??0,edit_test_cycles:a,duration_min:r?.duration_min??0,compact_count:o?.compact_count??0,sources_indexed:r?.sources_indexed??0,total_chunks:r?.total_chunks??0,search_queries:r?.search_queries??0}}incrementCompactCount(e){this.stmt(U.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(U.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(U.getResume).get(e)??null}markResumeConsumed(e){this.stmt(U.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(U.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(U.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(U.getToolCallTotals).get(e),n=this.stmt(U.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(U.deleteEvents).run(e),this.stmt(U.deleteResume).run(e),this.stmt(U.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(U.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as us,resolve as eb}from"node:path";import{accessSync as aO,copyFileSync as cO,constants as uO,mkdirSync as lO}from"node:fs";import{homedir as Wd}from"node:os";function Pt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?eb(Wd(),e.replace(/^~[/\\]?/,"")):eb(e)}var xe,pt=S(()=>{"use strict";Jt();xe=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=Pt(),r=e?us(e,"context-mode","sessions"):us(Wd(),...this.sessionDirSegments,"context-mode","sessions");return lO(r,{recursive:!0}),r}getConfigDir(e){return us(Wd(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=Pt(),n=r?us(r,"context-mode","memory"):us(this.getConfigDir(),"memory");return e?us(n,nt(e)):n}backupSettings(){let e=this.getSettingsPath();try{aO(e,uO.R_OK);let r=e+".bak";return cO(e,r),r}catch{return null}}}});var ls,Kd=S(()=>{"use strict";pt();ls=class extends xe{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Gd}from"node:fs";import{join as Jd}from"node:path";async function dO(){if(ds)return ds;if(ps)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return ds=n,ds}catch(n){e=n}return ps=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ps=t instanceof Error?t.message:String(t),null}}function pO(t){let e=[];return Gd(Jd(t,"start.mjs"))||e.push("start.mjs"),!Gd(Jd(t,"server.bundle.mjs"))&&!Gd(Jd(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function tb(t){if(ds){let e=ds.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ps){let e=pO(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ps}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ps}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ds,ps,rb=S(()=>{"use strict";ds=null,ps=null;dO()});function Oi(t,e){let r=eo[e],n=Yd(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Yd(t,e){if(e){let r=eo[t];return Xe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Qd(t){let e=gc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function sb(t){let e=Object.values(eo);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var fr,mO,Xd,nb,fO,A4,eo,ob,N4,ib=S(()=>{"use strict";Cr();fr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},mO="mcp__",Xd=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",mO],nb=Xd.join("|"),fO=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],A4=fO.join("|"),eo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},ob=[fr.PRE_TOOL_USE,fr.SESSION_START],N4=[fr.POST_TOOL_USE,fr.PRE_COMPACT,fr.USER_PROMPT_SUBMIT]});var tp={};we(tp,{ClaudeCodeAdapter:()=>ep});import{readFileSync as Tc,writeFileSync as ab,existsSync as cb,readdirSync as hO,chmodSync as gO,accessSync as yO,mkdirSync as _O,constants as xO}from"node:fs";import{resolve as Pc,join as kn}from"node:path";import{homedir as ub}from"node:os";var ep,rp=S(()=>{"use strict";Kd();pt();wn();rb();Cr();ib();ep=class extends ls{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return qe()}getSessionDir(){let e=Pt(),r=e?kn(e,"context-mode","sessions"):kn(this.getConfigDir(),"context-mode","sessions");return _O(r,{recursive:!0}),r}getSettingsPath(){return kn(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Xe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Xd].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Tc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){ab(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
143
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,fr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,fr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(eo).map(([o,s])=>{let i=kn(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>cb(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>tb(e)};return[...r,n]}readPluginHooks(e){let r=[kn(e,"hooks","hooks.json"),kn(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=Tc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>Oi(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>Oi(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=kn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Tc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),qe(),Pc(ub(),".claude"),Pc(ub(),".config","claude")]));for(let r of e){let n=Pc(r,"plugins","cache","context-mode","context-mode");try{let s=hO(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(d=>{let p=d;if(!sb(p))return!0;let h=p.hooks??[];return h.every(f=>!f.command||!Qd(f.command))?!0:h.every(f=>{let g=f.command?Qd(f.command):null;return g?cb(g):!0})}),l=c.length-u.length;l>0&&(n[a]=u,o.push(`Removed ${l} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&ob.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(eo),u=l=>l!=null&&(c.some(d=>l.includes(d))||l.includes("context-mode hook"));for(let l of Object.keys(n)){let d=n[l];if(!Array.isArray(d))continue;let p=0;for(let m of d){let f=m,g=f.hooks??[],y=g.length;f.hooks=g.filter(_=>!u(_.command)),p+=y-f.hooks.length}let h=d.filter(m=>{let f=m.hooks;return Array.isArray(f)&&f.length>0});(p>0||h.length!==d.length)&&(n[l]=h,p>0&&o.push(`Removed ${p} duplicate ${l} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[fr.PRE_TOOL_USE,fr.SESSION_START];for(let a of i){let c=Yd(a,e);if(a===fr.PRE_TOOL_USE){let u={matcher:nb,hooks:[{type:"command",command:c}]},l=n.PreToolUse;if(l&&Array.isArray(l)){let d=l.findIndex(p=>Oi(p,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=l}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},l=n[a];if(l&&Array.isArray(l)){let d=l.findIndex(p=>Oi(p,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n[a]=l}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(eo)){let o=Pc(e,"hooks",n);try{yO(o,xO.R_OK),gO(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=kn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Tc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();ab(n,JSON.stringify(o,null,2)+`
|
|
144
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function to(t,e){let r=Rc[t];return e&&r?Xe(`${e}/hooks/gemini-cli/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Oe,lb,Rc,V4,W4,db=S(()=>{"use strict";Cr();Oe={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},lb="mcp__(?!.*context-mode)",Rc={[Oe.BEFORE_AGENT]:"beforeagent.mjs",[Oe.BEFORE_TOOL]:"beforetool.mjs",[Oe.AFTER_TOOL]:"aftertool.mjs",[Oe.PRE_COMPRESS]:"precompress.mjs",[Oe.SESSION_START]:"sessionstart.mjs"},V4=[Oe.BEFORE_TOOL,Oe.SESSION_START],W4=[Oe.AFTER_TOOL,Oe.PRE_COMPRESS]});var fb={};we(fb,{GeminiCLIAdapter:()=>op});import{readFileSync as np,writeFileSync as pb,mkdirSync as bO,accessSync as vO,chmodSync as SO,existsSync as kO,constants as wO}from"node:fs";import{resolve as Ii,join as mb}from"node:path";import{homedir as Cc}from"node:os";var op,hb=S(()=>{"use strict";pt();db();op=class extends xe{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ii(Cc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Oe.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:to(Oe.BEFORE_AGENT,e)}]}],[Oe.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${lb}`,hooks:[{type:"command",command:to(Oe.BEFORE_TOOL,e)}]}],[Oe.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:to(Oe.AFTER_TOOL,e)}]}],[Oe.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:to(Oe.PRE_COMPRESS,e)}]}],[Oe.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:to(Oe.SESSION_START,e)}]}]}}readSettings(){try{let e=np(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Ii(Cc(),".gemini");bO(r,{recursive:!0}),pb(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
145
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[Oe.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Oe.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}getHealthChecks(e){return Object.entries(Rc).map(([r,n])=>{let o=mb(e,"hooks","gemini-cli",n);return{name:`Hook script: ${r} (${n})`,check:()=>kO(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Ii(Cc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(np(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:Oe.BEFORE_AGENT},{name:Oe.BEFORE_TOOL},{name:Oe.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:to(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(h=>h.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=mb(e,"hooks","gemini-cli");for(let o of Object.values(Rc)){let s=Ii(n,o);try{vO(s,wO.R_OK),SO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Ii(Cc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(np(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),pb(n,JSON.stringify(o,null,2)+`
|
|
146
|
+
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var ro,e9,t9,gb=S(()=>{"use strict";ro={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},e9=[ro.BEFORE,ro.AFTER],t9=[ro.COMPACTING]});var _b={};we(_b,{OpenCodeAdapter:()=>sp});import{readFileSync as yb,writeFileSync as $O,mkdirSync as TO,copyFileSync as PO,accessSync as RO,constants as CO}from"node:fs";import{resolve as Xt,join as Xr}from"node:path";import{homedir as En}from"node:os";function EO(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var sp,xb=S(()=>{"use strict";pt();gb();sp=class extends xe{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Xt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Xt("kilo.json"),Xt("kilo.jsonc"),Xt(".kilo","kilo.json"),Xt(".kilo","kilo.jsonc"),Xt(".kilocode","kilo.json"),Xt(".kilocode","kilo.jsonc"),Xr(En(),".config","kilo","kilo.json"),Xr(En(),".config","kilo","kilo.jsonc")]:[Xt("opencode.json"),Xt("opencode.jsonc"),Xt(".opencode","opencode.json"),Xt(".opencode","opencode.jsonc"),Xr(En(),".config","opencode","opencode.json"),Xr(En(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Pt(),r=e?Xr(e,"context-mode","sessions"):Xr(this.getConfigDir(),"context-mode","sessions");return TO(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Xr(En(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Xr(En(),".config"),Xr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[ro.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(En()))),n=null,o;for(let s of e)try{let i=yb(s,"utf-8"),a=s.endsWith(".jsonc")?EO(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){$O(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
147
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Xt(En(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(yb(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{RO(this.settingsPath,CO.R_OK);let r=this.settingsPath+".bak";return PO(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var no,c9,u9,bb=S(()=>{"use strict";no={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},c9=[no.TOOL_CALL_BEFORE,no.TOOL_CALL_AFTER],u9=[no.COMMAND_NEW]});var vb={};we(vb,{OpenClawAdapter:()=>up});import{readFileSync as ip,writeFileSync as OO,copyFileSync as IO,accessSync as AO,constants as NO}from"node:fs";import{resolve as Yr,join as ap}from"node:path";import{homedir as cp}from"node:os";var up,Sb=S(()=>{"use strict";pt();bb();up=class extends xe{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Yr("openclaw.json")}getConfigDir(e){return Yr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return ap(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[no.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Yr("openclaw.json"),Yr(".openclaw","openclaw.json"),ap(cp(),".openclaw","openclaw.json")];for(let r of e)try{let n=ip(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Yr("openclaw.json");OO(r,JSON.stringify(e,null,2)+`
|
|
148
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Yr(cp(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(ip(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Yr("node_modules","context-mode","package.json"),r=JSON.parse(ip(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Yr("openclaw.json"),Yr(".openclaw","openclaw.json"),ap(cp(),".openclaw","openclaw.json")];for(let r of e)try{AO(r,NO.R_OK);let n=r+".bak";return IO(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as kb}from"node:os";import{resolve as lp}from"node:path";function wb(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?lp(kb(),t.replace(/^~[/\\]?/,"")):lp(t):lp(kb(),".codex")}var Eb=S(()=>{"use strict"});var Ob={};we(Ob,{CodexAdapter:()=>fp,probeCodexCliVersion:()=>Rb});import{execFileSync as DO}from"node:child_process";import{existsSync as MO,readFileSync as ms,writeFileSync as $b,accessSync as jO,copyFileSync as LO,constants as zO,mkdirSync as dp}from"node:fs";import{resolve as FO,dirname as pp,join as Qr}from"node:path";import{fileURLToPath as HO}from"node:url";function Rb(t=DO){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function Oc(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
|
|
149
|
+
`):null}function Cb(t){let e=Oc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function ZO(t){let e=Oc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function mp(t){let e=Oc(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Tb(t){return Oc(t,"mcp_servers.context-mode")!==null}function qO(t){if(Cb(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
150
150
|
`)?`\r
|
|
151
151
|
`:`
|
|
152
152
|
`,r=t.split(/\r?\n/),n=r.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(n===-1){let s=t.length>0&&!t.endsWith(`
|
|
153
|
-
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}
|
|
153
|
+
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}function Pb(t,e){let r=t.includes(`\r
|
|
154
154
|
`)?`\r
|
|
155
155
|
`:`
|
|
156
|
-
`,d=u.text.endsWith(`
|
|
157
|
-
`)
|
|
156
|
+
`,n=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of n){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(r),removed:s}}function VO(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{let r="",n=!1;for(let o of e.slice(1,-1))n?(r+=o==='"'||o==="\\"?o:`\\${o}`,n=!1):o==="\\"?n=!0:r+=o;return n&&(r+="\\"),r}}var UO,oo,BO,fp,Ib=S(()=>{"use strict";pt();Jt();Eb();UO="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",oo={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},BO={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};fp=class extends xe{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return wb()}getSettingsPath(){return Qr(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Pt(),r=e?Qr(e,"context-mode","sessions"):Qr(this.getConfigDir(),"context-mode","sessions");return dp(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Pt(),n=r?Qr(r,"context-mode","memories"):Qr(this.getConfigDir(),"memories");return e?Qr(n,nt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:UO,hooks:[{type:"command",command:oo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:oo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:oo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:oo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:oo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:oo.Stop}]}]}}readSettings(){try{return{_raw_toml:ms(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Rb(),o="",s=!1;r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=ms(this.getSettingsPath(),"utf-8"),s=!0;let p=Cb(o),h=!p&&ZO(o);r.push({check:"Codex hooks feature flag",status:p?"pass":"fail",message:p?`[features].hooks enabled in ${this.getSettingsPath()}`:h?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...p?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=s&&mp(o),c=a&&this.hasCodexPluginHookManifest(e);a&&!c&&r.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Qr(e,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"}),a&&Tb(o)&&r.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let u=this.readHooksConfig();if(!u.ok){if(u.reason==="missing"&&c){let p=Object.keys(i).map(h=>({check:`${h} hook`,status:"pass",message:`${h} hook provided by context-mode@context-mode plugin`}));return r.concat(p)}return u.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):u.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${u.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${u.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!u.config.hooks&&!c)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let l=c?Object.keys(i).map(p=>({check:`${p} hook`,status:"pass",message:`${p} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([p,h])=>{let m=u.config.hooks?.[p],f=h[0],g=Array.isArray(m)&&m.some(_=>this.isExpectedHookEntry(p,_,f)),y=p==="PreCompact"?"warn":"fail";return{check:`${p} hook`,status:g?"pass":y,message:g?`${p} hook configured in ${this.getHooksPath()}`:p==="PreCompact"?`${p} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${p} hook missing or not pointing to context-mode`,fix:g?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),d=[];for(let p of Object.keys(i)){let h=u.config.hooks?.[p];if(!Array.isArray(h))continue;let m=h.filter(f=>this.isManagedContextModeEntry(p,f)).length;m>1?d.push({check:`${p} duplicates`,status:"warn",message:`${m} context-mode entries found for ${p} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):c&&m===1&&d.push({check:`${p} plugin duplicate`,status:"warn",message:`${p} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return r.concat(l,d)}checkPluginRegistration(){try{let e=ms(this.getSettingsPath(),"utf-8"),r=mp(e),n=Tb(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:r?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o=this.getSettingsPath(),s="";try{s=ms(o,"utf-8")}catch{s=""}let i=mp(s)&&this.hasCodexPluginHookManifest(e),a;if(r.ok)a=r.config;else if(r.reason==="missing")a={hooks:{}};else if(r.reason==="invalid_json"){let h=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${h}`),a={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let c=a.hooks&&typeof a.hooks=="object"&&!Array.isArray(a.hooks)?a.hooks:{},u=this.generateHookConfig(e),l=n.length;if(i)for(let h of Object.keys(u))this.removeManagedHookEntries(c,h,n);else for(let[h,m]of Object.entries(u))this.upsertManagedHookEntry(c,h,m[0],n);n.length>l&&(a.hooks=c,this.writeHooksConfig(a),n.push(i?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let d=qO(s).text,p=d!==s;if(i){let h=Pb(d,f=>f==="mcp_servers.context-mode"||f.startsWith("mcp_servers.context-mode.tools."));h.removed.length>0&&(d=h.text,n.push("Removed standalone Codex context-mode MCP registration"));let m=this.pruneStaleUserHookTrustState(d,c);m.removed.length>0&&(d=m.text,n.push(`Removed ${m.removed.length} stale Codex hook trust entr${m.removed.length===1?"y":"ies"}`))}if(d!==s){let h=d.includes(`\r
|
|
157
|
+
`)?`\r
|
|
158
|
+
`:`
|
|
159
|
+
`,m=d.endsWith(`
|
|
160
|
+
`)?d:`${d}${h}`;dp(pp(o),{recursive:!0}),$b(o,m,"utf-8"),p&&n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{jO(r,zO.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=FO(pp(HO(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return ms(e,"utf-8")}catch{return`# context-mode
|
|
158
161
|
|
|
159
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return
|
|
160
|
-
`,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(oo[e]??""),s=
|
|
161
|
-
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=WO(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Oc(n,o);try{ZO(s,VO.R_OK),qO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Ox(t,e){if(!fp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,fp,E9,$9,Ix=S(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},fp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},E9=[Yt.PRE_TOOL_USE,Yt.SESSION_START],$9=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var Nx={};we(Nx,{VSCodeCopilotAdapter:()=>yp});import{readFileSync as hp,mkdirSync as Ax,accessSync as KO,existsSync as GO,constants as JO}from"node:fs";import{resolve as hs,join as Ai}from"node:path";import{homedir as gp}from"node:os";var yp,Dx=S(()=>{"use strict";mp();pt();Ix();yp=class extends fs{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:fp,buildHookCommand:Ox};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=Pt();if(e){let s=Ai(e,"context-mode","sessions");return Ax(s,{recursive:!0}),s}let r=hs(".github","context-mode","sessions"),n=Ai(gp(),".vscode","context-mode","sessions"),o=GO(hs(".github"))?r:n;return Ax(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=hs(".github","hooks");try{KO(n,JO.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=hs(n,"context-mode.json");try{let s=hp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),r=hp(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ai(gp(),".vscode","extensions"),Ai(gp(),".vscode-insiders","extensions")];for(let r of e)try{let n=hp(Ai(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function Mx(t,e){if(!_p[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,_p,N9,D9,jx=S(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},_p={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},N9=[Qt.PRE_TOOL_USE,Qt.SESSION_START],D9=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var Lx={};we(Lx,{JetBrainsCopilotAdapter:()=>bp});import{readFileSync as XO}from"node:fs";import{resolve as YO}from"node:path";var bp,zx=S(()=>{"use strict";mp();jx();bp=class extends fs{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:_p,buildHookCommand:Mx};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return YO(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=XO(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Ni(t,e){let r=xp[e],n=er(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function er(t){return`context-mode hook cursor ${t.toLowerCase()}`}var xe,xp,QO,eI,vp,Fx,Hx,Ux=S(()=>{"use strict";xe={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},xp={[xe.PRE_TOOL_USE]:"pretooluse.mjs",[xe.POST_TOOL_USE]:"posttooluse.mjs",[xe.SESSION_START]:"sessionstart.mjs",[xe.STOP]:"stop.mjs",[xe.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},QO="MCP:(?!ctx_)",eI=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",QO],vp=eI.join("|"),Fx=[xe.PRE_TOOL_USE],Hx=[xe.POST_TOOL_USE]});var Wx={};we(Wx,{CursorAdapter:()=>Sp});import{readFileSync as Ic,writeFileSync as tI,mkdirSync as rI,accessSync as Bx,chmodSync as nI,constants as Zx,existsSync as qx,readdirSync as oI}from"node:fs";import{execSync as sI}from"node:child_process";import{resolve as so,join as io}from"node:path";import{homedir as Ac}from"node:os";var Vx,Sp,Kx=S(()=>{"use strict";pt();kn();Ux();Vx="/Library/Application Support/Cursor/hooks.json",Sp=class extends be{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return so(".cursor","hooks.json")}getConfigDir(e){return so(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[xe.PRE_TOOL_USE]:[{type:"command",command:er(xe.PRE_TOOL_USE),matcher:vp,loop_limit:null,failClosed:!1}],[xe.POST_TOOL_USE]:[{type:"command",command:er(xe.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[xe.SESSION_START]:[{type:"command",command:er(xe.SESSION_START),loop_limit:null,failClosed:!1}],[xe.STOP]:[{type:"command",command:er(xe.STOP),loop_limit:null,failClosed:!1}],[xe.AFTER_AGENT_RESPONSE]:[{type:"command",command:er(xe.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ic(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();rI(so(".cursor"),{recursive:!0}),tI(r,JSON.stringify(e,null,2)+`
|
|
162
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of
|
|
162
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Qr(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return LO(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(ms(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();dp(pp(r),{recursive:!0}),$b(r,JSON.stringify(e,null,2)+`
|
|
163
|
+
`,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}removeManagedHookEntries(e,r,n){let o=Array.isArray(e[r])?[...e[r]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(r,a)),i=o.length-s.length;i!==0&&(s.length>0?e[r]=s:delete e[r],n.push(`Removed ${i} ${r} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return MO(Qr(e,".codex-plugin","hooks.json"))}pruneStaleUserHookTrustState(e,r){let n=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return Pb(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=VO(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==n||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=r[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(oo[e]??""),s=BO[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as Ab,writeFileSync as WO,mkdirSync as KO,accessSync as GO,chmodSync as JO,constants as XO}from"node:fs";import{resolve as Ic,join as YO}from"node:path";var fs,hp=S(()=>{"use strict";pt();fs=class extends xe{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return Ic(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=Ab(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=Ab(Ic(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();KO(Ic(".github","hooks"),{recursive:!0}),WO(r,JSON.stringify(e,null,2)+`
|
|
164
|
+
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=YO(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Ic(n,o);try{GO(s,XO.R_OK),JO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Nb(t,e){if(!gp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,gp,C9,O9,Db=S(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},gp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},C9=[Yt.PRE_TOOL_USE,Yt.SESSION_START],O9=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var jb={};we(jb,{VSCodeCopilotAdapter:()=>xp});import{readFileSync as yp,mkdirSync as Mb,accessSync as QO,existsSync as eI,constants as tI}from"node:fs";import{resolve as hs,join as Ai}from"node:path";import{homedir as _p}from"node:os";var xp,Lb=S(()=>{"use strict";hp();pt();Db();xp=class extends fs{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:gp,buildHookCommand:Nb};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=Pt();if(e){let s=Ai(e,"context-mode","sessions");return Mb(s,{recursive:!0}),s}let r=hs(".github","context-mode","sessions"),n=Ai(_p(),".vscode","context-mode","sessions"),o=eI(hs(".github"))?r:n;return Mb(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=hs(".github","hooks");try{QO(n,tI.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=hs(n,"context-mode.json");try{let s=yp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),r=yp(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ai(_p(),".vscode","extensions"),Ai(_p(),".vscode-insiders","extensions")];for(let r of e)try{let n=yp(Ai(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function zb(t,e){if(!bp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,bp,z9,F9,Fb=S(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},bp={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},z9=[Qt.PRE_TOOL_USE,Qt.SESSION_START],F9=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var Hb={};we(Hb,{JetBrainsCopilotAdapter:()=>vp});import{readFileSync as rI}from"node:fs";import{resolve as nI}from"node:path";var vp,Ub=S(()=>{"use strict";hp();Fb();vp=class extends fs{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:bp,buildHookCommand:zb};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return nI(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=rI(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Ni(t,e){let r=Sp[e],n=er(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function er(t){return`context-mode hook cursor ${t.toLowerCase()}`}var be,Sp,oI,sI,kp,Bb,Zb,qb=S(()=>{"use strict";be={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Sp={[be.PRE_TOOL_USE]:"pretooluse.mjs",[be.POST_TOOL_USE]:"posttooluse.mjs",[be.SESSION_START]:"sessionstart.mjs",[be.STOP]:"stop.mjs",[be.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},oI="MCP:(?!ctx_)",sI=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",oI],kp=sI.join("|"),Bb=[be.PRE_TOOL_USE],Zb=[be.POST_TOOL_USE]});var Jb={};we(Jb,{CursorAdapter:()=>wp});import{readFileSync as Ac,writeFileSync as iI,mkdirSync as aI,accessSync as Vb,chmodSync as cI,constants as Wb,existsSync as Kb,readdirSync as uI}from"node:fs";import{execSync as lI}from"node:child_process";import{resolve as so,join as io}from"node:path";import{homedir as Nc}from"node:os";var Gb,wp,Xb=S(()=>{"use strict";pt();wn();qb();Gb="/Library/Application Support/Cursor/hooks.json",wp=class extends xe{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return so(".cursor","hooks.json")}getConfigDir(e){return so(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[be.PRE_TOOL_USE]:[{type:"command",command:er(be.PRE_TOOL_USE),matcher:kp,loop_limit:null,failClosed:!1}],[be.POST_TOOL_USE]:[{type:"command",command:er(be.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[be.SESSION_START]:[{type:"command",command:er(be.SESSION_START),loop_limit:null,failClosed:!1}],[be.STOP]:[{type:"command",command:er(be.STOP),loop_limit:null,failClosed:!1}],[be.AFTER_AGENT_RESPONSE]:[{type:"command",command:er(be.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ac(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();aI(so(".cursor"),{recursive:!0}),iI(r,JSON.stringify(e,null,2)+`
|
|
165
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of Bb){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ni(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of Zb){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ni(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}Kb(Gb)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Ni(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[io(Nc(),".cursor","plugins","local"),io(Nc(),".cursor","plugins","cache")],r=[];for(let n of e){try{Vb(n,Wb.F_OK)}catch{continue}let o=[];try{o=uI(n)}catch{continue}for(let s of o){let i=io(n,s,".cursor-plugin","plugin.json");try{let a=Ac(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[so(".cursor","mcp.json"),io(Nc(),".cursor","mcp.json")];for(let n of e)try{let o=Ac(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return lI("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,be.PRE_TOOL_USE,{type:"command",command:er(be.PRE_TOOL_USE),matcher:kp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,be.POST_TOOL_USE,{type:"command",command:er(be.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,be.SESSION_START,{type:"command",command:er(be.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,be.STOP,{type:"command",command:er(be.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,be.AFTER_AGENT_RESPONSE,{type:"command",command:er(be.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=io(e,"hooks","cursor");for(let o of Object.values(Sp)){let s=so(n,o);try{Vb(s,Wb.R_OK),cI(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),io(Nc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Gb),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ac(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[so(".claude","settings.json"),so(".claude","settings.local.json"),io(qe(),"settings.json")].some(r=>Kb(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Ni(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var Qb={};we(Qb,{AntigravityAdapter:()=>$p});import{readFileSync as Dc,writeFileSync as dI,mkdirSync as pI}from"node:fs";import{resolve as Mc,dirname as Yb}from"node:path";import{fileURLToPath as mI}from"node:url";import{homedir as Ep}from"node:os";var $p,ev=S(()=>{"use strict";pt();$p=class extends xe{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Mc(Ep(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Mc(Ep(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Dc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();pI(Yb(r),{recursive:!0}),dI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Dc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Mc(Ep(),".gemini","extensions","context-mode","package.json");return JSON.parse(Dc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Mc(Yb(mI(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Dc(e,"utf-8")}catch{return`# context-mode
|
|
163
166
|
|
|
164
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function
|
|
167
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function jc(t,e){let r=tv[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function gs(t,e){let r=tv[t];return e&&r?Xe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var He,tv,fI,hI,Tp,aV,cV,rv=S(()=>{"use strict";Cr();He={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},tv={[He.PRE_TOOL_USE]:"pretooluse.mjs",[He.POST_TOOL_USE]:"posttooluse.mjs",[He.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[He.AGENT_SPAWN]:"agentspawn.mjs"},fI="@(?!context-mode/)",hI=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",fI],Tp=hI.join("|"),aV=[He.PRE_TOOL_USE,He.AGENT_SPAWN],cV=[He.POST_TOOL_USE,He.USER_PROMPT_SUBMIT]});var iv={};we(iv,{KiroAdapter:()=>Pp});import{readFileSync as ys,writeFileSync as nv,mkdirSync as ov}from"node:fs";import{resolve as ao,dirname as sv}from"node:path";import{fileURLToPath as gI}from"node:url";import{homedir as Lc}from"node:os";var Pp,av=S(()=>{"use strict";pt();rv();Pp=class extends xe{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return ao(Lc(),".kiro","settings","mcp.json")}getConfigDir(e){return ao(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[He.PRE_TOOL_USE]:[{matcher:Tp,hooks:[{type:"command",command:gs(He.PRE_TOOL_USE,e)}]}],[He.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:gs(He.POST_TOOL_USE,e)}]}],[He.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:gs(He.AGENT_SPAWN,e)}]}],[He.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:gs(He.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ys(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();ov(sv(r),{recursive:!0}),nv(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=ao(Lc(),".kiro","agents","default.json");try{let s=JSON.parse(ys(n,"utf-8")).hooks??{};for(let i of[He.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>jc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[He.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>jc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=ys(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=ao(Lc(),".kiro","extensions","context-mode","package.json");return JSON.parse(ys(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=ao(Lc(),".kiro","agents"),o=ao(n,"default.json");try{ov(n,{recursive:!0});let s={};try{s=JSON.parse(ys(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[He.PRE_TOOL_USE,Tp],[He.POST_TOOL_USE,"*"],[He.AGENT_SPAWN,"*"],[He.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>jc(d,c))||(l.push({matcher:u,command:gs(c,e)}),i[c]=l,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,nv(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=ao(sv(gI(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ys(e,"utf-8")}catch{return`# context-mode
|
|
165
168
|
|
|
166
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var
|
|
169
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var lv={};we(lv,{ZedAdapter:()=>Cp});import{readFileSync as Rp,writeFileSync as yI,mkdirSync as _I}from"node:fs";import{resolve as cv,dirname as uv}from"node:path";import{fileURLToPath as xI}from"node:url";import{homedir as bI}from"node:os";var Cp,dv=S(()=>{"use strict";pt();Cp=class extends xe{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return cv(bI(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Rp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();_I(uv(r),{recursive:!0}),yI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Rp(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=cv(uv(xI(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Rp(e,"utf-8")}catch{return`# context-mode
|
|
167
170
|
|
|
168
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
171
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var Op,pv=S(()=>{"use strict";Op="mcp__(?!.*context-mode)"});var hv={};we(hv,{QwenCodeAdapter:()=>Ip});import{readFileSync as vI,writeFileSync as SI,existsSync as kI}from"node:fs";import{resolve as mv,join as wI}from"node:path";import{homedir as fv}from"node:os";var Ip,gv=S(()=>{"use strict";Kd();pv();Cr();Ip=class extends ls{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return mv(fv(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",Op].join("|"),hooks:[{type:"command",command:Xe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Xe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Xe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=vI(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){SI(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let f=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?kI(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",Op].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Xe(`${e}/hooks/${a}`)}]},l=n[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),n[i]=l}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:mv(wI(fv(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var yv={};we(yv,{OMPAdapter:()=>Dp});import{readFileSync as Ap,writeFileSync as EI,mkdirSync as $I}from"node:fs";import{resolve as Np,dirname as TI}from"node:path";import{homedir as PI}from"node:os";var Dp,_v=S(()=>{"use strict";pt();Dp=class extends xe{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??Np(PI(),".omp","agent")}getSettingsPath(){return Np(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ap(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();$I(TI(r),{recursive:!0}),EI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=Ap(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=Np(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Ap(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
169
172
|
|
|
170
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var
|
|
173
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var xv={};we(xv,{PiAdapter:()=>zp});import{readFileSync as Mp,writeFileSync as RI,mkdirSync as CI}from"node:fs";import{resolve as jp,dirname as OI}from"node:path";import{homedir as Lp}from"node:os";var zp,bv=S(()=>{"use strict";pt();zp=class extends xe{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return jp(Lp(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Mp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();CI(OI(r),{recursive:!0}),RI(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=jp(Lp(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Mp(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=jp(Lp(),".pi","extensions","context-mode","package.json");return JSON.parse(Mp(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
171
174
|
|
|
172
|
-
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as
|
|
173
|
-
`)}function
|
|
175
|
+
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as vv}from"node:os";import{resolve as Fp}from"node:path";function Sv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Fp(vv(),t.replace(/^~[/\\]?/,"")):Fp(t):Fp(vv(),".kimi-code")}var kv=S(()=>{"use strict"});var Pv={};we(Pv,{KimiAdapter:()=>Up,probeKimiCliVersion:()=>Tv});import{execFileSync as II}from"node:child_process";import{readFileSync as Di,writeFileSync as AI,accessSync as NI,copyFileSync as DI,constants as MI,mkdirSync as wv}from"node:fs";import{resolve as jI,dirname as Ev,join as co}from"node:path";import{fileURLToPath as LI}from"node:url";function Tv(t=II){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function $v(t){let e=[],r=t.split(/\r?\n/),n=null;for(let o of r){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){n&&n.event&&n.command&&e.push(n),n={};continue}if(!n)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?n[i]=a:c!==void 0&&(n[i]=Number(c))}}return n&&n.event&&n.command&&e.push(n),e}function HI(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
|
|
176
|
+
`)}function Hp(t){return t.command.includes("context-mode hook kimi")}function UI(t,e){let r=(e.hooks?.[0]?.command??"").trim();return r?{event:t,matcher:e.matcher||void 0,command:r,timeout:30}:null}var zI,$n,FI,Up,Rv=S(()=>{"use strict";pt();Jt();kv();zI="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",$n={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},FI={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};Up=class extends xe{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,o=(r.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Sv()}getSettingsPath(){return co(this.getConfigDir(),"config.toml")}getMcpPath(){return co(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=Pt(),r=e?co(e,"context-mode","sessions"):co(this.getConfigDir(),"context-mode","sessions");return wv(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Pt(),n=r?co(r,"context-mode","memory"):co(this.getConfigDir(),"memory");return e?co(n,nt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:zI,hooks:[{type:"command",command:$n.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:$n.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:$n.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:$n.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:$n.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:$n.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:$n.Stop}]}]}}readSettings(){try{return{_raw_toml:Di(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Tv();r.push({check:"Kimi Code CLI binary",status:n?"pass":"warn",message:n?`kimi --version resolved to ${n}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...n?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Di(this.getSettingsPath(),"utf-8")}catch{return r.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),r}let s=$v(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(p=>p.event===a&&this.isExpectedHookEntry(a,p,u)),d=a==="PreCompact"?"warn":"fail";r.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&Hp(u)).length;c>1&&r.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r}checkPluginRegistration(){try{let e=Di(this.getMcpPath(),"utf-8"),r=JSON.parse(e),n=e.includes("context-mode"),o=r.mcpServers!==void 0||r.mcp_servers!==void 0;return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=[],n=this.generateHookConfig(""),o="";try{o=Di(this.getSettingsPath(),"utf-8")}catch{o=""}let s=$v(o),i=s.filter(l=>!Hp(l)),a=[];for(let[l,d]of Object.entries(n)){let p=UI(l,d[0]);p&&a.push(p)}let c=s.some(Hp),u=this.rebuildToml(o,i,a);return u!==o&&(wv(Ev(this.getSettingsPath()),{recursive:!0}),AI(this.getSettingsPath(),u,"utf-8"),c?r.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):r.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),r}backupSettings(){let e=null;for(let r of[this.getSettingsPath(),this.getMcpPath()])try{NI(r,MI.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=jI(Ev(LI(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Di(e,"utf-8")}catch{return`# context-mode
|
|
174
177
|
|
|
175
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return
|
|
176
|
-
`)}}});var Lc={};we(Lc,{PLATFORM_ENV_VARS:()=>_s,__resetClaudeCodePluginCacheForTests:()=>FI,__seedClaudeCodePluginCacheMissForTests:()=>HI,detectPlatform:()=>vt,foreignIdentificationEnv:()=>qI,foreignWorkspaceEnv:()=>ZI,getAdapter:()=>bs,getEnvVarNames:()=>BI,getSessionDirSegments:()=>Mi,workspaceEnvVarsFor:()=>Hp});import{existsSync as Rt,readFileSync as LI}from"node:fs";import{resolve as xt}from"node:path";import{homedir as Tv}from"node:os";function zI(){if(uo!==null)return uo!=="miss"&&uo.hasCM;try{let t=xt(Tv(),".claude","plugins","installed_plugins.json"),e=LI(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return uo={hasCM:o},o}catch{return uo="miss",!1}}function FI(){uo=null}function HI(){uo="miss"}function BI(t){return(_s.get(t)??[]).map(e=>e.name)}function Hp(t){return(_s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function ZI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function qI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Mi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function vt(t){if(t?.name){let n=Ib[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of _s)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&zI()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Tv();return Rt(xt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Rt(xt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Rt(xt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Rt(xt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Rt(xt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Rt(xt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Rt(xt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Rt(xt(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Rt(xt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Rt(xt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Rt(xt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Rt(xt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Rt(xt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Rt(xt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function bs(t){let e=t??vt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(tp(),ep));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(mx(),px));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(yx(),gx));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(xx(),bx));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Rx(),Px));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(Dx(),Nx));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(zx(),Lx));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Kx(),Wx));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Xx(),Jx));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(ov(),nv));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(cv(),av));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(mv(),pv));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(hv(),fv));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(yv(),gv));return new r}case"kimi":{let{KimiAdapter:r}=await Promise.resolve().then(()=>($v(),Ev));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(tp(),ep));return new r}}}var uo,UI,_s,$n=S(()=>{"use strict";Ab();uo=null;UI=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],_s=new Map(UI)});import{resolve as ji}from"node:path";import{homedir as Up}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?ji(Up(),e.replace(/^~[/\\]?/,"")):ji(e):ji(Up(),".claude")}function VI(t=process.env){return ji(qe(t),"settings.json")}function Bp(t=process.env){let e=[],r=vt();if(r.platform!=="claude-code"){let o=Mi(r.platform);o&&o.length>0&&e.push(ji(Up(),...o,"settings.json"))}let n=VI(t);return e.includes(n)||e.push(n),e}var kn=S(()=>{"use strict";$n()});import{readdirSync as WI,statSync as KI,lstatSync as GI,realpathSync as Pv,existsSync as JI,readFileSync as XI}from"node:fs";import{join as Cv,extname as YI,relative as Ov,sep as QI,resolve as eA}from"node:path";function sA(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function Rv(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=sA(n);if(o.test(t)||o.test(r))return!0}return!1}function iA(t){let e=Cv(t,".gitignore");if(!JI(e))return[];try{return XI(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function aA(t,e){return Ov(t,e).split(QI).join("/")}function Iv(t,e={}){let{include:r,exclude:n,maxDepth:o=nA,maxFiles:s=oA,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Pv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:rA).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...tA,...n??[],...a?iA(u):[]],m=r??[],h=[],p=new Set([u]),f=0,g=!1;function y(_,b){if(g||b>o)return;let v;try{v=WI(_,{withFileTypes:!0})}catch{return}for(let E of v){if(g)return;let C=Cv(_,E.name),x=aA(u,C);if(Rv(x,d))continue;let k=E.isDirectory(),P=E.isFile(),N=!1;try{N=GI(C).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let O;try{O=Pv(C)}catch{continue}let F=Ov(u,O);if((F.startsWith("..")||eA(F)===O)&&F.startsWith("..")||p.has(O))continue;p.add(O);try{let K=KI(O);k=K.isDirectory(),P=K.isFile()}catch{continue}}if(k){y(C,b+1);continue}if(!P)continue;let R=YI(C).toLowerCase();if(l.includes(R)&&!(m.length>0&&!Rv(x,m))){if(f++,h.length>=s){g=!0;return}h.push(C)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var tA,rA,nA,oA,Av=S(()=>{"use strict";tA=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],rA=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],nA=5,oA=200});import{readFileSync as Nv,readdirSync as Fv,unlinkSync as qp,existsSync as Zp,statSync as zc,openSync as Dv,fstatSync as Mv,closeSync as jv}from"node:fs";import{createHash as Lv}from"node:crypto";import{tmpdir as Hv}from"node:os";import{join as Vp}from"node:path";function Uv(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function cA(t,e="AND"){let r=Uv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!xs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function uA(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=Uv(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!xs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function lA(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function dA(t){return t<=4?1:t<=12?2:3}function Wp(){let t=Hv(),e=0;try{let r=Fv(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Vp(t,n);for(let a of["","-wal","-shm"])try{qp(i+a)}catch{}e++}}}catch{}return e}function Kp(t,e){let r=0;try{if(!Zp(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Fv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Vp(t,s),c=zc(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Zp(u))try{let l=zc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{qp(i+u)}catch{}r++}}catch{}}catch{}return r}function pA(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function mA(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,m=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function fA(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var xs,zv,vs,Gp=S(()=>{"use strict";bn();Av();xs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);zv=4096;vs=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#b;#x;#v;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=rt();this.#t=e??Vp(Hv(),`context-mode-${process.pid}.db`),ts(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){vc(this.#t),ts(this.#t);try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#U(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{qp(this.#t+e)}catch{}}#U(){this.#e.exec(`
|
|
178
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return DI(e,n),n}isExpectedHookEntry(e,r,n){return e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(r.command??"").replace(/\\/g,"/"),o=($n[e]??"").replace(/\\/g,"/"),s=FI[e]??[];return n.includes(o)||s.some(i=>n.includes(i))}rebuildToml(e,r,n){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...r,...n];if(a.length>0)for(let c of a)s.push(HI(c)),s.push("");return s.join(`
|
|
179
|
+
`)}}});var zc={};we(zc,{PLATFORM_ENV_VARS:()=>_s,__resetClaudeCodePluginCacheForTests:()=>qI,__seedClaudeCodePluginCacheMissForTests:()=>VI,detectPlatform:()=>vt,foreignIdentificationEnv:()=>JI,foreignWorkspaceEnv:()=>GI,getAdapter:()=>xs,getEnvVarNames:()=>KI,getSessionDirSegments:()=>Mi,workspaceEnvVarsFor:()=>Bp});import{existsSync as Rt,readFileSync as BI}from"node:fs";import{resolve as bt}from"node:path";import{homedir as Cv}from"node:os";function ZI(){if(uo!==null)return uo!=="miss"&&uo.hasCM;try{let t=bt(Cv(),".claude","plugins","installed_plugins.json"),e=BI(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return uo={hasCM:o},o}catch{return uo="miss",!1}}function qI(){uo=null}function VI(){uo="miss"}function KI(t){return(_s.get(t)??[]).map(e=>e.name)}function Bp(t){return(_s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function GI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function JI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Mi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function vt(t){if(t?.name){let n=Nx[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of _s)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&ZI()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Cv();return Rt(bt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Rt(bt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Rt(bt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Rt(bt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Rt(bt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Rt(bt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Rt(bt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Rt(bt(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Rt(bt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Rt(bt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Rt(bt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Rt(bt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Rt(bt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Rt(bt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function xs(t){let e=t??vt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(rp(),tp));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(hb(),fb));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(xb(),_b));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(Sb(),vb));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Ib(),Ob));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(Lb(),jb));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(Ub(),Hb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Xb(),Jb));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(ev(),Qb));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(av(),iv));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(dv(),lv));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(gv(),hv));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(_v(),yv));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(bv(),xv));return new r}case"kimi":{let{KimiAdapter:r}=await Promise.resolve().then(()=>(Rv(),Pv));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(rp(),tp));return new r}}}var uo,WI,_s,Tn=S(()=>{"use strict";Dx();uo=null;WI=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],_s=new Map(WI)});import{resolve as ji}from"node:path";import{homedir as Zp}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?ji(Zp(),e.replace(/^~[/\\]?/,"")):ji(e):ji(Zp(),".claude")}function XI(t=process.env){return ji(qe(t),"settings.json")}function qp(t=process.env){let e=[],r=vt();if(r.platform!=="claude-code"){let o=Mi(r.platform);o&&o.length>0&&e.push(ji(Zp(),...o,"settings.json"))}let n=XI(t);return e.includes(n)||e.push(n),e}var wn=S(()=>{"use strict";Tn()});import{readdirSync as YI,statSync as QI,lstatSync as eA,realpathSync as Ov,existsSync as tA,readFileSync as rA}from"node:fs";import{join as Av,extname as nA,relative as Nv,sep as oA,resolve as sA}from"node:path";function lA(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function Iv(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=lA(n);if(o.test(t)||o.test(r))return!0}return!1}function dA(t){let e=Av(t,".gitignore");if(!tA(e))return[];try{return rA(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function pA(t,e){return Nv(t,e).split(oA).join("/")}function Dv(t,e={}){let{include:r,exclude:n,maxDepth:o=cA,maxFiles:s=uA,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Ov(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:aA).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...iA,...n??[],...a?dA(u):[]],p=r??[],h=[],m=new Set([u]),f=0,g=!1;function y(_,x){if(g||x>o)return;let v;try{v=YI(_,{withFileTypes:!0})}catch{return}for(let E of v){if(g)return;let C=Av(_,E.name),b=pA(u,C);if(Iv(b,d))continue;let k=E.isDirectory(),P=E.isFile(),N=!1;try{N=eA(C).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let O;try{O=Ov(C)}catch{continue}let F=Nv(u,O);if((F.startsWith("..")||sA(F)===O)&&F.startsWith("..")||m.has(O))continue;m.add(O);try{let K=QI(O);k=K.isDirectory(),P=K.isFile()}catch{continue}}if(k){y(C,x+1);continue}if(!P)continue;let R=nA(C).toLowerCase();if(l.includes(R)&&!(p.length>0&&!Iv(b,p))){if(f++,h.length>=s){g=!0;return}h.push(C)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var iA,aA,cA,uA,Mv=S(()=>{"use strict";iA=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],aA=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],cA=5,uA=200});import{readFileSync as jv,readdirSync as Bv,unlinkSync as Wp,existsSync as Vp,statSync as Fc,openSync as Lv,fstatSync as zv,closeSync as Fv}from"node:fs";import{createHash as Hv}from"node:crypto";import{tmpdir as Zv}from"node:os";import{join as Kp}from"node:path";function qv(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function mA(t,e="AND"){let r=qv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!bs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function fA(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=qv(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!bs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function hA(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function gA(t){return t<=4?1:t<=12?2:3}function Gp(){let t=Zv(),e=0;try{let r=Bv(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Kp(t,n);for(let a of["","-wal","-shm"])try{Wp(i+a)}catch{}e++}}}catch{}return e}function Jp(t,e){let r=0;try{if(!Vp(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Bv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Kp(t,s),c=Fc(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Vp(u))try{let l=Fc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Wp(i+u)}catch{}r++}}catch{}}catch{}return r}function yA(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function _A(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,p=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(n++,u++)}}return n}function xA(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var bs,Uv,vs,Xp=S(()=>{"use strict";bn();Mv();bs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);Uv=4096;vs=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#b;#v;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=rt();this.#t=e??Kp(Zv(),`context-mode-${process.pid}.db`),ts(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){vc(this.#t),ts(this.#t);try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#U(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Wp(this.#t+e)}catch{}}#U(){this.#e.exec(`
|
|
177
180
|
CREATE TABLE IF NOT EXISTS sources (
|
|
178
181
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
179
182
|
label TEXT NOT NULL,
|
|
@@ -311,7 +314,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
311
314
|
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
312
315
|
ORDER BY rank
|
|
313
316
|
LIMIT ?
|
|
314
|
-
`),this.#
|
|
317
|
+
`),this.#x=this.#e.prepare(`
|
|
315
318
|
SELECT
|
|
316
319
|
chunks_trigram.title,
|
|
317
320
|
chunks_trigram.content,
|
|
@@ -416,7 +419,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
416
419
|
WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
|
|
417
420
|
ORDER BY rank
|
|
418
421
|
LIMIT ?
|
|
419
|
-
`),this.#
|
|
422
|
+
`),this.#b=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#T=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
|
|
420
423
|
FROM chunks c
|
|
421
424
|
JOIN sources s ON s.id = c.source_id
|
|
422
425
|
WHERE c.source_id = ?
|
|
@@ -425,61 +428,61 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
425
428
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
426
429
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
427
430
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
428
|
-
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let
|
|
431
|
+
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let p=Lv(n,"r");try{if(!zv(p).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=jv(p,"utf-8")}finally{Fv(p)}}let c=o??n??"untitled",u=this.#W(a),l=n??void 0,d=l?Hv("sha256").update(a).digest("hex"):void 0;return xn(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:r,source:n,attribution:o,perFileDeny:s,...i}=e,a=Dv(r,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let h=n?`${n}:${p}`:p,m=this.index({path:p,source:h,attribution:o});c++,u+=m.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:n??r}}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#K(e,n);return xn(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=Uv,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#H(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):xn(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(p=>p.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let f=this.#s.run(r,o??null,s??null);return Number(f.lastInsertRowid)}let p=this.#o.run(r,e.length,a,o??null,s??null),h=Number(p.lastInsertRowid),m=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,m),this.#c.run(f.title,f.content,h,g,null,c,u,m)}return h})();return n&&this.#V(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:d,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0,sessionId:r.session_id??""}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=mA(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#v,u=[a,s,r]):(c=this.#f,u=[a,r]),xn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=fA(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#x:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#w,u=[a,s,r]):(c=this.#y,u=[a,r]),xn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=gA(r.length),o=this.#b.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let l=hA(r,u);l<i&&(i=l,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#L(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,h]of c.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}for(let[p,h]of u.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,h)=>h.score-p.score).slice(0,r).map(({result:p,score:h})=>({...p,rank:-h}))}#z(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!bs.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let h=i.content.toLowerCase(),m=s.map(f=>yA(h,f));if(!m.some(f=>f.length===0)){d=1/(1+xA(m)/Math.max(h.length,1));let g=_A(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like",i){this.#q();let a=i?Math.max(r*8,40):r,c=this.#Z(i),u=this.#L(e,a,n,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#z(l.slice(0,r),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(f=>f.length>=3&&!bs.has(f)),p=d.join(" "),m=d.map(f=>this.fuzzyCorrect(f)??f).join(" ");if(m!==p){let f=this.#L(m,a,n,o,s),g=c?f.filter(c):f;if(g.length>0)return this.#z(g.slice(0,r),m).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#Z(e){return e?r=>{let n=r.sessionId??"";return n===""||e.has(n)}:null}lastRefreshCount=0;#q(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!Vp(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Fc(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=Lv(r.file_path,"r"),i;try{if(!zv(s).isFile())continue;i=jv(s,"utf-8")}finally{Fv(s)}if(Hv("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getIndexState(){let e=this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#C.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!bs.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),h=Math.min(l.length/20,.5),m=/[_]/.test(l),f=l.length>=12,g=m?1.5:f?.8:0;return{word:l,score:p+h+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return Fc(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),rs(this.#e)}#V(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!bs.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#W(e,r=Uv){let n=[],o=e.split(`
|
|
429
432
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
430
|
-
`).trim();if(l.length===0)return;let d=this.#Y(s,a),
|
|
433
|
+
`).trim();if(l.length===0)return;let d=this.#Y(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:p}),i=[];return}let h=l.split(/\n\n+/),m=[],f=1,g=()=>{if(m.length===0)return;let y=m.join(`
|
|
431
434
|
|
|
432
|
-
`).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,n.push({title:_,content:y,hasCode:y.includes("```")}),
|
|
435
|
+
`).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,n.push({title:_,content:y,hasCode:y.includes("```")}),m=[]};for(let y of h){m.push(y);let _=m.join(`
|
|
433
436
|
|
|
434
|
-
`);Buffer.byteLength(_)>r&&
|
|
437
|
+
`);Buffer.byteLength(_)>r&&m.length>1&&(m.pop(),g(),m=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let h=d[1].length,m=d[2].trim();for(;s.length>0&&s[s.length-1].level>=h;)s.pop();s.push({level:h,text:m}),a=m,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let h=p[1],m=[l];for(u++;u<o.length;){if(m.push(o[u]),o[u].startsWith(h)&&o[u].trim()===h){u++;break}u++}i.push(...m);continue}i.push(l),u++}return c(),n}#K(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
|
|
435
438
|
`)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
|
|
436
|
-
`);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),
|
|
437
|
-
`)})}return s}#H(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#H(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#X(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#J(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#X(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#J(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});import{readFileSync as
|
|
438
|
-
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function
|
|
439
|
-
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function
|
|
440
|
-
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function
|
|
441
|
-
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function LA({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!Qr(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=Ss(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(n)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=St(r),c=a+mo,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let m=l.args[d];if(typeof m!="string")continue;let h=m.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let p=h.slice(i.length+1),f=p.indexOf("/");if(f<0)continue;let g=p.slice(f+1),y=St(r,g);y!==a&&!(y+mo).startsWith(c)||y!==m&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Fi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function Hc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=St(t);if(!Qr(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=St(n,o,s),a=n+mo;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!Qr(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=IA(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let l=St(i,u);if(!l.startsWith(i+mo))continue;try{if(!NA(l).isDirectory())continue}catch{continue}let d=St(l,".mcp.json");if(Qr(d))try{AA(d),r.push(d)}catch{}}return{removed:r}}var zi,em=S(()=>{"use strict";zi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,tm,z,Nr,Hi=S(()=>{(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})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tm||(tm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Nr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var A,HA,Ct,Uc=S(()=>{Hi();A=ce.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"]),HA=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ct=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,ce.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()}};Ct.create=t=>new Ct(t)});var UA,en,rm=S(()=>{Uc();Hi();UA=(t,e)=>{let r;switch(t.code){case A.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case A.invalid_union:r="Invalid input";break;case A.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case A.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:r="Invalid function arguments";break;case A.invalid_return_type:r="Invalid function return type";break;case A.invalid_date:r="Invalid date";break;case A.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}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case A.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 A.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 A.custom:r="Invalid input";break;case A.invalid_intersection_types:r="Intersection results could not be merged";break;case A.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},en=UA});function BA(t){Xv=t}function ks(){return Xv}var Xv,Bc=S(()=>{rm();Xv=en});function j(t,e){let r=ks(),n=Ui({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===en?void 0:en].filter(o=>!!o)});t.common.issues.push(n)}var Ui,ZA,st,J,fo,mt,Zc,qc,Tn,ws,nm=S(()=>{Bc();rm();Ui=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}},ZA=[];st=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),fo=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Zc=t=>t.status==="aborted",qc=t=>t.status==="dirty",Tn=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var Yv=S(()=>{});var B,Qv=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(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}}function nS(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 aN(t){return new RegExp(`^${nS(t)}$`)}function oS(t){let e=`${rS}T${nS(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 cN(t,e){return!!((e==="v4"||!e)&&eN.test(t)||(e==="v6"||!e)&&rN.test(t))}function uN(t,e){if(!JA.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 lN(t,e){return!!((e==="v4"||!e)&&tN.test(t)||(e==="v6"||!e)&&nN.test(t))}function dN(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 Es(t){if(t instanceof It){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ot.create(Es(n))}return new It({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:Es(t.element)}):t instanceof Ot?Ot.create(Es(t.unwrap())):t instanceof Mr?Mr.create(Es(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Es(e))):t}function sm(t,e){let r=Nr(t),n=Nr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=sm(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=sm(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function sS(t,e){return new Eo({values:t,typeName:D.ZodEnum,...te(e)})}function tS(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function iS(t,e={},r){return t?Rn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=tS(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=tS(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rn.create()}var tr,eS,ne,qA,VA,WA,KA,GA,JA,XA,YA,QA,om,eN,tN,rN,nN,oN,sN,rS,iN,Pn,ho,go,yo,_o,$s,bo,xo,Rn,rn,hr,Ts,nn,It,vo,tn,Vc,So,Dr,Wc,Ps,Rs,Kc,ko,wo,Eo,$o,Cn,rr,Ot,Mr,To,Po,Cs,pN,Bi,Zi,Ro,mN,D,fN,aS,cS,hN,gN,uS,yN,_N,bN,xN,vN,SN,kN,wN,EN,im,$N,TN,PN,RN,CN,ON,IN,AN,NN,DN,MN,jN,LN,zN,FN,HN,UN,BN,ZN,qN,VN,WN,KN,GN,lS=S(()=>{Uc();Bc();Qv();nm();Hi();tr=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}},eS=(t,e)=>{if(Tn(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 Ct(t.common.issues);return this._error=r,this._error}}};ne=class{get description(){return this._def.description}_getType(e){return Nr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ws(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:Nr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return eS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Tn(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=>Tn(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:Nr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ws(o)?o:Promise.resolve(o));return eS(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:A.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 rr({schema:this,typeName:D.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 Ot.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return Cn.create(this,this._def)}or(e){return vo.create([this,e],this._def)}and(e){return So.create(this,e,this._def)}transform(e){return new rr({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new To({...te(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Bi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zi.create(this,e)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qA=/^c[^\s-]{8,}$/i,VA=/^[0-9a-z]+$/,WA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,KA=/^[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,GA=/^[a-z0-9_-]{21}$/i,JA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XA=/^[-+]?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)?)??$/,YA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,QA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",eN=/^(?:(?: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])$/,tN=/^(?:(?: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])$/,rN=/^(([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]))$/,nN=/^(([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])$/,oN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rS="((\\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])))",iN=new RegExp(`^${rS}$`);Pn=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.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),j(o,{code:A.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?j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")YA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"email",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")om||(om=new RegExp(QA,"u")),om.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"emoji",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")KA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"uuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")GA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"nanoid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")qA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")VA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid2",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")WA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ulid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),j(o,{validation:"url",code:A.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),j(o,{validation:"regex",code:A.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),j(o,{code:A.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),j(o,{code:A.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?oS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?iN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?aN(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?XA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"duration",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ip",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?uN(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"jwt",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?lN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cidr",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?oN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?sN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64url",code:A.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:A.invalid_string,...B.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...B.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...B.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...B.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...B.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...B.errToObj(r)})}nonempty(e){return this.min(1,B.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}};Pn.create=t=>new Pn({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});ho=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.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),j(n,{code:A.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),j(n,{code:A.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?dN(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.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"&&ce.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)}};ho.create=t=>new ho({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});go=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new st;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),j(n,{code:A.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),j(n,{code:A.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),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.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}};go.create=t=>new go({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});yo=class extends ne{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};yo.create=t=>new yo({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});_o=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_date}),J}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.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),j(o,{code:A.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.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:B.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:B.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}};_o.create=t=>new _o({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});$s=class extends ne{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};$s.create=t=>new $s({typeName:D.ZodSymbol,...te(t)});bo=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};bo.create=t=>new bo({typeName:D.ZodUndefined,...te(t)});xo=class extends ne{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};xo.create=t=>new xo({typeName:D.ZodNull,...te(t)});Rn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Rn.create=t=>new Rn({typeName:D.ZodAny,...te(t)});rn=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};rn.create=t=>new rn({typeName:D.ZodUnknown,...te(t)});hr=class extends ne{_parse(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.never,received:r.parsedType}),J}};hr.create=t=>new hr({typeName:D.ZodNever,...te(t)});Ts=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ts.create=t=>new Ts({typeName:D.ZodVoid,...te(t)});nn=class t extends ne{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return j(r,{code:A.invalid_type,expected:z.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(j(r,{code:i?A.too_big:A.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&&(j(r,{code:A.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&&(j(r,{code:A.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 tr(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new tr(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:B.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:B.toString(r)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});It=class t extends ne{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=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return j(u,{code:A.invalid_type,expected:z.object,received:u.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hr&&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 tr(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof hr){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&&(j(o,{code:A.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 tr(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=>st.mergeObjectSync(n,u)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return B.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:B.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:D.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 ce.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 ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Es(this)}partial(e){let r={};for(let n of ce.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 ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return sS(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});vo=class extends ne{_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 Ct(a.ctx.common.issues));return j(r,{code:A.invalid_union,unionErrors:i}),J}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 Ct(c));return j(r,{code:A.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};vo.create=(t,e)=>new vo({options:t,typeName:D.ZodUnion,...te(e)});tn=t=>t instanceof ko?tn(t.schema):t instanceof rr?tn(t.innerType()):t instanceof wo?[t.value]:t instanceof Eo?t.options:t instanceof $o?ce.objectValues(t.enum):t instanceof To?tn(t._def.innerType):t instanceof bo?[void 0]:t instanceof xo?[null]:t instanceof Ot?[void 0,...tn(t.unwrap())]:t instanceof Mr?[null,...tn(t.unwrap())]:t instanceof Bi||t instanceof Ro?tn(t.unwrap()):t instanceof Po?tn(t._def.innerType):[],Vc=class t extends ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return j(r,{code:A.invalid_type,expected:z.object,received:r.parsedType}),J;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}):(j(r,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}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=tn(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:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...te(n)})}};So=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Zc(s)||Zc(i))return J;let a=sm(s.value,i.value);return a.valid?((qc(s)||qc(i))&&r.dirty(),{status:r.value,value:a.data}):(j(n,{code:A.invalid_intersection_types}),J)};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}))}};So.create=(t,e,r)=>new So({left:t,right:e,typeName:D.ZodIntersection,...te(r)});Dr=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return j(n,{code:A.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return j(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:A.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 tr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};Wc=class t extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return j(n,{code:A.invalid_type,expected:z.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new tr(n,a,n.path,a)),value:i._parse(new tr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ne?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...te(n)}):new t({keyType:Pn.create(),valueType:e,typeName:D.ZodRecord,...te(r)})}},Ps=class extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return j(n,{code:A.invalid_type,expected:z.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new tr(n,a,n.path,[u,"key"])),value:s._parse(new tr(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 J;(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 J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Ps.create=(t,e,r)=>new Ps({valueType:e,keyType:t,typeName:D.ZodMap,...te(r)});Rs=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return j(n,{code:A.invalid_type,expected:z.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(j(n,{code:A.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&&(j(n,{code:A.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 J;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 tr(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:B.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:B.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});Kc=class t extends ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return j(r,{code:A.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),en].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function o(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),en].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Cn){let a=this;return mt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return mt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ct([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:Dr.create(e).rest(rn.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||Dr.create([]).rest(rn.create()),returns:r||rn.create(),typeName:D.ZodFunction,...te(n)})}},ko=class extends ne{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})}};ko.create=(t,e)=>new ko({getter:t,typeName:D.ZodLazy,...te(e)});wo=class extends ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:A.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};wo.create=(t,e)=>new wo({value:t,typeName:D.ZodLiteral,...te(e)});Eo=class t extends ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:ce.joinValues(n),received:r.parsedType,code:A.invalid_type}),J}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 j(r,{received:r.data,code:A.invalid_enum_value,options:n}),J}return mt(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})}};Eo.create=sS;$o=class extends ne{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ce.objectValues(r);return j(n,{expected:ce.joinValues(o),received:n.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return j(n,{received:n.data,code:A.invalid_enum_value,options:o}),J}return mt(e.data)}get enum(){return this._def.values}};$o.create=(t,e)=>new $o({values:t,typeName:D.ZodNativeEnum,...te(e)});Cn=class extends ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return j(r,{code:A.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cn.create=(t,e)=>new Cn({type:t,typeName:D.ZodPromise,...te(e)});rr=class extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.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=>{j(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 J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?fo(c.value):r.value==="dirty"?fo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?fo(a.value):r.value==="dirty"?fo(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"?J:(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"?J:(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(!Tn(i))return J;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=>Tn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);ce.assertNever(o)}};rr.create=(t,e,r)=>new rr({schema:t,typeName:D.ZodEffects,effect:e,...te(r)});rr.createWithPreprocess=(t,e,r)=>new rr({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(r)});Ot=class extends ne{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:D.ZodOptional,...te(e)});Mr=class extends ne{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:D.ZodNullable,...te(e)});To=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};To.create=(t,e)=>new To({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Po=class extends ne{_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 ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends ne{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:D.ZodNaN,...te(t)});pN=Symbol("zod_brand"),Bi=class extends ne{_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}},Zi=class t extends ne{_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"?J:s.status==="dirty"?(r.dirty(),fo(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"?J: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:D.ZodPipeline})}},Ro=class extends ne{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Tn(o)&&(o.value=Object.freeze(o.value)),o);return ws(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodReadonly,...te(e)});mN={object:It.lazycreate};(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"})(D||(D={}));fN=(t,e={message:`Input not instance of ${t.name}`})=>iS(r=>r instanceof t,e),aS=Pn.create,cS=ho.create,hN=Cs.create,gN=go.create,uS=yo.create,yN=_o.create,_N=$s.create,bN=bo.create,xN=xo.create,vN=Rn.create,SN=rn.create,kN=hr.create,wN=Ts.create,EN=nn.create,im=It.create,$N=It.strictCreate,TN=vo.create,PN=Vc.create,RN=So.create,CN=Dr.create,ON=Wc.create,IN=Ps.create,AN=Rs.create,NN=Kc.create,DN=ko.create,MN=wo.create,jN=Eo.create,LN=$o.create,zN=Cn.create,FN=rr.create,HN=Ot.create,UN=Mr.create,BN=rr.createWithPreprocess,ZN=Zi.create,qN=()=>aS().optional(),VN=()=>cS().optional(),WN=()=>uS().optional(),KN={string:(t=>Pn.create({...t,coerce:!0})),number:(t=>ho.create({...t,coerce:!0})),boolean:(t=>yo.create({...t,coerce:!0})),bigint:(t=>go.create({...t,coerce:!0})),date:(t=>_o.create({...t,coerce:!0}))},GN=J});var M={};we(M,{BRAND:()=>pN,DIRTY:()=>fo,EMPTY_PATH:()=>ZA,INVALID:()=>J,NEVER:()=>GN,OK:()=>mt,ParseStatus:()=>st,Schema:()=>ne,ZodAny:()=>Rn,ZodArray:()=>nn,ZodBigInt:()=>go,ZodBoolean:()=>yo,ZodBranded:()=>Bi,ZodCatch:()=>Po,ZodDate:()=>_o,ZodDefault:()=>To,ZodDiscriminatedUnion:()=>Vc,ZodEffects:()=>rr,ZodEnum:()=>Eo,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Kc,ZodIntersection:()=>So,ZodIssueCode:()=>A,ZodLazy:()=>ko,ZodLiteral:()=>wo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>$o,ZodNever:()=>hr,ZodNull:()=>xo,ZodNullable:()=>Mr,ZodNumber:()=>ho,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Zi,ZodPromise:()=>Cn,ZodReadonly:()=>Ro,ZodRecord:()=>Wc,ZodSchema:()=>ne,ZodSet:()=>Rs,ZodString:()=>Pn,ZodSymbol:()=>$s,ZodTransformer:()=>rr,ZodTuple:()=>Dr,ZodType:()=>ne,ZodUndefined:()=>bo,ZodUnion:()=>vo,ZodUnknown:()=>rn,ZodVoid:()=>Ts,addIssueToContext:()=>j,any:()=>vN,array:()=>EN,bigint:()=>gN,boolean:()=>uS,coerce:()=>KN,custom:()=>iS,date:()=>yN,datetimeRegex:()=>oS,defaultErrorMap:()=>en,discriminatedUnion:()=>PN,effect:()=>FN,enum:()=>jN,function:()=>NN,getErrorMap:()=>ks,getParsedType:()=>Nr,instanceof:()=>fN,intersection:()=>RN,isAborted:()=>Zc,isAsync:()=>ws,isDirty:()=>qc,isValid:()=>Tn,late:()=>mN,lazy:()=>DN,literal:()=>MN,makeIssue:()=>Ui,map:()=>IN,nan:()=>hN,nativeEnum:()=>LN,never:()=>kN,null:()=>xN,nullable:()=>UN,number:()=>cS,object:()=>im,objectUtil:()=>tm,oboolean:()=>WN,onumber:()=>VN,optional:()=>HN,ostring:()=>qN,pipeline:()=>ZN,preprocess:()=>BN,promise:()=>zN,quotelessJson:()=>HA,record:()=>ON,set:()=>AN,setErrorMap:()=>BA,strictObject:()=>$N,string:()=>aS,symbol:()=>_N,transformer:()=>FN,tuple:()=>CN,undefined:()=>bN,union:()=>TN,unknown:()=>SN,util:()=>ce,void:()=>wN});var Gc=S(()=>{Bc();nm();Yv();Hi();lS();Uc()});var qi=S(()=>{Gc()});function T(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 Ft(t){return t&&Object.assign(Jc,t),Jc}var XN,on,Jc,Os=S(()=>{XN=Object.freeze({status:"aborted"});on=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jc={}});var ue={};we(ue,{BIGINT_FORMAT_RANGES:()=>pS,Class:()=>cm,NUMBER_FORMAT_RANGES:()=>hm,aborted:()=>Oo,allowsEval:()=>pm,assert:()=>rD,assertEqual:()=>YN,assertIs:()=>eD,assertNever:()=>tD,assertNotEqual:()=>QN,assignProp:()=>dm,cached:()=>Ki,captureStackTrace:()=>Yc,cleanEnum:()=>hD,cleanRegex:()=>Ji,clone:()=>Ht,createTransparentProxy:()=>cD,defineLazy:()=>Te,esc:()=>Co,escapeRegex:()=>On,extend:()=>dD,finalizeIssue:()=>gr,floatSafeRemainder:()=>lm,getElementAtPath:()=>nD,getEnumValues:()=>Wi,getLengthableOrigin:()=>Xi,getParsedType:()=>aD,getSizableOrigin:()=>mS,isObject:()=>Is,isPlainObject:()=>As,issue:()=>gm,joinValues:()=>Xc,jsonStringifyReplacer:()=>um,merge:()=>pD,normalizeParams:()=>X,nullish:()=>Gi,numKeys:()=>iD,omit:()=>lD,optionalKeys:()=>fm,partial:()=>mD,pick:()=>uD,prefixIssues:()=>jr,primitiveTypes:()=>dS,promiseAllObject:()=>oD,propertyKeyTypes:()=>mm,randomString:()=>sD,required:()=>fD,stringifyPrimitive:()=>Qc,unwrapMessage:()=>Vi});function YN(t){return t}function QN(t){return t}function eD(t){}function tD(t){throw new Error}function rD(t){}function Wi(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 Xc(t,e="|"){return t.map(r=>Qc(r)).join(e)}function um(t,e){return typeof e=="bigint"?e.toString():e}function Ki(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gi(t){return t==null}function Ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function lm(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 Te(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 dm(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function nD(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function oD(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 sD(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Co(t){return JSON.stringify(t)}function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function As(t){if(Is(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Is(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function iD(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function On(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(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 cD(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 Qc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function fm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function uD(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 Ht(t,{...t._zod.def,shape:r,checks:[]})}function lD(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 Ht(t,{...t._zod.def,shape:r,checks:[]})}function dD(t,e){if(!As(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 dm(this,"shape",n),n},checks:[]};return Ht(t,r)}function pD(t,e){return Ht(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return dm(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function mD(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 Ht(e,{...e._zod.def,shape:o,checks:[]})}function fD(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 Ht(e,{...e._zod.def,shape:o,checks:[]})}function Oo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Vi(t){return typeof t=="string"?t:t?.message}function gr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Vi(t.inst?._zod.def?.error?.(t))??Vi(e?.error?.(t))??Vi(r.customError?.(t))??Vi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function mS(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Xi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gm(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function hD(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Yc,pm,aD,mm,dS,hm,pS,cm,Lr=S(()=>{Yc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};pm=Ki(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});aD=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}`)}},mm=new Set(["string","number","symbol"]),dS=new Set(["string","number","bigint","boolean","symbol","undefined"]);hm={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]},pS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};cm=class{constructor(...e){}}});function ym(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 _m(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 fS,eu,Yi,bm=S(()=>{Os();Lr();fS=(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,um,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},eu=T("$ZodError",fS),Yi=T("$ZodError",fS,{Parent:Error})});var xm,vm,Sm,km,wm,Io,Em,Ao,$m=S(()=>{Os();bm();Lr();xm=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 on;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Yc(a,o?.callee),a}return i.value},vm=xm(Yi),Sm=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=>gr(c,s,Ft())));throw Yc(a,o?.callee),a}return i.value},km=Sm(Yi),wm=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 on;return s.issues.length?{success:!1,error:new(t??eu)(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Io=wm(Yi),Em=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=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Ao=Em(Yi)});function wS(){return new RegExp(yD,"u")}function NS(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 DS(t){return new RegExp(`^${NS(t)}$`)}function MS(t){let e=NS({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(`^${IS}T(?:${n})$`)}var hS,gS,yS,_S,bS,xS,vS,SS,Tm,kS,yD,ES,$S,TS,PS,RS,Pm,CS,OS,IS,AS,jS,LS,zS,FS,HS,US,BS,ru=S(()=>{hS=/^[cC][^\s-]{8,}$/,gS=/^[0-9a-z]+$/,yS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_S=/^[0-9a-vA-V]{20}$/,bS=/^[A-Za-z0-9]{27}$/,xS=/^[a-zA-Z0-9_-]{21}$/,vS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,SS=/^([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})$/,Tm=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)$/,kS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ES=/^(?:(?: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])$/,$S=/^(([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})$/,TS=/^((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])$/,PS=/^(([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])$/,RS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pm=/^[A-Za-z0-9_-]*$/,CS=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,OS=/^\+(?:[0-9]){6,14}[0-9]$/,IS="(?:(?:\\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])))",AS=new RegExp(`^${IS}$`);jS=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},LS=/^\d+$/,zS=/^-?\d+(?:\.\d+)?/i,FS=/true|false/i,HS=/null/i,US=/^[^A-Z]*$/,BS=/^[^a-z]*$/});var it,ZS,Rm,Cm,qS,VS,WS,KS,GS,Qi,JS,XS,YS,QS,ek,tk,rk,nu=S(()=>{Os();ru();Lr();it=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ZS={number:"number",bigint:"bigint",object:"date"},Rm=T("$ZodCheckLessThan",(t,e)=>{it.init(t,e);let r=ZS[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})}}),Cm=T("$ZodCheckGreaterThan",(t,e)=>{it.init(t,e);let r=ZS[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})}}),qS=T("$ZodCheckMultipleOf",(t,e)=>{it.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):lm(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})}}),VS=T("$ZodCheckNumberFormat",(t,e)=>{it.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=hm[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=LS)}),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})}}),WS=T("$ZodCheckMaxLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),KS=T("$ZodCheckMinLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),GS=T("$ZodCheckLengthEquals",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(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})}}),Qi=T("$ZodCheckStringFormat",(t,e)=>{var r,n;it.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=()=>{})}),JS=T("$ZodCheckRegex",(t,e)=>{Qi.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})}}),XS=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=US),Qi.init(t,e)}),YS=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=BS),Qi.init(t,e)}),QS=T("$ZodCheckIncludes",(t,e)=>{it.init(t,e);let r=On(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})}}),ek=T("$ZodCheckStartsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`^${On(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})}}),tk=T("$ZodCheckEndsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`.*${On(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})}}),rk=T("$ZodCheckOverwrite",(t,e)=>{it.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ou,Om=S(()=>{ou=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(`
|
|
439
|
+
`);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),p=u[0]?.trim().slice(0,80);s.push({title:p||`Lines ${l}-${d}`,content:u.join(`
|
|
440
|
+
`)})}return s}#H(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#H(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#X(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#J(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#X(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#J(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});import{readFileSync as Wv,realpathSync as bA}from"node:fs";import{resolve as Li}from"node:path";function Kv(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function vA(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function SA(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Vv(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function kA(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=SA(o),a=Vv(s);r=`^${i}(\\s${a})?$`}else r=`^${Vv(t)}$`;return new RegExp(r,e?"i":"")}function wA(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function EA(t,e,r=!1){for(let n of e){let o=Kv(n);if(o&&kA(o,r).test(t))return n}return null}function $A(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function Yp(t){let e;try{e=Wv(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Kv(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function Qp(t,e){let r=[];if(t){let o=Li(t,".claude","settings.local.json"),s=Yp(o);s&&r.push(s);let i=Li(t,".claude","settings.json"),a=Yp(i);a&&r.push(a)}let n=e!==void 0?[e]:qp();for(let o of n){let s=Yp(o);s&&r.push(s)}return r}function lo(t,e,r){let n=[],o=i=>{let a;try{a=Wv(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let p=vA(d);p&&p.tool===t&&l.push(p.glob)}return l};if(e){let i=o(Li(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Li(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:qp();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function em(t,e,r=process.platform==="win32"){let n=$A(t);for(let o of n)for(let s of e){let i=EA(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function po(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Li(n,t);s.add(o(i));try{s.add(o(bA(i)))}catch{}}for(let i of e)for(let a of i){let c=wA(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function PA(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Gv(t,e){let r=TA[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...PA(t)),n}var TA,tm=S(()=>{"use strict";wn();TA={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});var Yv={};we(Yv,{healClaudeJsonMcpArgs:()=>BA,healInstalledPlugins:()=>FA,healMcpJsonArgs:()=>UA,healPluginJsonMcpServers:()=>Hc,healSettingsEnabledPlugins:()=>HA,sweepStaleMcpJson:()=>Uc});import{existsSync as en,readFileSync as Ss,writeFileSync as Fi,readdirSync as jA,unlinkSync as LA,statSync as zA}from"node:fs";import{resolve as St,sep as mo}from"node:path";function FA({registryPath:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!en(t))return{healed:[],skipped:"no-registry"};let n;try{n=Ss(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[r]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let l=St(u),d=St(e)+mo;if(!l.startsWith(d))continue;let p=St(u,".claude-plugin","plugin.json");if(!en(p))continue;let h=null;try{let m=JSON.parse(Ss(p,"utf-8"));m&&typeof m.version=="string"&&m.version&&(h=m.version)}catch{continue}h&&(a=h,c.version!==h&&(c.version=h,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[r];(c==null||c===!1||c==="")&&(o.enabledPlugins[r]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Fi(t,JSON.stringify(o,null,2)+`
|
|
441
|
+
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function HA({settingsPath:t,pluginKey:e}){if(!t||!en(t))return{healed:[],skipped:"no-settings"};let r;try{r=Ss(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let n;try{n=JSON.parse(r)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!n.enabledPlugins||typeof n.enabledPlugins!="object"||Array.isArray(n.enabledPlugins))&&(n.enabledPlugins={});let s=n.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(n.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{Fi(t,JSON.stringify(n,null,2)+`
|
|
442
|
+
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function Hc({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=St(t),o=St(e)+mo;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".claude-plugin","plugin.json");if(!en(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=Ss(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===zi?f:/[/\\]start\.mjs$/.test(f)?zi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("plugin-json-args");try{Fi(s,JSON.stringify(a,null,2)+`
|
|
443
|
+
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function UA({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=St(t),o=St(e)+mo;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=St(t,".mcp.json");if(!en(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=Ss(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===zi?f:f==="./start.mjs"||f==="start.mjs"||/[/\\]start\.mjs$/.test(f)?zi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("mcp-json-args");try{Fi(s,JSON.stringify(a,null,2)+`
|
|
444
|
+
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function BA({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!en(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=Ss(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(n)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=St(r),c=a+mo,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let p=l.args[d];if(typeof p!="string")continue;let h=p.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let m=h.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let g=m.slice(f+1),y=St(r,g);y!==a&&!(y+mo).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Fi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function Uc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=St(t);if(!en(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=St(n,o,s),a=n+mo;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!en(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=jA(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let l=St(i,u);if(!l.startsWith(i+mo))continue;try{if(!zA(l).isDirectory())continue}catch{continue}let d=St(l,".mcp.json");if(en(d))try{LA(d),r.push(d)}catch{}}return{removed:r}}var zi,rm=S(()=>{"use strict";zi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,nm,z,Nr,Hi=S(()=>{(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})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(nm||(nm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Nr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var A,VA,Ct,Bc=S(()=>{Hi();A=ce.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"]),VA=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ct=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,ce.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()}};Ct.create=t=>new Ct(t)});var WA,tn,om=S(()=>{Bc();Hi();WA=(t,e)=>{let r;switch(t.code){case A.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case A.invalid_union:r="Invalid input";break;case A.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case A.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:r="Invalid function arguments";break;case A.invalid_return_type:r="Invalid function return type";break;case A.invalid_date:r="Invalid date";break;case A.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}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case A.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 A.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 A.custom:r="Invalid input";break;case A.invalid_intersection_types:r="Intersection results could not be merged";break;case A.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},tn=WA});function KA(t){eS=t}function ks(){return eS}var eS,Zc=S(()=>{om();eS=tn});function j(t,e){let r=ks(),n=Ui({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===tn?void 0:tn].filter(o=>!!o)});t.common.issues.push(n)}var Ui,GA,st,J,fo,mt,qc,Vc,Pn,ws,sm=S(()=>{Zc();om();Ui=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}},GA=[];st=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),fo=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),qc=t=>t.status==="aborted",Vc=t=>t.status==="dirty",Pn=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var tS=S(()=>{});var B,rS=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(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}}function iS(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 pN(t){return new RegExp(`^${iS(t)}$`)}function aS(t){let e=`${sS}T${iS(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 mN(t,e){return!!((e==="v4"||!e)&&sN.test(t)||(e==="v6"||!e)&&aN.test(t))}function fN(t,e){if(!tN.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 hN(t,e){return!!((e==="v4"||!e)&&iN.test(t)||(e==="v6"||!e)&&cN.test(t))}function gN(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 Es(t){if(t instanceof It){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ot.create(Es(n))}return new It({...t._def,shape:()=>e})}else return t instanceof on?new on({...t._def,type:Es(t.element)}):t instanceof Ot?Ot.create(Es(t.unwrap())):t instanceof Mr?Mr.create(Es(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Es(e))):t}function am(t,e){let r=Nr(t),n=Nr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=am(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=am(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function cS(t,e){return new Eo({values:t,typeName:D.ZodEnum,...te(e)})}function oS(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function uS(t,e={},r){return t?Cn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=oS(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=oS(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Cn.create()}var tr,nS,ne,JA,XA,YA,QA,eN,tN,rN,nN,oN,im,sN,iN,aN,cN,uN,lN,sS,dN,Rn,ho,go,yo,_o,$s,xo,bo,Cn,nn,hr,Ts,on,It,vo,rn,Wc,So,Dr,Kc,Ps,Rs,Gc,ko,wo,Eo,$o,On,rr,Ot,Mr,To,Po,Cs,yN,Bi,Zi,Ro,_N,D,xN,lS,dS,bN,vN,pS,SN,kN,wN,EN,$N,TN,PN,RN,CN,cm,ON,IN,AN,NN,DN,MN,jN,LN,zN,FN,HN,UN,BN,ZN,qN,VN,WN,KN,GN,JN,XN,YN,QN,eD,mS=S(()=>{Bc();Zc();rS();sm();Hi();tr=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}},nS=(t,e)=>{if(Pn(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 Ct(t.common.issues);return this._error=r,this._error}}};ne=class{get description(){return this._def.description}_getType(e){return Nr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ws(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:Nr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return nS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pn(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=>Pn(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:Nr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ws(o)?o:Promise.resolve(o));return nS(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:A.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 rr({schema:this,typeName:D.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 Ot.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return on.create(this)}promise(){return On.create(this,this._def)}or(e){return vo.create([this,e],this._def)}and(e){return So.create(this,e,this._def)}transform(e){return new rr({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new To({...te(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Bi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zi.create(this,e)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},JA=/^c[^\s-]{8,}$/i,XA=/^[0-9a-z]+$/,YA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QA=/^[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,eN=/^[a-z0-9_-]{21}$/i,tN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rN=/^[-+]?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)?)??$/,nN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sN=/^(?:(?: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])$/,iN=/^(?:(?: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])$/,aN=/^(([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]))$/,cN=/^(([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])$/,uN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sS="((\\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])))",dN=new RegExp(`^${sS}$`);Rn=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.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),j(o,{code:A.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?j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")nN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"email",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")im||(im=new RegExp(oN,"u")),im.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"emoji",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")QA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"uuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")eN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"nanoid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")JA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")XA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid2",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")YA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ulid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),j(o,{validation:"url",code:A.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),j(o,{validation:"regex",code:A.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),j(o,{code:A.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),j(o,{code:A.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?aS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?dN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?pN(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?rN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"duration",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?mN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ip",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?fN(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"jwt",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?hN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cidr",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?uN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?lN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64url",code:A.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:A.invalid_string,...B.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...B.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...B.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...B.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...B.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...B.errToObj(r)})}nonempty(e){return this.min(1,B.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}};Rn.create=t=>new Rn({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});ho=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.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),j(n,{code:A.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),j(n,{code:A.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?gN(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.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"&&ce.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)}};ho.create=t=>new ho({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});go=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new st;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),j(n,{code:A.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),j(n,{code:A.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),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.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}};go.create=t=>new go({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});yo=class extends ne{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};yo.create=t=>new yo({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});_o=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_date}),J}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.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),j(o,{code:A.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.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:B.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:B.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}};_o.create=t=>new _o({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});$s=class extends ne{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};$s.create=t=>new $s({typeName:D.ZodSymbol,...te(t)});xo=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};xo.create=t=>new xo({typeName:D.ZodUndefined,...te(t)});bo=class extends ne{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};bo.create=t=>new bo({typeName:D.ZodNull,...te(t)});Cn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Cn.create=t=>new Cn({typeName:D.ZodAny,...te(t)});nn=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};nn.create=t=>new nn({typeName:D.ZodUnknown,...te(t)});hr=class extends ne{_parse(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.never,received:r.parsedType}),J}};hr.create=t=>new hr({typeName:D.ZodNever,...te(t)});Ts=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ts.create=t=>new Ts({typeName:D.ZodVoid,...te(t)});on=class t extends ne{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return j(r,{code:A.invalid_type,expected:z.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(j(r,{code:i?A.too_big:A.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&&(j(r,{code:A.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&&(j(r,{code:A.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 tr(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new tr(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:B.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:B.toString(r)}})}nonempty(e){return this.min(1,e)}};on.create=(t,e)=>new on({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});It=class t extends ne{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=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return j(u,{code:A.invalid_type,expected:z.object,received:u.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hr&&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 tr(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof hr){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&&(j(o,{code:A.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 tr(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>st.mergeObjectSync(n,u)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return B.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:B.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:D.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 ce.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 ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Es(this)}partial(e){let r={};for(let n of ce.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 ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return cS(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});vo=class extends ne{_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 Ct(a.ctx.common.issues));return j(r,{code:A.invalid_union,unionErrors:i}),J}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 Ct(c));return j(r,{code:A.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};vo.create=(t,e)=>new vo({options:t,typeName:D.ZodUnion,...te(e)});rn=t=>t instanceof ko?rn(t.schema):t instanceof rr?rn(t.innerType()):t instanceof wo?[t.value]:t instanceof Eo?t.options:t instanceof $o?ce.objectValues(t.enum):t instanceof To?rn(t._def.innerType):t instanceof xo?[void 0]:t instanceof bo?[null]:t instanceof Ot?[void 0,...rn(t.unwrap())]:t instanceof Mr?[null,...rn(t.unwrap())]:t instanceof Bi||t instanceof Ro?rn(t.unwrap()):t instanceof Po?rn(t._def.innerType):[],Wc=class t extends ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return j(r,{code:A.invalid_type,expected:z.object,received:r.parsedType}),J;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}):(j(r,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}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=rn(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:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...te(n)})}};So=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qc(s)||qc(i))return J;let a=am(s.value,i.value);return a.valid?((Vc(s)||Vc(i))&&r.dirty(),{status:r.value,value:a.data}):(j(n,{code:A.invalid_intersection_types}),J)};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}))}};So.create=(t,e,r)=>new So({left:t,right:e,typeName:D.ZodIntersection,...te(r)});Dr=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return j(n,{code:A.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return j(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:A.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 tr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};Kc=class t extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return j(n,{code:A.invalid_type,expected:z.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new tr(n,a,n.path,a)),value:i._parse(new tr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ne?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...te(n)}):new t({keyType:Rn.create(),valueType:e,typeName:D.ZodRecord,...te(r)})}},Ps=class extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return j(n,{code:A.invalid_type,expected:z.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new tr(n,a,n.path,[u,"key"])),value:s._parse(new tr(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 J;(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 J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Ps.create=(t,e,r)=>new Ps({valueType:e,keyType:t,typeName:D.ZodMap,...te(r)});Rs=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return j(n,{code:A.invalid_type,expected:z.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(j(n,{code:A.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&&(j(n,{code:A.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 J;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 tr(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:B.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:B.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});Gc=class t extends ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return j(r,{code:A.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),tn].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function o(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),tn].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof On){let a=this;return mt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return mt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ct([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:Dr.create(e).rest(nn.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||Dr.create([]).rest(nn.create()),returns:r||nn.create(),typeName:D.ZodFunction,...te(n)})}},ko=class extends ne{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})}};ko.create=(t,e)=>new ko({getter:t,typeName:D.ZodLazy,...te(e)});wo=class extends ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:A.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};wo.create=(t,e)=>new wo({value:t,typeName:D.ZodLiteral,...te(e)});Eo=class t extends ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:ce.joinValues(n),received:r.parsedType,code:A.invalid_type}),J}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 j(r,{received:r.data,code:A.invalid_enum_value,options:n}),J}return mt(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})}};Eo.create=cS;$o=class extends ne{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ce.objectValues(r);return j(n,{expected:ce.joinValues(o),received:n.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return j(n,{received:n.data,code:A.invalid_enum_value,options:o}),J}return mt(e.data)}get enum(){return this._def.values}};$o.create=(t,e)=>new $o({values:t,typeName:D.ZodNativeEnum,...te(e)});On=class extends ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return j(r,{code:A.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};On.create=(t,e)=>new On({type:t,typeName:D.ZodPromise,...te(e)});rr=class extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.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=>{j(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 J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?fo(c.value):r.value==="dirty"?fo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?fo(a.value):r.value==="dirty"?fo(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"?J:(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"?J:(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(!Pn(i))return J;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=>Pn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);ce.assertNever(o)}};rr.create=(t,e,r)=>new rr({schema:t,typeName:D.ZodEffects,effect:e,...te(r)});rr.createWithPreprocess=(t,e,r)=>new rr({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(r)});Ot=class extends ne{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:D.ZodOptional,...te(e)});Mr=class extends ne{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:D.ZodNullable,...te(e)});To=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};To.create=(t,e)=>new To({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Po=class extends ne{_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 ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends ne{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:D.ZodNaN,...te(t)});yN=Symbol("zod_brand"),Bi=class extends ne{_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}},Zi=class t extends ne{_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"?J:s.status==="dirty"?(r.dirty(),fo(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"?J: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:D.ZodPipeline})}},Ro=class extends ne{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o);return ws(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodReadonly,...te(e)});_N={object:It.lazycreate};(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"})(D||(D={}));xN=(t,e={message:`Input not instance of ${t.name}`})=>uS(r=>r instanceof t,e),lS=Rn.create,dS=ho.create,bN=Cs.create,vN=go.create,pS=yo.create,SN=_o.create,kN=$s.create,wN=xo.create,EN=bo.create,$N=Cn.create,TN=nn.create,PN=hr.create,RN=Ts.create,CN=on.create,cm=It.create,ON=It.strictCreate,IN=vo.create,AN=Wc.create,NN=So.create,DN=Dr.create,MN=Kc.create,jN=Ps.create,LN=Rs.create,zN=Gc.create,FN=ko.create,HN=wo.create,UN=Eo.create,BN=$o.create,ZN=On.create,qN=rr.create,VN=Ot.create,WN=Mr.create,KN=rr.createWithPreprocess,GN=Zi.create,JN=()=>lS().optional(),XN=()=>dS().optional(),YN=()=>pS().optional(),QN={string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ho.create({...t,coerce:!0})),boolean:(t=>yo.create({...t,coerce:!0})),bigint:(t=>go.create({...t,coerce:!0})),date:(t=>_o.create({...t,coerce:!0}))},eD=J});var M={};we(M,{BRAND:()=>yN,DIRTY:()=>fo,EMPTY_PATH:()=>GA,INVALID:()=>J,NEVER:()=>eD,OK:()=>mt,ParseStatus:()=>st,Schema:()=>ne,ZodAny:()=>Cn,ZodArray:()=>on,ZodBigInt:()=>go,ZodBoolean:()=>yo,ZodBranded:()=>Bi,ZodCatch:()=>Po,ZodDate:()=>_o,ZodDefault:()=>To,ZodDiscriminatedUnion:()=>Wc,ZodEffects:()=>rr,ZodEnum:()=>Eo,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Gc,ZodIntersection:()=>So,ZodIssueCode:()=>A,ZodLazy:()=>ko,ZodLiteral:()=>wo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>$o,ZodNever:()=>hr,ZodNull:()=>bo,ZodNullable:()=>Mr,ZodNumber:()=>ho,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Zi,ZodPromise:()=>On,ZodReadonly:()=>Ro,ZodRecord:()=>Kc,ZodSchema:()=>ne,ZodSet:()=>Rs,ZodString:()=>Rn,ZodSymbol:()=>$s,ZodTransformer:()=>rr,ZodTuple:()=>Dr,ZodType:()=>ne,ZodUndefined:()=>xo,ZodUnion:()=>vo,ZodUnknown:()=>nn,ZodVoid:()=>Ts,addIssueToContext:()=>j,any:()=>$N,array:()=>CN,bigint:()=>vN,boolean:()=>pS,coerce:()=>QN,custom:()=>uS,date:()=>SN,datetimeRegex:()=>aS,defaultErrorMap:()=>tn,discriminatedUnion:()=>AN,effect:()=>qN,enum:()=>UN,function:()=>zN,getErrorMap:()=>ks,getParsedType:()=>Nr,instanceof:()=>xN,intersection:()=>NN,isAborted:()=>qc,isAsync:()=>ws,isDirty:()=>Vc,isValid:()=>Pn,late:()=>_N,lazy:()=>FN,literal:()=>HN,makeIssue:()=>Ui,map:()=>jN,nan:()=>bN,nativeEnum:()=>BN,never:()=>PN,null:()=>EN,nullable:()=>WN,number:()=>dS,object:()=>cm,objectUtil:()=>nm,oboolean:()=>YN,onumber:()=>XN,optional:()=>VN,ostring:()=>JN,pipeline:()=>GN,preprocess:()=>KN,promise:()=>ZN,quotelessJson:()=>VA,record:()=>MN,set:()=>LN,setErrorMap:()=>KA,strictObject:()=>ON,string:()=>lS,symbol:()=>kN,transformer:()=>qN,tuple:()=>DN,undefined:()=>wN,union:()=>IN,unknown:()=>TN,util:()=>ce,void:()=>RN});var Jc=S(()=>{Zc();sm();tS();Hi();mS();Bc()});var qi=S(()=>{Jc()});function T(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 Ft(t){return t&&Object.assign(Xc,t),Xc}var rD,sn,Xc,Os=S(()=>{rD=Object.freeze({status:"aborted"});sn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Xc={}});var ue={};we(ue,{BIGINT_FORMAT_RANGES:()=>hS,Class:()=>lm,NUMBER_FORMAT_RANGES:()=>ym,aborted:()=>Oo,allowsEval:()=>fm,assert:()=>aD,assertEqual:()=>nD,assertIs:()=>sD,assertNever:()=>iD,assertNotEqual:()=>oD,assignProp:()=>mm,cached:()=>Ki,captureStackTrace:()=>Qc,cleanEnum:()=>bD,cleanRegex:()=>Ji,clone:()=>Ht,createTransparentProxy:()=>mD,defineLazy:()=>Te,esc:()=>Co,escapeRegex:()=>In,extend:()=>gD,finalizeIssue:()=>gr,floatSafeRemainder:()=>pm,getElementAtPath:()=>cD,getEnumValues:()=>Wi,getLengthableOrigin:()=>Xi,getParsedType:()=>pD,getSizableOrigin:()=>gS,isObject:()=>Is,isPlainObject:()=>As,issue:()=>_m,joinValues:()=>Yc,jsonStringifyReplacer:()=>dm,merge:()=>yD,normalizeParams:()=>X,nullish:()=>Gi,numKeys:()=>dD,omit:()=>hD,optionalKeys:()=>gm,partial:()=>_D,pick:()=>fD,prefixIssues:()=>jr,primitiveTypes:()=>fS,promiseAllObject:()=>uD,propertyKeyTypes:()=>hm,randomString:()=>lD,required:()=>xD,stringifyPrimitive:()=>eu,unwrapMessage:()=>Vi});function nD(t){return t}function oD(t){return t}function sD(t){}function iD(t){throw new Error}function aD(t){}function Wi(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 Yc(t,e="|"){return t.map(r=>eu(r)).join(e)}function dm(t,e){return typeof e=="bigint"?e.toString():e}function Ki(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gi(t){return t==null}function Ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pm(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 Te(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 mm(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cD(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function uD(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 lD(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Co(t){return JSON.stringify(t)}function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function As(t){if(Is(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Is(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function dD(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function In(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(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 mD(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 eu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function fD(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 Ht(t,{...t._zod.def,shape:r,checks:[]})}function hD(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 Ht(t,{...t._zod.def,shape:r,checks:[]})}function gD(t,e){if(!As(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 mm(this,"shape",n),n},checks:[]};return Ht(t,r)}function yD(t,e){return Ht(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mm(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function _D(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 Ht(e,{...e._zod.def,shape:o,checks:[]})}function xD(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 Ht(e,{...e._zod.def,shape:o,checks:[]})}function Oo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Vi(t){return typeof t=="string"?t:t?.message}function gr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Vi(t.inst?._zod.def?.error?.(t))??Vi(e?.error?.(t))??Vi(r.customError?.(t))??Vi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function gS(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Xi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _m(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function bD(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Qc,fm,pD,hm,fS,ym,hS,lm,Lr=S(()=>{Qc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};fm=Ki(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});pD=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}`)}},hm=new Set(["string","number","symbol"]),fS=new Set(["string","number","bigint","boolean","symbol","undefined"]);ym={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]},hS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};lm=class{constructor(...e){}}});function xm(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 bm(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 yS,tu,Yi,vm=S(()=>{Os();Lr();yS=(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,dm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},tu=T("$ZodError",yS),Yi=T("$ZodError",yS,{Parent:Error})});var Sm,km,wm,Em,$m,Io,Tm,Ao,Pm=S(()=>{Os();vm();Lr();Sm=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 sn;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Qc(a,o?.callee),a}return i.value},km=Sm(Yi),wm=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=>gr(c,s,Ft())));throw Qc(a,o?.callee),a}return i.value},Em=wm(Yi),$m=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 sn;return s.issues.length?{success:!1,error:new(t??tu)(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Io=$m(Yi),Tm=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=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Ao=Tm(Yi)});function TS(){return new RegExp(SD,"u")}function jS(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 LS(t){return new RegExp(`^${jS(t)}$`)}function zS(t){let e=jS({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(`^${DS}T(?:${n})$`)}var _S,xS,bS,vS,SS,kS,wS,ES,Rm,$S,SD,PS,RS,CS,OS,IS,Cm,AS,NS,DS,MS,FS,HS,US,BS,ZS,qS,VS,nu=S(()=>{_S=/^[cC][^\s-]{8,}$/,xS=/^[0-9a-z]+$/,bS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vS=/^[0-9a-vA-V]{20}$/,SS=/^[A-Za-z0-9]{27}$/,kS=/^[a-zA-Z0-9_-]{21}$/,wS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ES=/^([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})$/,Rm=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)$/,$S=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,SD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";PS=/^(?:(?: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])$/,RS=/^(([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})$/,CS=/^((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])$/,OS=/^(([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])$/,IS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Cm=/^[A-Za-z0-9_-]*$/,AS=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,NS=/^\+(?:[0-9]){6,14}[0-9]$/,DS="(?:(?:\\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])))",MS=new RegExp(`^${DS}$`);FS=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},HS=/^\d+$/,US=/^-?\d+(?:\.\d+)?/i,BS=/true|false/i,ZS=/null/i,qS=/^[^A-Z]*$/,VS=/^[^a-z]*$/});var it,WS,Om,Im,KS,GS,JS,XS,YS,Qi,QS,ek,tk,rk,nk,ok,sk,ou=S(()=>{Os();nu();Lr();it=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),WS={number:"number",bigint:"bigint",object:"date"},Om=T("$ZodCheckLessThan",(t,e)=>{it.init(t,e);let r=WS[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})}}),Im=T("$ZodCheckGreaterThan",(t,e)=>{it.init(t,e);let r=WS[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})}}),KS=T("$ZodCheckMultipleOf",(t,e)=>{it.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):pm(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})}}),GS=T("$ZodCheckNumberFormat",(t,e)=>{it.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ym[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=HS)}),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})}}),JS=T("$ZodCheckMaxLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),XS=T("$ZodCheckMinLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),YS=T("$ZodCheckLengthEquals",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(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=Xi(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})}}),Qi=T("$ZodCheckStringFormat",(t,e)=>{var r,n;it.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=()=>{})}),QS=T("$ZodCheckRegex",(t,e)=>{Qi.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})}}),ek=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=qS),Qi.init(t,e)}),tk=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=VS),Qi.init(t,e)}),rk=T("$ZodCheckIncludes",(t,e)=>{it.init(t,e);let r=In(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})}}),nk=T("$ZodCheckStartsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`^${In(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})}}),ok=T("$ZodCheckEndsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`.*${In(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})}}),sk=T("$ZodCheckOverwrite",(t,e)=>{it.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var su,Am=S(()=>{su=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(`
|
|
442
445
|
`).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(`
|
|
443
|
-
`))}}});var
|
|
444
|
-
if (${
|
|
446
|
+
`))}}});var ak,Nm=S(()=>{ak={major:4,minor:0,patch:0}});function vk(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function kD(t){if(!Cm.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return vk(r)}function wD(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 ck(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function iu(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function uk(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(...jr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function lk(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=>gr(s,n,Ft())))}),e}function Dm(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(As(t)&&As(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=Dm(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=Dm(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 dk(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Oo(t))return t;let n=Dm(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 pk(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function mk(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 fk(t,e,r){return Oo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function hk(t){return t.value=Object.freeze(t.value),t}function gk(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(_m(o))}}var ve,ea,Pe,Mm,jm,Lm,zm,Fm,Hm,Um,Bm,Zm,qm,Vm,yk,_k,xk,bk,Wm,Km,Gm,Jm,Xm,Ym,Qm,ef,au,tf,rf,nf,of,sf,af,cu,uu,cf,uf,lf,df,pf,mf,ff,hf,gf,yf,_f,xf,bf,vf,Sf,Sk=S(()=>{ou();Os();Am();Pm();nu();Lr();Nm();Lr();ve=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ak;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=Oo(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,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new sn;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Oo(s,d)))});else{if(s.issues.length===d)continue;c||(c=Oo(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 sn;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Io(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ao(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ea=T("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??FS(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=T("$ZodStringFormat",(t,e)=>{Qi.init(t,e),ea.init(t,e)}),Mm=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ES),Pe.init(t,e)}),jm=T("$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=Rm(n))}else e.pattern??(e.pattern=Rm());Pe.init(t,e)}),Lm=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=$S),Pe.init(t,e)}),zm=T("$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:AS.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})}}}),Fm=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=TS()),Pe.init(t,e)}),Hm=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=kS),Pe.init(t,e)}),Um=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=_S),Pe.init(t,e)}),Bm=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=xS),Pe.init(t,e)}),Zm=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=bS),Pe.init(t,e)}),qm=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=vS),Pe.init(t,e)}),Vm=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=SS),Pe.init(t,e)}),yk=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=zS(e)),Pe.init(t,e)}),_k=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=MS),Pe.init(t,e)}),xk=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=LS(e)),Pe.init(t,e)}),bk=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=wS),Pe.init(t,e)}),Wm=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=PS),Pe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Km=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=RS),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})}}}),Gm=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=CS),Pe.init(t,e)}),Jm=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=OS),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})}}});Xm=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=IS),Pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{vk(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ym=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Cm),Pe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{kD(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Qm=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=NS),Pe.init(t,e)});ef=T("$ZodJWT",(t,e)=>{Pe.init(t,e),t._zod.check=r=>{wD(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),au=T("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??US,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}}),tf=T("$ZodNumber",(t,e)=>{GS.init(t,e),au.init(t,e)}),rf=T("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=BS,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}}),nf=T("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=ZS,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}}),of=T("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=r=>r}),sf=T("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});af=T("$ZodArray",(t,e)=>{ve.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=>ck(u,r,i))):ck(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});cu=T("$ZodObject",(t,e)=>{ve.init(t,e);let r=Ki(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof ve))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let p=gm(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Te(t._zod,"propValues",()=>{let d=e.shape,p={};for(let h in d){let m=d[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(let f of m.values)p[h].add(f)}}return p});let n=d=>{let p=new su(["shape","payload","ctx"]),h=r.value,m=_=>{let x=Co(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let f=Object.create(null),g=0;for(let _ of h.keys)f[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of h.keys)if(h.optionalKeys.has(_)){let x=f[_];p.write(`const ${x} = ${m(_)};`);let v=Co(_);p.write(`
|
|
447
|
+
if (${x}.issues.length) {
|
|
445
448
|
if (input[${v}] === undefined) {
|
|
446
449
|
if (${v} in input) {
|
|
447
450
|
newResult[${v}] = undefined;
|
|
448
451
|
}
|
|
449
452
|
} else {
|
|
450
453
|
payload.issues = payload.issues.concat(
|
|
451
|
-
${
|
|
454
|
+
${x}.issues.map((iss) => ({
|
|
452
455
|
...iss,
|
|
453
456
|
path: iss.path ? [${v}, ...iss.path] : [${v}],
|
|
454
457
|
}))
|
|
455
458
|
);
|
|
456
459
|
}
|
|
457
|
-
} else if (${
|
|
460
|
+
} else if (${x}.value === undefined) {
|
|
458
461
|
if (${v} in input) newResult[${v}] = undefined;
|
|
459
462
|
} else {
|
|
460
|
-
newResult[${v}] = ${
|
|
463
|
+
newResult[${v}] = ${x}.value;
|
|
461
464
|
}
|
|
462
|
-
`)}else{let
|
|
463
|
-
if (${
|
|
465
|
+
`)}else{let x=f[_];p.write(`const ${x} = ${m(_)};`),p.write(`
|
|
466
|
+
if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
|
464
467
|
...iss,
|
|
465
468
|
path: iss.path ? [${Co(_)}, ...iss.path] : [${Co(_)}]
|
|
466
|
-
})));`),m.write(`newResult[${Co(_)}] = ${b}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(_,b)=>y(d,_,b)},o,s=Is,i=!Jc.jitless,c=i&&pm.value,u=e.catchall,l;t._zod.parse=(d,m)=>{l??(l=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),d=o(d,m);else{d.value={};let b=l.shape;for(let v of l.keys){let E=b[v],C=E._zod.run({value:h[v],issues:[]},m),x=E._zod.optin==="optional"&&E._zod.optout==="optional";C instanceof Promise?p.push(C.then(k=>x?ik(k,d,v,h):su(k,d,v))):x?ik(C,d,v,h):su(C,d,v)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(h)){if(g.has(b))continue;if(_==="never"){f.push(b);continue}let v=y.run({value:h[b],issues:[]},m);v instanceof Promise?p.push(v.then(E=>su(E,d,b))):su(v,d,b)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});cu=T("$ZodUnion",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Te(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=>Ji(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=>ak(i,r,t,n)):ak(s,r,t,n)}}),sf=T("$ZodDiscriminatedUnion",(t,e)=>{cu.init(t,e);let r=t._zod.parse;Te(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=Ki(()=>{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(!Is(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)}}),af=T("$ZodIntersection",(t,e)=>{ve.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])=>ck(r,c,u)):ck(r,s,i)}});cf=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!As(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(...jr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jr(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=>gr(u,n,Ft())),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(...jr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),uf=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Wi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>mm.has(typeof n)).map(n=>typeof n=="string"?On(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}}),lf=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?On(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}}),df=T("$ZodTransform",(t,e)=>{ve.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 on;return r.value=o,r}}),pf=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(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)}),mf=T("$ZodNullable",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)}|null)$`):void 0}),Te(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)}),ff=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(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=>uk(s,e)):uk(o,e)}});hf=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(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))}),gf=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),Te(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=>lk(s,t)):lk(o,t)}});yf=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(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=>gr(i,n,Ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gr(s,n,Ft()))},input:r.value}),r.issues=[]),r)}}),_f=T("$ZodPipe",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(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=>dk(s,e,n)):dk(o,e,n)}});bf=T("$ZodReadonly",(t,e)=>{ve.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(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(pk):pk(o)}});xf=T("$ZodCustom",(t,e)=>{it.init(t,e),ve.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=>mk(s,r,n,t));mk(o,r,n,t)}})});function xk(){return{localeError:vD()}}var xD,vD,vk=S(()=>{Lr();xD=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},vD=()=>{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 ${xD(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Qc(n.values[0])}`:`Invalid option: expected one of ${Xc(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":""}: ${Xc(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 uu=S(()=>{});function Sk(){return new ta}var ta,In,Sf=S(()=>{ta=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)}};In=Sk()});function kf(t,e){return new t({type:"string",...X(e)})}function wf(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function lu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function Ef(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function $f(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function Tf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function Pf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function Rf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function Cf(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Of(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function If(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Af(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function Nf(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function Df(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Mf(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function jf(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Lf(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function zf(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Ff(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function Hf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Uf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function Bf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Zf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function kk(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function wk(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function Ek(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function $k(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function qf(t,e){return new t({type:"number",checks:[],...X(e)})}function Vf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Wf(t,e){return new t({type:"boolean",...X(e)})}function Kf(t,e){return new t({type:"null",...X(e)})}function Gf(t){return new t({type:"unknown"})}function Jf(t,e){return new t({type:"never",...X(e)})}function du(t,e){return new Rm({check:"less_than",...X(e),value:t,inclusive:!1})}function ra(t,e){return new Rm({check:"less_than",...X(e),value:t,inclusive:!0})}function pu(t,e){return new Cm({check:"greater_than",...X(e),value:t,inclusive:!1})}function na(t,e){return new Cm({check:"greater_than",...X(e),value:t,inclusive:!0})}function mu(t,e){return new qS({check:"multiple_of",...X(e),value:t})}function fu(t,e){return new WS({check:"max_length",...X(e),maximum:t})}function Ns(t,e){return new KS({check:"min_length",...X(e),minimum:t})}function hu(t,e){return new GS({check:"length_equals",...X(e),length:t})}function Xf(t,e){return new JS({check:"string_format",format:"regex",...X(e),pattern:t})}function Yf(t){return new XS({check:"string_format",format:"lowercase",...X(t)})}function Qf(t){return new YS({check:"string_format",format:"uppercase",...X(t)})}function eh(t,e){return new QS({check:"string_format",format:"includes",...X(e),includes:t})}function th(t,e){return new ek({check:"string_format",format:"starts_with",...X(e),prefix:t})}function rh(t,e){return new tk({check:"string_format",format:"ends_with",...X(e),suffix:t})}function No(t){return new rk({check:"overwrite",tx:t})}function nh(t){return No(e=>e.normalize(t))}function oh(){return No(t=>t.trim())}function sh(){return No(t=>t.toLowerCase())}function ih(){return No(t=>t.toUpperCase())}function Tk(t,e,r){return new t({type:"array",element:e,...X(r)})}function ah(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ch(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var Pk=S(()=>{nu();Lr()});var Rk=S(()=>{});function uh(t,e){if(t instanceof ta){let n=new gu(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 gu(e);return r.process(t),r.emit(t,e)}function Ye(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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var gu,Ck=S(()=>{Sf();Lr();gu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??In,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 h=a.schema;switch(o.type){case"string":{let p=h;p.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof f=="number"&&(p.minLength=f),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),_&&_.size>0){let v=[..._];v.length===1?p.pattern=v[0].source:v.length>1&&(a.schema.allOf=[...v.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let p=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof v=="number"&&(p.exclusiveMinimum=v),typeof f=="number"&&(p.minimum=f,typeof v=="number"&&(v>=f?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=h;p.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(p.minItems=f),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let f=o.shape;for(let _ in f)p.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let b=o.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=h;p.type="array";let f=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=f:p.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=h;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.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 p=h,f=Wi(o.entries);f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),p.enum=f;break}case"literal":{let p=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];p.type=g===null?"null":typeof g,p.const=g}else f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),f.every(g=>typeof g=="boolean")&&(p.type="string"),f.every(g=>g===null)&&(p.type="null"),p.enum=f;break}case"file":{let p=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(p,f)):p.anyOf=_.map(b=>({...f,contentMediaType:b})):Object.assign(p,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=f.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.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 p=e._zod.innerType;this.process(p,d),a.ref=p;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"&&Ye(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 f=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:m,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let p=d.schema;for(let f in p)delete p[f];p.$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>
|
|
469
|
+
})));`),p.write(`newResult[${Co(_)}] = ${x}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,x)=>y(d,_,x)},o,s=Is,i=!Xc.jitless,c=i&&fm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let x=l.shape;for(let v of l.keys){let E=x[v],C=E._zod.run({value:h[v],issues:[]},p),b=E._zod.optin==="optional"&&E._zod.optout==="optional";C instanceof Promise?m.push(C.then(k=>b?uk(k,d,v,h):iu(k,d,v))):b?uk(C,d,v,h):iu(C,d,v)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(h)){if(g.has(x))continue;if(_==="never"){f.push(x);continue}let v=y.run({value:h[x],issues:[]},p);v instanceof Promise?m.push(v.then(E=>iu(E,d,x))):iu(v,d,x)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),m.length?Promise.all(m).then(()=>d):d}});uu=T("$ZodUnion",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Te(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=>Ji(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=>lk(i,r,t,n)):lk(s,r,t,n)}}),cf=T("$ZodDiscriminatedUnion",(t,e)=>{uu.init(t,e);let r=t._zod.parse;Te(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=Ki(()=>{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(!Is(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)}}),uf=T("$ZodIntersection",(t,e)=>{ve.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])=>dk(r,c,u)):dk(r,s,i)}});lf=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!As(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(...jr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jr(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=>gr(u,n,Ft())),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(...jr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),df=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Wi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>hm.has(typeof n)).map(n=>typeof n=="string"?In(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}}),pf=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?In(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}}),mf=T("$ZodTransform",(t,e)=>{ve.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 sn;return r.value=o,r}}),ff=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(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)}),hf=T("$ZodNullable",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)}|null)$`):void 0}),Te(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)}),gf=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(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=>pk(s,e)):pk(o,e)}});yf=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(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))}),_f=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),Te(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=>mk(s,t)):mk(o,t)}});xf=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(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=>gr(i,n,Ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gr(s,n,Ft()))},input:r.value}),r.issues=[]),r)}}),bf=T("$ZodPipe",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(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=>fk(s,e,n)):fk(o,e,n)}});vf=T("$ZodReadonly",(t,e)=>{ve.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(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(hk):hk(o)}});Sf=T("$ZodCustom",(t,e)=>{it.init(t,e),ve.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=>gk(s,r,n,t));gk(o,r,n,t)}})});function kk(){return{localeError:$D()}}var ED,$D,wk=S(()=>{Lr();ED=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},$D=()=>{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 ${ED(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${eu(n.values[0])}`:`Invalid option: expected one of ${Yc(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":""}: ${Yc(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 lu=S(()=>{});function Ek(){return new ta}var ta,An,wf=S(()=>{ta=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)}};An=Ek()});function Ef(t,e){return new t({type:"string",...X(e)})}function $f(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function du(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function Tf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function Pf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function Rf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function Cf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function Of(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function If(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Af(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function Nf(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Df(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function Mf(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function jf(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Lf(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function zf(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Ff(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function Hf(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Uf(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function Bf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Zf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function qf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Vf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function $k(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function Tk(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function Pk(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function Rk(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function Wf(t,e){return new t({type:"number",checks:[],...X(e)})}function Kf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Gf(t,e){return new t({type:"boolean",...X(e)})}function Jf(t,e){return new t({type:"null",...X(e)})}function Xf(t){return new t({type:"unknown"})}function Yf(t,e){return new t({type:"never",...X(e)})}function pu(t,e){return new Om({check:"less_than",...X(e),value:t,inclusive:!1})}function ra(t,e){return new Om({check:"less_than",...X(e),value:t,inclusive:!0})}function mu(t,e){return new Im({check:"greater_than",...X(e),value:t,inclusive:!1})}function na(t,e){return new Im({check:"greater_than",...X(e),value:t,inclusive:!0})}function fu(t,e){return new KS({check:"multiple_of",...X(e),value:t})}function hu(t,e){return new JS({check:"max_length",...X(e),maximum:t})}function Ns(t,e){return new XS({check:"min_length",...X(e),minimum:t})}function gu(t,e){return new YS({check:"length_equals",...X(e),length:t})}function Qf(t,e){return new QS({check:"string_format",format:"regex",...X(e),pattern:t})}function eh(t){return new ek({check:"string_format",format:"lowercase",...X(t)})}function th(t){return new tk({check:"string_format",format:"uppercase",...X(t)})}function rh(t,e){return new rk({check:"string_format",format:"includes",...X(e),includes:t})}function nh(t,e){return new nk({check:"string_format",format:"starts_with",...X(e),prefix:t})}function oh(t,e){return new ok({check:"string_format",format:"ends_with",...X(e),suffix:t})}function No(t){return new sk({check:"overwrite",tx:t})}function sh(t){return No(e=>e.normalize(t))}function ih(){return No(t=>t.trim())}function ah(){return No(t=>t.toLowerCase())}function ch(){return No(t=>t.toUpperCase())}function Ck(t,e,r){return new t({type:"array",element:e,...X(r)})}function uh(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function lh(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var Ok=S(()=>{ou();Lr()});var Ik=S(()=>{});function dh(t,e){if(t instanceof ta){let n=new yu(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 yu(e);return r.process(t),r.emit(t,e)}function Ye(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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var yu,Ak=S(()=>{wf();Lr();yu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??An,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let m=h;m.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof f=="number"&&(m.minLength=f),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),x&&(m.contentEncoding=x),_&&_.size>0){let v=[..._];v.length===1?m.pattern=v[0].source:v.length>1&&(a.schema.allOf=[...v.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let m=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof v=="number"&&(m.exclusiveMinimum=v),typeof f=="number"&&(m.minimum=f,typeof v=="number"&&(v>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=h;m.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(m.minItems=f),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=h;m.type="object",m.properties={};let f=o.shape;for(let _ in f)m.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=h;m.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=h;m.type="array";let f=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.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 m=h,f=Wi(o.entries);f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),m.enum=f;break}case"literal":{let m=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];m.type=g===null?"null":typeof g,m.const=g}else f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),f.every(g=>typeof g=="boolean")&&(m.type="string"),f.every(g=>g===null)&&(m.type="null"),m.enum=f;break}case"file":{let m=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(m,f)):m.anyOf=_.map(x=>({...f,contentMediaType:x})):Object.assign(m,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=h;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.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 m=e._zod.innerType;this.process(m,d),a.ref=m;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"&&Ye(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 f=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let m=d.schema;for(let f in m)delete m[f];m.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
467
470
|
|
|
468
|
-
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 h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){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),h=m.def??m.schema,p={...h};if(m.ref===null)return;let f=m.ref;if(m.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}m.isParent||this.override({zodSchema:l,jsonSchema:h,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 Ok=S(()=>{});var kt=S(()=>{Os();$m();bm();bk();nu();Im();Lr();ru();uu();Sf();Om();Rk();Pk();Ck();Ok()});var lh=S(()=>{kt()});function dh(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new n1(r)}var r1,n1,Ik=S(()=>{kt();kt();lh();r1=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>vm(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Io(t,r,n),t.parseAsync=async(r,n)=>km(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ao(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)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),n1=T("ZodMiniObject",(t,e)=>{au.init(t,e),r1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Ak=S(()=>{});var Nk=S(()=>{});var Dk=S(()=>{});var Mk=S(()=>{kt();lh();Ik();Ak();kt();uu();Nk();Dk()});var jk=S(()=>{Mk()});var ph=S(()=>{jk()});function nr(t){return!!t._zod}function Mo(t){let e=Object.values(t);if(e.length===0)return dh({});let r=e.every(nr),n=e.every(o=>!nr(o));if(r)return dh(t);if(n)return im(t);throw new Error("Mixed Zod versions detected in object shape.")}function An(t,e){return nr(t)?Io(t,e):t.safeParse(e)}async function yu(t,e){return nr(t)?await Ao(t,e):await t.safeParseAsync(e)}function Nn(t){if(!t)return;let e;if(nr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ds(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 Mo(t)}}if(nr(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 _u(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function zk(t){return t.description}function Fk(t){if(nr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function bu(t){if(nr(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}var oa=S(()=>{qi();ph()});var mh=S(()=>{kt()});var sa={};we(sa,{ZodISODate:()=>Uk,ZodISODateTime:()=>Hk,ZodISODuration:()=>Zk,ZodISOTime:()=>Bk,date:()=>hh,datetime:()=>fh,duration:()=>yh,time:()=>gh});function fh(t){return kk(Hk,t)}function hh(t){return wk(Uk,t)}function gh(t){return Ek(Bk,t)}function yh(t){return $k(Zk,t)}var Hk,Uk,Bk,Zk,_h=S(()=>{kt();bh();Hk=T("ZodISODateTime",(t,e)=>{fk.init(t,e),Me.init(t,e)});Uk=T("ZodISODate",(t,e)=>{hk.init(t,e),Me.init(t,e)});Bk=T("ZodISOTime",(t,e)=>{gk.init(t,e),Me.init(t,e)});Zk=T("ZodISODuration",(t,e)=>{yk.init(t,e),Me.init(t,e)})});var qk,e6,ia,xh=S(()=>{kt();kt();qk=(t,e)=>{eu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>_m(t,r)},flatten:{value:r=>ym(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},e6=T("ZodError",qk),ia=T("ZodError",qk,{Parent:Error})});var Vk,Wk,Kk,Gk,vh=S(()=>{kt();xh();Vk=xm(ia),Wk=Sm(ia),Kk=wm(ia),Gk=Em(ia)});function $(t){return kf(m1,t)}function ye(t){return qf(e0,t)}function Xk(t){return Vf(O1,t)}function ot(t){return Wf(I1,t)}function t0(t){return Kf(A1,t)}function je(){return Gf(N1)}function M1(t){return Jf(D1,t)}function le(t,e){return Tk(j1,t,e)}function H(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new r0(r)}function wt(t,e){return new r0({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:je(),...ue.normalizeParams(e)})}function Ie(t,e){return new n0({type:"union",options:t,...ue.normalizeParams(e)})}function wh(t,e,r){return new L1({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function vu(t,e){return new z1({type:"intersection",left:t,right:e})}function Re(t,e,r){return new F1({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Sh({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new H1({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function o0(t){return new U1({type:"transform",transform:t})}function Le(t){return new s0({type:"optional",innerType:t})}function Yk(t){return new B1({type:"nullable",innerType:t})}function q1(t,e){return new Z1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function W1(t,e){return new V1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function K1(t,e){return new i0({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function J1(t,e){return new G1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function kh(t,e){return new X1({type:"pipe",in:t,out:e})}function Q1(t){return new Y1({type:"readonly",innerType:t})}function eM(t){let e=new it({check:"custom"});return e._zod.check=t,e}function c0(t,e){return ah(a0,t??(()=>!0),e)}function tM(t,e={}){return ch(a0,t,e)}function rM(t){let e=eM(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.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(ue.issue(o))}},t(r.value,r)));return e}function Eh(t,e){return kh(o0(t),e)}var Ue,Qk,m1,Me,f1,Jk,xu,h1,g1,y1,_1,b1,x1,v1,S1,k1,w1,E1,$1,T1,P1,R1,C1,e0,O1,I1,A1,N1,D1,j1,r0,n0,L1,z1,F1,Sh,H1,U1,s0,B1,Z1,V1,i0,G1,X1,Y1,a0,bh=S(()=>{kt();kt();mh();_h();vh();Ue=T("ZodType",(t,e)=>(ve.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)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Vk(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Kk(t,r,n),t.parseAsync=async(r,n)=>Wk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gk(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(tM(r,n)),t.superRefine=r=>t.check(rM(r)),t.overwrite=r=>t.check(No(r)),t.optional=()=>Le(t),t.nullable=()=>Yk(t),t.nullish=()=>Le(Yk(t)),t.nonoptional=r=>K1(t,r),t.array=()=>le(t),t.or=r=>Ie([t,r]),t.and=r=>vu(t,r),t.transform=r=>kh(t,o0(r)),t.default=r=>q1(t,r),t.prefault=r=>W1(t,r),t.catch=r=>J1(t,r),t.pipe=r=>kh(t,r),t.readonly=()=>Q1(t),t.describe=r=>{let n=t.clone();return In.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return In.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return In.get(t);let n=t.clone();return In.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Qk=T("_ZodString",(t,e)=>{ea.init(t,e),Ue.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(Xf(...n)),t.includes=(...n)=>t.check(eh(...n)),t.startsWith=(...n)=>t.check(th(...n)),t.endsWith=(...n)=>t.check(rh(...n)),t.min=(...n)=>t.check(Ns(...n)),t.max=(...n)=>t.check(fu(...n)),t.length=(...n)=>t.check(hu(...n)),t.nonempty=(...n)=>t.check(Ns(1,...n)),t.lowercase=n=>t.check(Yf(n)),t.uppercase=n=>t.check(Qf(n)),t.trim=()=>t.check(oh()),t.normalize=(...n)=>t.check(nh(...n)),t.toLowerCase=()=>t.check(sh()),t.toUpperCase=()=>t.check(ih())}),m1=T("ZodString",(t,e)=>{ea.init(t,e),Qk.init(t,e),t.email=r=>t.check(wf(f1,r)),t.url=r=>t.check(Rf(h1,r)),t.jwt=r=>t.check(Zf(C1,r)),t.emoji=r=>t.check(Cf(g1,r)),t.guid=r=>t.check(lu(Jk,r)),t.uuid=r=>t.check(Ef(xu,r)),t.uuidv4=r=>t.check($f(xu,r)),t.uuidv6=r=>t.check(Tf(xu,r)),t.uuidv7=r=>t.check(Pf(xu,r)),t.nanoid=r=>t.check(Of(y1,r)),t.guid=r=>t.check(lu(Jk,r)),t.cuid=r=>t.check(If(_1,r)),t.cuid2=r=>t.check(Af(b1,r)),t.ulid=r=>t.check(Nf(x1,r)),t.base64=r=>t.check(Hf(T1,r)),t.base64url=r=>t.check(Uf(P1,r)),t.xid=r=>t.check(Df(v1,r)),t.ksuid=r=>t.check(Mf(S1,r)),t.ipv4=r=>t.check(jf(k1,r)),t.ipv6=r=>t.check(Lf(w1,r)),t.cidrv4=r=>t.check(zf(E1,r)),t.cidrv6=r=>t.check(Ff($1,r)),t.e164=r=>t.check(Bf(R1,r)),t.datetime=r=>t.check(fh(r)),t.date=r=>t.check(hh(r)),t.time=r=>t.check(gh(r)),t.duration=r=>t.check(yh(r))});Me=T("ZodStringFormat",(t,e)=>{Pe.init(t,e),Qk.init(t,e)}),f1=T("ZodEmail",(t,e)=>{Mm.init(t,e),Me.init(t,e)}),Jk=T("ZodGUID",(t,e)=>{Nm.init(t,e),Me.init(t,e)}),xu=T("ZodUUID",(t,e)=>{Dm.init(t,e),Me.init(t,e)}),h1=T("ZodURL",(t,e)=>{jm.init(t,e),Me.init(t,e)}),g1=T("ZodEmoji",(t,e)=>{Lm.init(t,e),Me.init(t,e)}),y1=T("ZodNanoID",(t,e)=>{zm.init(t,e),Me.init(t,e)}),_1=T("ZodCUID",(t,e)=>{Fm.init(t,e),Me.init(t,e)}),b1=T("ZodCUID2",(t,e)=>{Hm.init(t,e),Me.init(t,e)}),x1=T("ZodULID",(t,e)=>{Um.init(t,e),Me.init(t,e)}),v1=T("ZodXID",(t,e)=>{Bm.init(t,e),Me.init(t,e)}),S1=T("ZodKSUID",(t,e)=>{Zm.init(t,e),Me.init(t,e)}),k1=T("ZodIPv4",(t,e)=>{qm.init(t,e),Me.init(t,e)}),w1=T("ZodIPv6",(t,e)=>{Vm.init(t,e),Me.init(t,e)}),E1=T("ZodCIDRv4",(t,e)=>{Wm.init(t,e),Me.init(t,e)}),$1=T("ZodCIDRv6",(t,e)=>{Km.init(t,e),Me.init(t,e)}),T1=T("ZodBase64",(t,e)=>{Gm.init(t,e),Me.init(t,e)}),P1=T("ZodBase64URL",(t,e)=>{Jm.init(t,e),Me.init(t,e)}),R1=T("ZodE164",(t,e)=>{Xm.init(t,e),Me.init(t,e)}),C1=T("ZodJWT",(t,e)=>{Ym.init(t,e),Me.init(t,e)}),e0=T("ZodNumber",(t,e)=>{iu.init(t,e),Ue.init(t,e),t.gt=(n,o)=>t.check(pu(n,o)),t.gte=(n,o)=>t.check(na(n,o)),t.min=(n,o)=>t.check(na(n,o)),t.lt=(n,o)=>t.check(du(n,o)),t.lte=(n,o)=>t.check(ra(n,o)),t.max=(n,o)=>t.check(ra(n,o)),t.int=n=>t.check(Xk(n)),t.safe=n=>t.check(Xk(n)),t.positive=n=>t.check(pu(0,n)),t.nonnegative=n=>t.check(na(0,n)),t.negative=n=>t.check(du(0,n)),t.nonpositive=n=>t.check(ra(0,n)),t.multipleOf=(n,o)=>t.check(mu(n,o)),t.step=(n,o)=>t.check(mu(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});O1=T("ZodNumberFormat",(t,e)=>{Qm.init(t,e),e0.init(t,e)});I1=T("ZodBoolean",(t,e)=>{ef.init(t,e),Ue.init(t,e)});A1=T("ZodNull",(t,e)=>{tf.init(t,e),Ue.init(t,e)});N1=T("ZodUnknown",(t,e)=>{rf.init(t,e),Ue.init(t,e)});D1=T("ZodNever",(t,e)=>{nf.init(t,e),Ue.init(t,e)});j1=T("ZodArray",(t,e)=>{of.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ns(r,n)),t.nonempty=r=>t.check(Ns(1,r)),t.max=(r,n)=>t.check(fu(r,n)),t.length=(r,n)=>t.check(hu(r,n)),t.unwrap=()=>t.element});r0=T("ZodObject",(t,e)=>{au.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:je()}),t.loose=()=>t.clone({...t._zod.def,catchall:je()}),t.strict=()=>t.clone({...t._zod.def,catchall:M1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(s0,t,r[0]),t.required=(...r)=>ue.required(i0,t,r[0])});n0=T("ZodUnion",(t,e)=>{cu.init(t,e),Ue.init(t,e),t.options=e.options});L1=T("ZodDiscriminatedUnion",(t,e)=>{n0.init(t,e),sf.init(t,e)});z1=T("ZodIntersection",(t,e)=>{af.init(t,e),Ue.init(t,e)});F1=T("ZodRecord",(t,e)=>{cf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Sh=T("ZodEnum",(t,e)=>{uf.init(t,e),Ue.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 Sh({...e,checks:[],...ue.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 Sh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});H1=T("ZodLiteral",(t,e)=>{lf.init(t,e),Ue.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]}})});U1=T("ZodTransform",(t,e)=>{df.init(t,e),Ue.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.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(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});s0=T("ZodOptional",(t,e)=>{pf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});B1=T("ZodNullable",(t,e)=>{mf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});Z1=T("ZodDefault",(t,e)=>{ff.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});V1=T("ZodPrefault",(t,e)=>{hf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});i0=T("ZodNonOptional",(t,e)=>{gf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});G1=T("ZodCatch",(t,e)=>{yf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});X1=T("ZodPipe",(t,e)=>{_f.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});Y1=T("ZodReadonly",(t,e)=>{bf.init(t,e),Ue.init(t,e)});a0=T("ZodCustom",(t,e)=>{xf.init(t,e),Ue.init(t,e)})});var u0=S(()=>{});var l0=S(()=>{});var d0=S(()=>{kt();bh();mh();xh();vh();u0();kt();vk();uu();_h();l0();Ft(xk())});var p0=S(()=>{d0()});var m0=S(()=>{p0()});function C0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function O0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Th,f0,Dn,ku,Qe,h0,g0,g6,sM,iM,Ph,Ut,aa,y0,at,or,sr,ct,wu,_0,Rh,b0,x0,Ch,ca,G,Oh,v0,S0,y6,Eu,aM,$u,cM,ua,Ms,k0,uM,lM,dM,pM,mM,fM,Ih,hM,gM,Ah,Tu,yM,_M,Pu,bM,la,da,xM,pa,js,vM,ma,Ru,Cu,Ou,_6,Iu,Au,Nu,w0,E0,$0,Nh,T0,fa,Ls,P0,SM,zs,kM,Fs,wM,Dh,EM,Du,$M,TM,PM,RM,CM,OM,IM,AM,NM,DM,Hs,MM,jM,Mu,Mh,jh,Lh,LM,zM,FM,zh,HM,UM,BM,ZM,qM,R0,Us,VM,ju,b6,WM,Bs,KM,x6,ha,GM,Fh,JM,XM,YM,QM,ej,tj,rj,Su,nj,oj,sj,ga,Hh,ij,aj,cj,uj,lj,dj,pj,mj,fj,hj,gj,yj,_j,bj,xj,vj,Sj,kj,Zs,wj,Ej,$j,Lu,Tj,Pj,Rj,Uh,Cj,v6,S6,k6,w6,E6,$6,Z,$h,jo=S(()=>{m0();Th="2025-11-25",f0=[Th,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Dn="io.modelcontextprotocol/related-task",ku="2.0",Qe=c0(t=>t!==null&&(typeof t=="object"||typeof t=="function")),h0=Ie([$(),ye().int()]),g0=$(),g6=wt({ttl:ye().optional(),pollInterval:ye().optional()}),sM=H({ttl:ye().optional()}),iM=H({taskId:$()}),Ph=wt({progressToken:h0.optional(),[Dn]:iM.optional()}),Ut=H({_meta:Ph.optional()}),aa=Ut.extend({task:sM.optional()}),y0=t=>aa.safeParse(t).success,at=H({method:$(),params:Ut.loose().optional()}),or=H({_meta:Ph.optional()}),sr=H({method:$(),params:or.loose().optional()}),ct=wt({_meta:Ph.optional()}),wu=Ie([$(),ye().int()]),_0=H({jsonrpc:q(ku),id:wu,...at.shape}).strict(),Rh=t=>_0.safeParse(t).success,b0=H({jsonrpc:q(ku),...sr.shape}).strict(),x0=t=>b0.safeParse(t).success,Ch=H({jsonrpc:q(ku),id:wu,result:ct}).strict(),ca=t=>Ch.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"})(G||(G={}));Oh=H({jsonrpc:q(ku),id:wu.optional(),error:H({code:ye().int(),message:$(),data:je().optional()})}).strict(),v0=t=>Oh.safeParse(t).success,S0=Ie([_0,b0,Ch,Oh]),y6=Ie([Ch,Oh]),Eu=ct.strict(),aM=or.extend({requestId:wu.optional(),reason:$().optional()}),$u=sr.extend({method:q("notifications/cancelled"),params:aM}),cM=H({src:$(),mimeType:$().optional(),sizes:le($()).optional(),theme:At(["light","dark"]).optional()}),ua=H({icons:le(cM).optional()}),Ms=H({name:$(),title:$().optional()}),k0=Ms.extend({...Ms.shape,...ua.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),uM=vu(H({applyDefaults:ot().optional()}),Re($(),je())),lM=Eh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,vu(H({form:uM.optional(),url:Qe.optional()}),Re($(),je()).optional())),dM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({sampling:wt({createMessage:Qe.optional()}).optional(),elicitation:wt({create:Qe.optional()}).optional()}).optional()}),pM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({tools:wt({call:Qe.optional()}).optional()}).optional()}),mM=H({experimental:Re($(),Qe).optional(),sampling:H({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:lM.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:dM.optional(),extensions:Re($(),Qe).optional()}),fM=Ut.extend({protocolVersion:$(),capabilities:mM,clientInfo:k0}),Ih=at.extend({method:q("initialize"),params:fM}),hM=H({experimental:Re($(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:pM.optional(),extensions:Re($(),Qe).optional()}),gM=ct.extend({protocolVersion:$(),capabilities:hM,serverInfo:k0,instructions:$().optional()}),Ah=sr.extend({method:q("notifications/initialized"),params:or.optional()}),Tu=at.extend({method:q("ping"),params:Ut.optional()}),yM=H({progress:ye(),total:Le(ye()),message:Le($())}),_M=H({...or.shape,...yM.shape,progressToken:h0}),Pu=sr.extend({method:q("notifications/progress"),params:_M}),bM=Ut.extend({cursor:g0.optional()}),la=at.extend({params:bM.optional()}),da=ct.extend({nextCursor:g0.optional()}),xM=At(["working","input_required","completed","failed","cancelled"]),pa=H({taskId:$(),status:xM,ttl:Ie([ye(),t0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Le(ye()),statusMessage:Le($())}),js=ct.extend({task:pa}),vM=or.merge(pa),ma=sr.extend({method:q("notifications/tasks/status"),params:vM}),Ru=at.extend({method:q("tasks/get"),params:Ut.extend({taskId:$()})}),Cu=ct.merge(pa),Ou=at.extend({method:q("tasks/result"),params:Ut.extend({taskId:$()})}),_6=ct.loose(),Iu=la.extend({method:q("tasks/list")}),Au=da.extend({tasks:le(pa)}),Nu=at.extend({method:q("tasks/cancel"),params:Ut.extend({taskId:$()})}),w0=ct.merge(pa),E0=H({uri:$(),mimeType:Le($()),_meta:Re($(),je()).optional()}),$0=E0.extend({text:$()}),Nh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),T0=E0.extend({blob:Nh}),fa=At(["user","assistant"]),Ls=H({audience:le(fa).optional(),priority:ye().min(0).max(1).optional(),lastModified:sa.datetime({offset:!0}).optional()}),P0=H({...Ms.shape,...ua.shape,uri:$(),description:Le($()),mimeType:Le($()),size:Le(ye()),annotations:Ls.optional(),_meta:Le(wt({}))}),SM=H({...Ms.shape,...ua.shape,uriTemplate:$(),description:Le($()),mimeType:Le($()),annotations:Ls.optional(),_meta:Le(wt({}))}),zs=la.extend({method:q("resources/list")}),kM=da.extend({resources:le(P0)}),Fs=la.extend({method:q("resources/templates/list")}),wM=da.extend({resourceTemplates:le(SM)}),Dh=Ut.extend({uri:$()}),EM=Dh,Du=at.extend({method:q("resources/read"),params:EM}),$M=ct.extend({contents:le(Ie([$0,T0]))}),TM=sr.extend({method:q("notifications/resources/list_changed"),params:or.optional()}),PM=Dh,RM=at.extend({method:q("resources/subscribe"),params:PM}),CM=Dh,OM=at.extend({method:q("resources/unsubscribe"),params:CM}),IM=or.extend({uri:$()}),AM=sr.extend({method:q("notifications/resources/updated"),params:IM}),NM=H({name:$(),description:Le($()),required:Le(ot())}),DM=H({...Ms.shape,...ua.shape,description:Le($()),arguments:Le(le(NM)),_meta:Le(wt({}))}),Hs=la.extend({method:q("prompts/list")}),MM=da.extend({prompts:le(DM)}),jM=Ut.extend({name:$(),arguments:Re($(),$()).optional()}),Mu=at.extend({method:q("prompts/get"),params:jM}),Mh=H({type:q("text"),text:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),jh=H({type:q("image"),data:Nh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),Lh=H({type:q("audio"),data:Nh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),LM=H({type:q("tool_use"),name:$(),id:$(),input:Re($(),je()),_meta:Re($(),je()).optional()}),zM=H({type:q("resource"),resource:Ie([$0,T0]),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),FM=P0.extend({type:q("resource_link")}),zh=Ie([Mh,jh,Lh,FM,zM]),HM=H({role:fa,content:zh}),UM=ct.extend({description:$().optional(),messages:le(HM)}),BM=sr.extend({method:q("notifications/prompts/list_changed"),params:or.optional()}),ZM=H({title:$().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),qM=H({taskSupport:At(["required","optional","forbidden"]).optional()}),R0=H({...Ms.shape,...ua.shape,description:$().optional(),inputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()),outputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()).optional(),annotations:ZM.optional(),execution:qM.optional(),_meta:Re($(),je()).optional()}),Us=la.extend({method:q("tools/list")}),VM=da.extend({tools:le(R0)}),ju=ct.extend({content:le(zh).default([]),structuredContent:Re($(),je()).optional(),isError:ot().optional()}),b6=ju.or(ct.extend({toolResult:je()})),WM=aa.extend({name:$(),arguments:Re($(),je()).optional()}),Bs=at.extend({method:q("tools/call"),params:WM}),KM=sr.extend({method:q("notifications/tools/list_changed"),params:or.optional()}),x6=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),ha=At(["debug","info","notice","warning","error","critical","alert","emergency"]),GM=Ut.extend({level:ha}),Fh=at.extend({method:q("logging/setLevel"),params:GM}),JM=or.extend({level:ha,logger:$().optional(),data:je()}),XM=sr.extend({method:q("notifications/message"),params:JM}),YM=H({name:$().optional()}),QM=H({hints:le(YM).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),ej=H({mode:At(["auto","required","none"]).optional()}),tj=H({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:le(zh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:Re($(),je()).optional()}),rj=wh("type",[Mh,jh,Lh]),Su=wh("type",[Mh,jh,Lh,LM,tj]),nj=H({role:fa,content:Ie([Su,le(Su)]),_meta:Re($(),je()).optional()}),oj=aa.extend({messages:le(nj),modelPreferences:QM.optional(),systemPrompt:$().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le($()).optional(),metadata:Qe.optional(),tools:le(R0).optional(),toolChoice:ej.optional()}),sj=at.extend({method:q("sampling/createMessage"),params:oj}),ga=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens"]).or($())),role:fa,content:rj}),Hh=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:fa,content:Ie([Su,le(Su)])}),ij=H({type:q("boolean"),title:$().optional(),description:$().optional(),default:ot().optional()}),aj=H({type:q("string"),title:$().optional(),description:$().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:$().optional()}),cj=H({type:At(["number","integer"]),title:$().optional(),description:$().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),uj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),default:$().optional()}),lj=H({type:q("string"),title:$().optional(),description:$().optional(),oneOf:le(H({const:$(),title:$()})),default:$().optional()}),dj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),enumNames:le($()).optional(),default:$().optional()}),pj=Ie([uj,lj]),mj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le($())}),default:le($()).optional()}),fj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:$(),title:$()}))}),default:le($()).optional()}),hj=Ie([mj,fj]),gj=Ie([dj,pj,hj]),yj=Ie([gj,ij,aj,cj]),_j=aa.extend({mode:q("form").optional(),message:$(),requestedSchema:H({type:q("object"),properties:Re($(),yj),required:le($()).optional()})}),bj=aa.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),xj=Ie([_j,bj]),vj=at.extend({method:q("elicitation/create"),params:xj}),Sj=or.extend({elicitationId:$()}),kj=sr.extend({method:q("notifications/elicitation/complete"),params:Sj}),Zs=ct.extend({action:At(["accept","decline","cancel"]),content:Eh(t=>t===null?void 0:t,Re($(),Ie([$(),ye(),ot(),le($())])).optional())}),wj=H({type:q("ref/resource"),uri:$()}),Ej=H({type:q("ref/prompt"),name:$()}),$j=Ut.extend({ref:Ie([Ej,wj]),argument:H({name:$(),value:$()}),context:H({arguments:Re($(),$()).optional()}).optional()}),Lu=at.extend({method:q("completion/complete"),params:$j});Tj=ct.extend({completion:wt({values:le($()).max(100),total:Le(ye().int()),hasMore:Le(ot())})}),Pj=H({uri:$().startsWith("file://"),name:$().optional(),_meta:Re($(),je()).optional()}),Rj=at.extend({method:q("roots/list"),params:Ut.optional()}),Uh=ct.extend({roots:le(Pj)}),Cj=sr.extend({method:q("notifications/roots/list_changed"),params:or.optional()}),v6=Ie([Tu,Ih,Lu,Fh,Mu,Hs,zs,Fs,Du,RM,OM,Bs,Us,Ru,Ou,Iu,Nu]),S6=Ie([$u,Pu,Ah,Cj,ma]),k6=Ie([Eu,ga,Hh,Zs,Uh,Cu,Au,js]),w6=Ie([Tu,sj,vj,Rj,Ru,Ou,Iu,Nu]),E6=Ie([$u,Pu,XM,AM,TM,KM,BM,ma,kj]),$6=Ie([Eu,gM,Tj,UM,MM,kM,wM,$M,ju,VM,Cu,Au,js]),Z=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===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new $h(o.elicitations,r)}return new t(e,r,n)}},$h=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Mn(t){return t==="completed"||t==="failed"||t==="cancelled"}var I0=S(()=>{});var N0,A0,D0,zu=S(()=>{N0=Symbol("Let zodToJsonSchema decide on which parser to use"),A0={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"},D0=t=>typeof t=="string"?{...A0,name:t}:{...A0,...t}});var M0,Bh=S(()=>{zu();M0=t=>{let e=D0(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 Zh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,Zh(t,e,n,o)}var jn=S(()=>{});var Fu,Hu=S(()=>{Fu=(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 ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Fu(e,t.currentPath):e.join("/")}}var ir=S(()=>{Hu()});function j0(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var qh=S(()=>{qi();jn();Ge()});function L0(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?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Vh=S(()=>{jn()});function z0(){return{type:"boolean"}}var Wh=S(()=>{});function Uu(t,e){return Y(t.type._def,e)}var Bu=S(()=>{Ge()});var F0,Kh=S(()=>{Ge();F0=(t,e)=>Y(t.innerType._def,e)});function Gh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Gh(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 Oj(t,e)}}var Oj,Jh=S(()=>{jn();Oj=(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":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function H0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Xh=S(()=>{Ge()});function U0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):ze(e)}var Yh=S(()=>{Ge();ir()});function B0(t){return{type:"string",enum:Array.from(t.values)}}var Qh=S(()=>{});function Z0(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(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(Ij(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}var Ij,eg=S(()=>{Ge();Ij=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function q0(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 tg=S(()=>{});function Zu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(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":_r(r,"email",n.message,e);break;case"format:idn-email":_r(r,"idn-email",n.message,e);break;case"pattern:zod":Et(r,yr.email,n.message,e);break}break;case"url":_r(r,"uri",n.message,e);break;case"uuid":_r(r,"uuid",n.message,e);break;case"regex":Et(r,n.regex,n.message,e);break;case"cuid":Et(r,yr.cuid,n.message,e);break;case"cuid2":Et(r,yr.cuid2,n.message,e);break;case"startsWith":Et(r,RegExp(`^${ng(n.value,e)}`),n.message,e);break;case"endsWith":Et(r,RegExp(`${ng(n.value,e)}$`),n.message,e);break;case"datetime":_r(r,"date-time",n.message,e);break;case"date":_r(r,"date",n.message,e);break;case"time":_r(r,"time",n.message,e);break;case"duration":_r(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Et(r,RegExp(ng(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&_r(r,"ipv4",n.message,e),n.version!=="v4"&&_r(r,"ipv6",n.message,e);break}case"base64url":Et(r,yr.base64url,n.message,e);break;case"jwt":Et(r,yr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Et(r,yr.ipv4Cidr,n.message,e),n.version!=="v4"&&Et(r,yr.ipv6Cidr,n.message,e);break}case"emoji":Et(r,yr.emoji(),n.message,e);break;case"ulid":{Et(r,yr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_r(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Et(r,yr.base64,n.message,e);break}}break}case"nanoid":Et(r,yr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ng(t,e){return e.patternStrategy==="escape"?Nj(t):t}function Nj(t){let e="";for(let r=0;r<t.length;r++)Aj.has(t[r])||(e+="\\"),e+=t[r];return e}function _r(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}}})):de(t,"format",e,r,n)}function Et(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:V0(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",V0(e,n),r,n)}function V0(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
|
|
471
|
+
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 h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),h=p.def??p.schema,m={...h};if(p.ref===null)return;let f=p.ref;if(p.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,m))}p.isParent||this.override({zodSchema:l,jsonSchema:h,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Nk=S(()=>{});var kt=S(()=>{Os();Pm();vm();Sk();ou();Nm();Lr();nu();lu();wf();Am();Ik();Ok();Ak();Nk()});var ph=S(()=>{kt()});function mh(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new c1(r)}var a1,c1,Dk=S(()=>{kt();kt();ph();a1=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>km(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Io(t,r,n),t.parseAsync=async(r,n)=>Em(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ao(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)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),c1=T("ZodMiniObject",(t,e)=>{cu.init(t,e),a1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Mk=S(()=>{});var jk=S(()=>{});var Lk=S(()=>{});var zk=S(()=>{kt();ph();Dk();Mk();kt();lu();jk();Lk()});var Fk=S(()=>{zk()});var fh=S(()=>{Fk()});function nr(t){return!!t._zod}function Mo(t){let e=Object.values(t);if(e.length===0)return mh({});let r=e.every(nr),n=e.every(o=>!nr(o));if(r)return mh(t);if(n)return cm(t);throw new Error("Mixed Zod versions detected in object shape.")}function Nn(t,e){return nr(t)?Io(t,e):t.safeParse(e)}async function _u(t,e){return nr(t)?await Ao(t,e):await t.safeParseAsync(e)}function Dn(t){if(!t)return;let e;if(nr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ds(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 Mo(t)}}if(nr(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 xu(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Uk(t){return t.description}function Bk(t){if(nr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function bu(t){if(nr(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}var oa=S(()=>{qi();fh()});var hh=S(()=>{kt()});var sa={};we(sa,{ZodISODate:()=>qk,ZodISODateTime:()=>Zk,ZodISODuration:()=>Wk,ZodISOTime:()=>Vk,date:()=>yh,datetime:()=>gh,duration:()=>xh,time:()=>_h});function gh(t){return $k(Zk,t)}function yh(t){return Tk(qk,t)}function _h(t){return Pk(Vk,t)}function xh(t){return Rk(Wk,t)}var Zk,qk,Vk,Wk,bh=S(()=>{kt();vh();Zk=T("ZodISODateTime",(t,e)=>{yk.init(t,e),Me.init(t,e)});qk=T("ZodISODate",(t,e)=>{_k.init(t,e),Me.init(t,e)});Vk=T("ZodISOTime",(t,e)=>{xk.init(t,e),Me.init(t,e)});Wk=T("ZodISODuration",(t,e)=>{bk.init(t,e),Me.init(t,e)})});var Kk,s6,ia,Sh=S(()=>{kt();kt();Kk=(t,e)=>{tu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bm(t,r)},flatten:{value:r=>xm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},s6=T("ZodError",Kk),ia=T("ZodError",Kk,{Parent:Error})});var Gk,Jk,Xk,Yk,kh=S(()=>{kt();Sh();Gk=Sm(ia),Jk=wm(ia),Xk=$m(ia),Yk=Tm(ia)});function $(t){return Ef(_1,t)}function ye(t){return Wf(n0,t)}function e0(t){return Kf(M1,t)}function ot(t){return Gf(j1,t)}function o0(t){return Jf(L1,t)}function je(){return Xf(z1)}function H1(t){return Yf(F1,t)}function le(t,e){return Ck(U1,t,e)}function H(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new s0(r)}function wt(t,e){return new s0({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:je(),...ue.normalizeParams(e)})}function Ie(t,e){return new i0({type:"union",options:t,...ue.normalizeParams(e)})}function $h(t,e,r){return new B1({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function Su(t,e){return new Z1({type:"intersection",left:t,right:e})}function Re(t,e,r){return new q1({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new wh({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new V1({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function a0(t){return new W1({type:"transform",transform:t})}function Le(t){return new c0({type:"optional",innerType:t})}function t0(t){return new K1({type:"nullable",innerType:t})}function J1(t,e){return new G1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Y1(t,e){return new X1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Q1(t,e){return new u0({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function tM(t,e){return new eM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Eh(t,e){return new rM({type:"pipe",in:t,out:e})}function oM(t){return new nM({type:"readonly",innerType:t})}function sM(t){let e=new it({check:"custom"});return e._zod.check=t,e}function d0(t,e){return uh(l0,t??(()=>!0),e)}function iM(t,e={}){return lh(l0,t,e)}function aM(t){let e=sM(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.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(ue.issue(o))}},t(r.value,r)));return e}function Th(t,e){return Eh(a0(t),e)}var Ue,r0,_1,Me,x1,Qk,vu,b1,v1,S1,k1,w1,E1,$1,T1,P1,R1,C1,O1,I1,A1,N1,D1,n0,M1,j1,L1,z1,F1,U1,s0,i0,B1,Z1,q1,wh,V1,W1,c0,K1,G1,X1,u0,eM,rM,nM,l0,vh=S(()=>{kt();kt();hh();bh();kh();Ue=T("ZodType",(t,e)=>(ve.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)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Gk(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Xk(t,r,n),t.parseAsync=async(r,n)=>Jk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yk(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(iM(r,n)),t.superRefine=r=>t.check(aM(r)),t.overwrite=r=>t.check(No(r)),t.optional=()=>Le(t),t.nullable=()=>t0(t),t.nullish=()=>Le(t0(t)),t.nonoptional=r=>Q1(t,r),t.array=()=>le(t),t.or=r=>Ie([t,r]),t.and=r=>Su(t,r),t.transform=r=>Eh(t,a0(r)),t.default=r=>J1(t,r),t.prefault=r=>Y1(t,r),t.catch=r=>tM(t,r),t.pipe=r=>Eh(t,r),t.readonly=()=>oM(t),t.describe=r=>{let n=t.clone();return An.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return An.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return An.get(t);let n=t.clone();return An.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),r0=T("_ZodString",(t,e)=>{ea.init(t,e),Ue.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(Qf(...n)),t.includes=(...n)=>t.check(rh(...n)),t.startsWith=(...n)=>t.check(nh(...n)),t.endsWith=(...n)=>t.check(oh(...n)),t.min=(...n)=>t.check(Ns(...n)),t.max=(...n)=>t.check(hu(...n)),t.length=(...n)=>t.check(gu(...n)),t.nonempty=(...n)=>t.check(Ns(1,...n)),t.lowercase=n=>t.check(eh(n)),t.uppercase=n=>t.check(th(n)),t.trim=()=>t.check(ih()),t.normalize=(...n)=>t.check(sh(...n)),t.toLowerCase=()=>t.check(ah()),t.toUpperCase=()=>t.check(ch())}),_1=T("ZodString",(t,e)=>{ea.init(t,e),r0.init(t,e),t.email=r=>t.check($f(x1,r)),t.url=r=>t.check(Of(b1,r)),t.jwt=r=>t.check(Vf(D1,r)),t.emoji=r=>t.check(If(v1,r)),t.guid=r=>t.check(du(Qk,r)),t.uuid=r=>t.check(Tf(vu,r)),t.uuidv4=r=>t.check(Pf(vu,r)),t.uuidv6=r=>t.check(Rf(vu,r)),t.uuidv7=r=>t.check(Cf(vu,r)),t.nanoid=r=>t.check(Af(S1,r)),t.guid=r=>t.check(du(Qk,r)),t.cuid=r=>t.check(Nf(k1,r)),t.cuid2=r=>t.check(Df(w1,r)),t.ulid=r=>t.check(Mf(E1,r)),t.base64=r=>t.check(Bf(I1,r)),t.base64url=r=>t.check(Zf(A1,r)),t.xid=r=>t.check(jf($1,r)),t.ksuid=r=>t.check(Lf(T1,r)),t.ipv4=r=>t.check(zf(P1,r)),t.ipv6=r=>t.check(Ff(R1,r)),t.cidrv4=r=>t.check(Hf(C1,r)),t.cidrv6=r=>t.check(Uf(O1,r)),t.e164=r=>t.check(qf(N1,r)),t.datetime=r=>t.check(gh(r)),t.date=r=>t.check(yh(r)),t.time=r=>t.check(_h(r)),t.duration=r=>t.check(xh(r))});Me=T("ZodStringFormat",(t,e)=>{Pe.init(t,e),r0.init(t,e)}),x1=T("ZodEmail",(t,e)=>{Lm.init(t,e),Me.init(t,e)}),Qk=T("ZodGUID",(t,e)=>{Mm.init(t,e),Me.init(t,e)}),vu=T("ZodUUID",(t,e)=>{jm.init(t,e),Me.init(t,e)}),b1=T("ZodURL",(t,e)=>{zm.init(t,e),Me.init(t,e)}),v1=T("ZodEmoji",(t,e)=>{Fm.init(t,e),Me.init(t,e)}),S1=T("ZodNanoID",(t,e)=>{Hm.init(t,e),Me.init(t,e)}),k1=T("ZodCUID",(t,e)=>{Um.init(t,e),Me.init(t,e)}),w1=T("ZodCUID2",(t,e)=>{Bm.init(t,e),Me.init(t,e)}),E1=T("ZodULID",(t,e)=>{Zm.init(t,e),Me.init(t,e)}),$1=T("ZodXID",(t,e)=>{qm.init(t,e),Me.init(t,e)}),T1=T("ZodKSUID",(t,e)=>{Vm.init(t,e),Me.init(t,e)}),P1=T("ZodIPv4",(t,e)=>{Wm.init(t,e),Me.init(t,e)}),R1=T("ZodIPv6",(t,e)=>{Km.init(t,e),Me.init(t,e)}),C1=T("ZodCIDRv4",(t,e)=>{Gm.init(t,e),Me.init(t,e)}),O1=T("ZodCIDRv6",(t,e)=>{Jm.init(t,e),Me.init(t,e)}),I1=T("ZodBase64",(t,e)=>{Xm.init(t,e),Me.init(t,e)}),A1=T("ZodBase64URL",(t,e)=>{Ym.init(t,e),Me.init(t,e)}),N1=T("ZodE164",(t,e)=>{Qm.init(t,e),Me.init(t,e)}),D1=T("ZodJWT",(t,e)=>{ef.init(t,e),Me.init(t,e)}),n0=T("ZodNumber",(t,e)=>{au.init(t,e),Ue.init(t,e),t.gt=(n,o)=>t.check(mu(n,o)),t.gte=(n,o)=>t.check(na(n,o)),t.min=(n,o)=>t.check(na(n,o)),t.lt=(n,o)=>t.check(pu(n,o)),t.lte=(n,o)=>t.check(ra(n,o)),t.max=(n,o)=>t.check(ra(n,o)),t.int=n=>t.check(e0(n)),t.safe=n=>t.check(e0(n)),t.positive=n=>t.check(mu(0,n)),t.nonnegative=n=>t.check(na(0,n)),t.negative=n=>t.check(pu(0,n)),t.nonpositive=n=>t.check(ra(0,n)),t.multipleOf=(n,o)=>t.check(fu(n,o)),t.step=(n,o)=>t.check(fu(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});M1=T("ZodNumberFormat",(t,e)=>{tf.init(t,e),n0.init(t,e)});j1=T("ZodBoolean",(t,e)=>{rf.init(t,e),Ue.init(t,e)});L1=T("ZodNull",(t,e)=>{nf.init(t,e),Ue.init(t,e)});z1=T("ZodUnknown",(t,e)=>{of.init(t,e),Ue.init(t,e)});F1=T("ZodNever",(t,e)=>{sf.init(t,e),Ue.init(t,e)});U1=T("ZodArray",(t,e)=>{af.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ns(r,n)),t.nonempty=r=>t.check(Ns(1,r)),t.max=(r,n)=>t.check(hu(r,n)),t.length=(r,n)=>t.check(gu(r,n)),t.unwrap=()=>t.element});s0=T("ZodObject",(t,e)=>{cu.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:je()}),t.loose=()=>t.clone({...t._zod.def,catchall:je()}),t.strict=()=>t.clone({...t._zod.def,catchall:H1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(c0,t,r[0]),t.required=(...r)=>ue.required(u0,t,r[0])});i0=T("ZodUnion",(t,e)=>{uu.init(t,e),Ue.init(t,e),t.options=e.options});B1=T("ZodDiscriminatedUnion",(t,e)=>{i0.init(t,e),cf.init(t,e)});Z1=T("ZodIntersection",(t,e)=>{uf.init(t,e),Ue.init(t,e)});q1=T("ZodRecord",(t,e)=>{lf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});wh=T("ZodEnum",(t,e)=>{df.init(t,e),Ue.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 wh({...e,checks:[],...ue.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 wh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});V1=T("ZodLiteral",(t,e)=>{pf.init(t,e),Ue.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]}})});W1=T("ZodTransform",(t,e)=>{mf.init(t,e),Ue.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.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(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});c0=T("ZodOptional",(t,e)=>{ff.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});K1=T("ZodNullable",(t,e)=>{hf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});G1=T("ZodDefault",(t,e)=>{gf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});X1=T("ZodPrefault",(t,e)=>{yf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});u0=T("ZodNonOptional",(t,e)=>{_f.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});eM=T("ZodCatch",(t,e)=>{xf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});rM=T("ZodPipe",(t,e)=>{bf.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});nM=T("ZodReadonly",(t,e)=>{vf.init(t,e),Ue.init(t,e)});l0=T("ZodCustom",(t,e)=>{Sf.init(t,e),Ue.init(t,e)})});var p0=S(()=>{});var m0=S(()=>{});var f0=S(()=>{kt();vh();hh();Sh();kh();p0();kt();wk();lu();bh();m0();Ft(kk())});var h0=S(()=>{f0()});var g0=S(()=>{h0()});function A0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function N0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Rh,y0,Mn,wu,Qe,_0,x0,v6,lM,dM,Ch,Ut,aa,b0,at,or,sr,ct,Eu,v0,Oh,S0,k0,Ih,ca,G,Ah,w0,E0,S6,$u,pM,Tu,mM,ua,Ms,$0,fM,hM,gM,yM,_M,xM,Nh,bM,vM,Dh,Pu,SM,kM,Ru,wM,la,da,EM,pa,js,$M,ma,Cu,Ou,Iu,k6,Au,Nu,Du,T0,P0,R0,Mh,C0,fa,Ls,O0,TM,zs,PM,Fs,RM,jh,CM,Mu,OM,IM,AM,NM,DM,MM,jM,LM,zM,FM,Hs,HM,UM,ju,Lh,zh,Fh,BM,ZM,qM,Hh,VM,WM,KM,GM,JM,I0,Us,XM,Lu,w6,YM,Bs,QM,E6,ha,ej,Uh,tj,rj,nj,oj,sj,ij,aj,ku,cj,uj,lj,ga,Bh,dj,pj,mj,fj,hj,gj,yj,_j,xj,bj,vj,Sj,kj,wj,Ej,$j,Tj,Pj,Zs,Rj,Cj,Oj,zu,Ij,Aj,Nj,Zh,Dj,$6,T6,P6,R6,C6,O6,Z,Ph,jo=S(()=>{g0();Rh="2025-11-25",y0=[Rh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mn="io.modelcontextprotocol/related-task",wu="2.0",Qe=d0(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_0=Ie([$(),ye().int()]),x0=$(),v6=wt({ttl:ye().optional(),pollInterval:ye().optional()}),lM=H({ttl:ye().optional()}),dM=H({taskId:$()}),Ch=wt({progressToken:_0.optional(),[Mn]:dM.optional()}),Ut=H({_meta:Ch.optional()}),aa=Ut.extend({task:lM.optional()}),b0=t=>aa.safeParse(t).success,at=H({method:$(),params:Ut.loose().optional()}),or=H({_meta:Ch.optional()}),sr=H({method:$(),params:or.loose().optional()}),ct=wt({_meta:Ch.optional()}),Eu=Ie([$(),ye().int()]),v0=H({jsonrpc:q(wu),id:Eu,...at.shape}).strict(),Oh=t=>v0.safeParse(t).success,S0=H({jsonrpc:q(wu),...sr.shape}).strict(),k0=t=>S0.safeParse(t).success,Ih=H({jsonrpc:q(wu),id:Eu,result:ct}).strict(),ca=t=>Ih.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"})(G||(G={}));Ah=H({jsonrpc:q(wu),id:Eu.optional(),error:H({code:ye().int(),message:$(),data:je().optional()})}).strict(),w0=t=>Ah.safeParse(t).success,E0=Ie([v0,S0,Ih,Ah]),S6=Ie([Ih,Ah]),$u=ct.strict(),pM=or.extend({requestId:Eu.optional(),reason:$().optional()}),Tu=sr.extend({method:q("notifications/cancelled"),params:pM}),mM=H({src:$(),mimeType:$().optional(),sizes:le($()).optional(),theme:At(["light","dark"]).optional()}),ua=H({icons:le(mM).optional()}),Ms=H({name:$(),title:$().optional()}),$0=Ms.extend({...Ms.shape,...ua.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),fM=Su(H({applyDefaults:ot().optional()}),Re($(),je())),hM=Th(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Su(H({form:fM.optional(),url:Qe.optional()}),Re($(),je()).optional())),gM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({sampling:wt({createMessage:Qe.optional()}).optional(),elicitation:wt({create:Qe.optional()}).optional()}).optional()}),yM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({tools:wt({call:Qe.optional()}).optional()}).optional()}),_M=H({experimental:Re($(),Qe).optional(),sampling:H({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:hM.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:gM.optional(),extensions:Re($(),Qe).optional()}),xM=Ut.extend({protocolVersion:$(),capabilities:_M,clientInfo:$0}),Nh=at.extend({method:q("initialize"),params:xM}),bM=H({experimental:Re($(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:yM.optional(),extensions:Re($(),Qe).optional()}),vM=ct.extend({protocolVersion:$(),capabilities:bM,serverInfo:$0,instructions:$().optional()}),Dh=sr.extend({method:q("notifications/initialized"),params:or.optional()}),Pu=at.extend({method:q("ping"),params:Ut.optional()}),SM=H({progress:ye(),total:Le(ye()),message:Le($())}),kM=H({...or.shape,...SM.shape,progressToken:_0}),Ru=sr.extend({method:q("notifications/progress"),params:kM}),wM=Ut.extend({cursor:x0.optional()}),la=at.extend({params:wM.optional()}),da=ct.extend({nextCursor:x0.optional()}),EM=At(["working","input_required","completed","failed","cancelled"]),pa=H({taskId:$(),status:EM,ttl:Ie([ye(),o0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Le(ye()),statusMessage:Le($())}),js=ct.extend({task:pa}),$M=or.merge(pa),ma=sr.extend({method:q("notifications/tasks/status"),params:$M}),Cu=at.extend({method:q("tasks/get"),params:Ut.extend({taskId:$()})}),Ou=ct.merge(pa),Iu=at.extend({method:q("tasks/result"),params:Ut.extend({taskId:$()})}),k6=ct.loose(),Au=la.extend({method:q("tasks/list")}),Nu=da.extend({tasks:le(pa)}),Du=at.extend({method:q("tasks/cancel"),params:Ut.extend({taskId:$()})}),T0=ct.merge(pa),P0=H({uri:$(),mimeType:Le($()),_meta:Re($(),je()).optional()}),R0=P0.extend({text:$()}),Mh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),C0=P0.extend({blob:Mh}),fa=At(["user","assistant"]),Ls=H({audience:le(fa).optional(),priority:ye().min(0).max(1).optional(),lastModified:sa.datetime({offset:!0}).optional()}),O0=H({...Ms.shape,...ua.shape,uri:$(),description:Le($()),mimeType:Le($()),size:Le(ye()),annotations:Ls.optional(),_meta:Le(wt({}))}),TM=H({...Ms.shape,...ua.shape,uriTemplate:$(),description:Le($()),mimeType:Le($()),annotations:Ls.optional(),_meta:Le(wt({}))}),zs=la.extend({method:q("resources/list")}),PM=da.extend({resources:le(O0)}),Fs=la.extend({method:q("resources/templates/list")}),RM=da.extend({resourceTemplates:le(TM)}),jh=Ut.extend({uri:$()}),CM=jh,Mu=at.extend({method:q("resources/read"),params:CM}),OM=ct.extend({contents:le(Ie([R0,C0]))}),IM=sr.extend({method:q("notifications/resources/list_changed"),params:or.optional()}),AM=jh,NM=at.extend({method:q("resources/subscribe"),params:AM}),DM=jh,MM=at.extend({method:q("resources/unsubscribe"),params:DM}),jM=or.extend({uri:$()}),LM=sr.extend({method:q("notifications/resources/updated"),params:jM}),zM=H({name:$(),description:Le($()),required:Le(ot())}),FM=H({...Ms.shape,...ua.shape,description:Le($()),arguments:Le(le(zM)),_meta:Le(wt({}))}),Hs=la.extend({method:q("prompts/list")}),HM=da.extend({prompts:le(FM)}),UM=Ut.extend({name:$(),arguments:Re($(),$()).optional()}),ju=at.extend({method:q("prompts/get"),params:UM}),Lh=H({type:q("text"),text:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),zh=H({type:q("image"),data:Mh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),Fh=H({type:q("audio"),data:Mh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),BM=H({type:q("tool_use"),name:$(),id:$(),input:Re($(),je()),_meta:Re($(),je()).optional()}),ZM=H({type:q("resource"),resource:Ie([R0,C0]),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),qM=O0.extend({type:q("resource_link")}),Hh=Ie([Lh,zh,Fh,qM,ZM]),VM=H({role:fa,content:Hh}),WM=ct.extend({description:$().optional(),messages:le(VM)}),KM=sr.extend({method:q("notifications/prompts/list_changed"),params:or.optional()}),GM=H({title:$().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),JM=H({taskSupport:At(["required","optional","forbidden"]).optional()}),I0=H({...Ms.shape,...ua.shape,description:$().optional(),inputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()),outputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()).optional(),annotations:GM.optional(),execution:JM.optional(),_meta:Re($(),je()).optional()}),Us=la.extend({method:q("tools/list")}),XM=da.extend({tools:le(I0)}),Lu=ct.extend({content:le(Hh).default([]),structuredContent:Re($(),je()).optional(),isError:ot().optional()}),w6=Lu.or(ct.extend({toolResult:je()})),YM=aa.extend({name:$(),arguments:Re($(),je()).optional()}),Bs=at.extend({method:q("tools/call"),params:YM}),QM=sr.extend({method:q("notifications/tools/list_changed"),params:or.optional()}),E6=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),ha=At(["debug","info","notice","warning","error","critical","alert","emergency"]),ej=Ut.extend({level:ha}),Uh=at.extend({method:q("logging/setLevel"),params:ej}),tj=or.extend({level:ha,logger:$().optional(),data:je()}),rj=sr.extend({method:q("notifications/message"),params:tj}),nj=H({name:$().optional()}),oj=H({hints:le(nj).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),sj=H({mode:At(["auto","required","none"]).optional()}),ij=H({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:le(Hh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:Re($(),je()).optional()}),aj=$h("type",[Lh,zh,Fh]),ku=$h("type",[Lh,zh,Fh,BM,ij]),cj=H({role:fa,content:Ie([ku,le(ku)]),_meta:Re($(),je()).optional()}),uj=aa.extend({messages:le(cj),modelPreferences:oj.optional(),systemPrompt:$().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le($()).optional(),metadata:Qe.optional(),tools:le(I0).optional(),toolChoice:sj.optional()}),lj=at.extend({method:q("sampling/createMessage"),params:uj}),ga=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens"]).or($())),role:fa,content:aj}),Bh=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:fa,content:Ie([ku,le(ku)])}),dj=H({type:q("boolean"),title:$().optional(),description:$().optional(),default:ot().optional()}),pj=H({type:q("string"),title:$().optional(),description:$().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:$().optional()}),mj=H({type:At(["number","integer"]),title:$().optional(),description:$().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),fj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),default:$().optional()}),hj=H({type:q("string"),title:$().optional(),description:$().optional(),oneOf:le(H({const:$(),title:$()})),default:$().optional()}),gj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),enumNames:le($()).optional(),default:$().optional()}),yj=Ie([fj,hj]),_j=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le($())}),default:le($()).optional()}),xj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:$(),title:$()}))}),default:le($()).optional()}),bj=Ie([_j,xj]),vj=Ie([gj,yj,bj]),Sj=Ie([vj,dj,pj,mj]),kj=aa.extend({mode:q("form").optional(),message:$(),requestedSchema:H({type:q("object"),properties:Re($(),Sj),required:le($()).optional()})}),wj=aa.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),Ej=Ie([kj,wj]),$j=at.extend({method:q("elicitation/create"),params:Ej}),Tj=or.extend({elicitationId:$()}),Pj=sr.extend({method:q("notifications/elicitation/complete"),params:Tj}),Zs=ct.extend({action:At(["accept","decline","cancel"]),content:Th(t=>t===null?void 0:t,Re($(),Ie([$(),ye(),ot(),le($())])).optional())}),Rj=H({type:q("ref/resource"),uri:$()}),Cj=H({type:q("ref/prompt"),name:$()}),Oj=Ut.extend({ref:Ie([Cj,Rj]),argument:H({name:$(),value:$()}),context:H({arguments:Re($(),$()).optional()}).optional()}),zu=at.extend({method:q("completion/complete"),params:Oj});Ij=ct.extend({completion:wt({values:le($()).max(100),total:Le(ye().int()),hasMore:Le(ot())})}),Aj=H({uri:$().startsWith("file://"),name:$().optional(),_meta:Re($(),je()).optional()}),Nj=at.extend({method:q("roots/list"),params:Ut.optional()}),Zh=ct.extend({roots:le(Aj)}),Dj=sr.extend({method:q("notifications/roots/list_changed"),params:or.optional()}),$6=Ie([Pu,Nh,zu,Uh,ju,Hs,zs,Fs,Mu,NM,MM,Bs,Us,Cu,Iu,Au,Du]),T6=Ie([Tu,Ru,Dh,Dj,ma]),P6=Ie([$u,ga,Bh,Zs,Zh,Ou,Nu,js]),R6=Ie([Pu,lj,$j,Nj,Cu,Iu,Au,Du]),C6=Ie([Tu,Ru,rj,LM,IM,QM,KM,ma,Pj]),O6=Ie([$u,vM,Ij,WM,HM,PM,RM,OM,Lu,XM,Ou,Nu,js]),Z=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===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ph(o.elicitations,r)}return new t(e,r,n)}},Ph=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function jn(t){return t==="completed"||t==="failed"||t==="cancelled"}var D0=S(()=>{});var j0,M0,L0,Fu=S(()=>{j0=Symbol("Let zodToJsonSchema decide on which parser to use"),M0={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"},L0=t=>typeof t=="string"?{...M0,name:t}:{...M0,...t}});var z0,qh=S(()=>{Fu();z0=t=>{let e=L0(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 Vh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,Vh(t,e,n,o)}var Ln=S(()=>{});var Hu,Uu=S(()=>{Hu=(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 ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Hu(e,t.currentPath):e.join("/")}}var ir=S(()=>{Uu()});function F0(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Wh=S(()=>{qi();Ln();Ge()});function H0(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?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Kh=S(()=>{Ln()});function U0(){return{type:"boolean"}}var Gh=S(()=>{});function Bu(t,e){return Y(t.type._def,e)}var Zu=S(()=>{Ge()});var B0,Jh=S(()=>{Ge();B0=(t,e)=>Y(t.innerType._def,e)});function Xh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Xh(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 Mj(t,e)}}var Mj,Yh=S(()=>{Ln();Mj=(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":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function Z0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Qh=S(()=>{Ge()});function q0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):ze(e)}var eg=S(()=>{Ge();ir()});function V0(t){return{type:"string",enum:Array.from(t.values)}}var tg=S(()=>{});function W0(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(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(jj(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}var jj,rg=S(()=>{Ge();jj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function K0(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 ng=S(()=>{});function qu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(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":_r(r,"email",n.message,e);break;case"format:idn-email":_r(r,"idn-email",n.message,e);break;case"pattern:zod":Et(r,yr.email,n.message,e);break}break;case"url":_r(r,"uri",n.message,e);break;case"uuid":_r(r,"uuid",n.message,e);break;case"regex":Et(r,n.regex,n.message,e);break;case"cuid":Et(r,yr.cuid,n.message,e);break;case"cuid2":Et(r,yr.cuid2,n.message,e);break;case"startsWith":Et(r,RegExp(`^${sg(n.value,e)}`),n.message,e);break;case"endsWith":Et(r,RegExp(`${sg(n.value,e)}$`),n.message,e);break;case"datetime":_r(r,"date-time",n.message,e);break;case"date":_r(r,"date",n.message,e);break;case"time":_r(r,"time",n.message,e);break;case"duration":_r(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Et(r,RegExp(sg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&_r(r,"ipv4",n.message,e),n.version!=="v4"&&_r(r,"ipv6",n.message,e);break}case"base64url":Et(r,yr.base64url,n.message,e);break;case"jwt":Et(r,yr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Et(r,yr.ipv4Cidr,n.message,e),n.version!=="v4"&&Et(r,yr.ipv6Cidr,n.message,e);break}case"emoji":Et(r,yr.emoji(),n.message,e);break;case"ulid":{Et(r,yr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_r(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Et(r,yr.base64,n.message,e);break}}break}case"nanoid":Et(r,yr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function sg(t,e){return e.patternStrategy==="escape"?zj(t):t}function zj(t){let e="";for(let r=0;r<t.length;r++)Lj.has(t[r])||(e+="\\"),e+=t[r];return e}function _r(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}}})):de(t,"format",e,r,n)}function Et(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:G0(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",G0(e,n),r,n)}function G0(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
|
|
469
472
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
470
473
|
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
471
474
|
`:`[${n[c]}\r
|
|
472
|
-
]`;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}var rg,yr,Aj,qu=S(()=>{jn();yr={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:()=>(rg===void 0&&(rg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rg),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-_]*$/};Aj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Vu(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===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Zu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Uu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Wu=S(()=>{qi();Ge();qu();Bu();ir()});function W0(t,e){if(e.mapStrategy==="record")return Vu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ze(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var og=S(()=>{Ge();Wu();ir()});function K0(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}}var sg=S(()=>{});function G0(t){return t.target==="openAi"?void 0:{not:ze({...t,currentPath:[...t.currentPath,"not"]})}}var ig=S(()=>{ir()});function J0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ag=S(()=>{});function Y0(t,e){if(e.target==="openApi3")return X0(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ya&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ya[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"];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 X0(t,e)}var ya,X0,Ku=S(()=>{Ge();ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};X0=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(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 Q0(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:ya[t.innerType._def.typeName],nullable:!0}:{type:[ya[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var cg=S(()=>{Ge();Ku()});function ew(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",Zh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var ug=S(()=>{jn()});function tw(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=Mj(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Y(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=Dj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Dj(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(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 Mj(t){try{return t.isOptional()}catch{return!0}}var lg=S(()=>{Ge()});var rw,dg=S(()=>{Ge();ir();rw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ze(e)},r]}:ze(e)}});var nw,pg=S(()=>{Ge();nw=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function ow(t,e){return Y(t.type._def,e)}var mg=S(()=>{Ge()});function sw(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var fg=S(()=>{jn();Ge()});function iw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var hg=S(()=>{Ge()});function aw(t){return{not:ze(t)}}var gg=S(()=>{ir()});function cw(t){return ze(t)}var yg=S(()=>{ir()});var uw,_g=S(()=>{Ge();uw=(t,e)=>Y(t.innerType._def,e)});var lw,bg=S(()=>{qi();ir();qh();Vh();Wh();Bu();Kh();Jh();Xh();Yh();Qh();eg();tg();og();sg();ig();ag();cg();ug();lg();dg();pg();mg();Wu();fg();qu();hg();gg();Ku();yg();_g();lw=(t,e,r)=>{switch(e){case D.ZodString:return Zu(t,r);case D.ZodNumber:return ew(t,r);case D.ZodObject:return tw(t,r);case D.ZodBigInt:return L0(t,r);case D.ZodBoolean:return z0();case D.ZodDate:return Gh(t,r);case D.ZodUndefined:return aw(r);case D.ZodNull:return J0(r);case D.ZodArray:return j0(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Y0(t,r);case D.ZodIntersection:return Z0(t,r);case D.ZodTuple:return iw(t,r);case D.ZodRecord:return Vu(t,r);case D.ZodLiteral:return q0(t,r);case D.ZodEnum:return B0(t);case D.ZodNativeEnum:return K0(t);case D.ZodNullable:return Q0(t,r);case D.ZodOptional:return rw(t,r);case D.ZodMap:return W0(t,r);case D.ZodSet:return sw(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return ow(t,r);case D.ZodNaN:case D.ZodNever:return G0(r);case D.ZodEffects:return U0(t,r);case D.ZodAny:return ze(r);case D.ZodUnknown:return cw(r);case D.ZodDefault:return H0(t,r);case D.ZodBranded:return Uu(t,r);case D.ZodReadonly:return uw(t,r);case D.ZodCatch:return F0(t,r);case D.ZodPipeline:return nw(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==N0)return a}if(n&&!r){let a=jj(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=lw(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Lj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var jj,Lj,Ge=S(()=>{zu();bg();Hu();ir();jj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Fu(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`),ze(e)):e.$refStrategy==="seen"?ze(e):void 0}},Lj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var dw=S(()=>{});var xg,vg=S(()=>{Ge();Bh();ir();xg=(t,e)=>{let r=M0(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ze(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}});var pw=S(()=>{zu();Bh();jn();Hu();Ge();dw();ir();qh();Vh();Wh();Bu();Kh();Jh();Xh();Yh();Qh();eg();tg();og();sg();ig();ag();cg();ug();lg();dg();pg();mg();_g();Wu();fg();qu();hg();gg();Ku();yg();bg();vg();vg()});function zj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Sg(t,e){return nr(t)?uh(t,{target:zj(e?.target),io:e?.pipeStrategy??"input"}):xg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function kg(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function wg(t,e){let r=An(t,e);if(!r.success)throw r.error;return r.data}var Eg=S(()=>{ph();oa();pw()});function mw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fw(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];mw(i)&&mw(s)?r[o]={...i,...s}:r[o]=s}return r}var Fj,Gu,hw=S(()=>{oa();jo();I0();Eg();Fj=6e4,Gu=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($u,r=>{this._oncancel(r)}),this.setNotificationHandler(Pu,r=>{this._onprogress(r)}),this.setRequestHandler(Tu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ru,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ou,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,m=new Z(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 Z(G.InvalidParams,`Task not found: ${s}`);if(!Mn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Dn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Iu,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 Z(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Nu,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mn(o.status))throw new Z(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Z(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(G.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),Z.fromError(G.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),ca(s)||v0(s)?this._onresponse(s):Rh(s)?this._onrequest(s,i):x0(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=Z.fromError(G.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?.[Dn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=y0(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(i.signal.aborted)throw new Z(G.ConnectionClosed,"Request was cancelled");let h={...m,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let p=h.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ca(e))n(e);else{let i=new Z(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(ca(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),ca(e))o(e);else{let i=Z.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 Z?i:new Z(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Mn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(G.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 Z?i:new Z(G.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=_=>{l(_)};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(_){d(_);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Dn]:c}});let p=_=>{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(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let b=_ instanceof Z?_:new Z(G.RequestTimeout,String(_));l(b)};this._responseHandlers.set(m,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=An(r,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let f=n?.timeout??Fj,g=()=>p(Z.fromError(G.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(m,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let v=this._responseHandlers.get(m);v?v(b):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(m),l(b)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(m),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cu,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},Au,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},w0,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||{},[Dn]: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||{},[Dn]: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||{},[Dn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=kg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=wg(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=kg(e);this._notificationHandlers.set(n,o=>{let s=wg(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Rh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Z(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Z(G.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 Z(G.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=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mn(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 Z(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mn(a.status))throw new Z(G.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=ma.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var xa=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var _a=class{};he._CodeOrName=_a;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lo=class extends _a{constructor(e){if(super(),!he.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}}};he.Name=Lo;var ar=class extends _a{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 Lo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ar;he.nil=new ar("");function gw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Tg(r,e[n]),r.push(t[++n]);return new ar(r)}he._=gw;var $g=new ar("+");function yw(t,...e){let r=[ba(t[0])],n=0;for(;n<e.length;)r.push($g),Tg(r,e[n]),r.push($g,ba(t[++n]));return Hj(r),new ar(r)}he.str=yw;function Tg(t,e){e instanceof ar?t.push(...e._items):e instanceof Lo?t.push(e):t.push(Zj(e))}he.addCodeArg=Tg;function Hj(t){let e=1;for(;e<t.length-1;){if(t[e]===$g){let r=Uj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Uj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Lo||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 Lo))return`"${t}${e.slice(1)}`}function Bj(t,e){return e.emptyStr()?t:t.emptyStr()?e:yw`${t}${e}`}he.strConcat=Bj;function Zj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ba(Array.isArray(t)?t.join(","):t)}function qj(t){return new ar(ba(t))}he.stringify=qj;function ba(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ba;function Vj(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ar(`.${t}`):gw`[${t}]`}he.getProperty=Vj;function Wj(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ar(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Wj;function Kj(t){return new ar(t.toString())}he.regexpCode=Kj});var Cg=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Nt=xa(),Pg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ju;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ju||(Dt.UsedValueState=Ju={}));Dt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var Xu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.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}}};Dt.Scope=Xu;var Yu=class extends Nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(r)}[${n}]`}};Dt.ValueScopeName=Yu;var Gj=(0,Nt._)`\n`,Rg=class extends Xu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Gj:Nt.nil}}get(){return this._scope}name(e){return new Yu(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,Nt._)`${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=Nt.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,Ju.Started);let l=r(u);if(l){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;s=(0,Nt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Nt._)`${s}${l}${this.opts._n}`;else throw new Pg(u);c.set(u,Ju.Completed)})}return s}};Dt.ValueScope=Rg});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=xa(),br=Cg(),Ln=xa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Ln._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Ln.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Ln.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Ln.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Ln.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Ln.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Ln.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Ln.Name}});var rl=Cg();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return rl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return rl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return rl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return rl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var sn=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Og=class extends sn{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?br.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=Vs(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Qu=class extends sn{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 pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return tl(e,this.rhs)}},Ig=class extends Qu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ag=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ng=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Dg=class extends sn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Mg=class extends sn{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=Vs(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},va=class extends sn{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)||(Jj(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},an=class extends va{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},jg=class extends va{},qs=class extends an{};qs.kind="else";var zo=class t extends an{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 qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(_w(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=Vs(this.condition,e,r),this}get names(){let e=super.names;return tl(e,this.condition),this.else&&Ho(e,this.else.names),e}};zo.kind="if";var Fo=class extends an{};Fo.kind="for";var Lg=class extends Fo{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=Vs(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},zg=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?br.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=tl(super.names,this.from);return tl(e,this.to)}},el=class extends Fo{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=Vs(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},Sa=class extends an{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)}};Sa.kind="func";var ka=class extends va{render(e){return"return "+super.render(e)}};ka.kind="return";var Fg=class extends an{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&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},wa=class extends an{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wa.kind="catch";var Ea=class extends an{render(e){return"finally"+super.render(e)}};Ea.kind="finally";var Hg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
473
|
-
`:""},this._extScope=e,this._scope=new br.Scope({parent:e}),this._nodes=[new jg]}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 Og(e,s,n)),s}const(e,r,n){return this._def(br.varKinds.const,e,r,n)}let(e,r,n){return this._def(br.varKinds.let,e,r,n)}var(e,r,n){return this._def(br.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Qu(e,r,n))}add(e,r){return this._leafNode(new Ig(e,se.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Mg(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,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new zo(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 zo(e))}else(){return this._elseNode(new qs)}endIf(){return this._endBlockNode(zo,qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Lg(e),r)}forRange(e,r,n,o,s=this.opts.es5?br.varKinds.var:br.varKinds.let){let i=this._scope.toName(e);return this._for(new zg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=br.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new el("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?br.varKinds.var:br.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new el("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Ag(e))}break(e){return this._leafNode(new Ng(e))}return(e){let r=new ka;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ka)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Fg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wa(s),r(s)}return n&&(this._currNode=o.finally=new Ea,this.code(n)),this._endBlockNode(wa,Ea)}throw(e){return this._leafNode(new Dg(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=pe.nil,n,o){return this._blockNode(new Sa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sa)}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 zo))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}};se.CodeGen=Hg;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function tl(t,e){return e instanceof pe._CodeOrName?Ho(t,e.names):t}function Vs(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._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 pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Jj(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function _w(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Ug(t)}`}se.not=_w;var Xj=bw(se.operators.AND);function Yj(...t){return t.reduce(Xj)}se.and=Yj;var Qj=bw(se.operators.OR);function eL(...t){return t.reduce(Qj)}se.or=eL;function bw(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${Ug(e)} ${t} ${Ug(r)}`}function Ug(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var Ee=oe(),tL=xa();function rL(t){let e={};for(let r of t)e[r]=!0;return e}ae.toHash=rL;function nL(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Sw(t,e),!kw(e,t.self.RULES.all))}ae.alwaysValidSchema=nL;function Sw(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]||$w(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=Sw;function kw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ae.schemaHasRules=kw;function oL(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ae.schemaHasRulesButRef=oL;function sL({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ee._)`${r}`}return(0,Ee._)`${t}${e}${(0,Ee.getProperty)(n)}`}ae.schemaRefOrVal=sL;function iL(t){return ww(decodeURIComponent(t))}ae.unescapeFragment=iL;function aL(t){return encodeURIComponent(Zg(t))}ae.escapeFragment=aL;function Zg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Zg;function ww(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=ww;function cL(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ae.eachItem=cL;function xw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ee.Name?(s instanceof Ee.Name?t(o,s,i):e(o,s,i),i):s instanceof Ee.Name?(e(o,i,s),s):r(s,i);return a===Ee.Name&&!(c instanceof Ee.Name)?n(o,c):c}}ae.mergeEvaluated={props:xw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ee._)`${r} || {}`).code((0,Ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ee._)`${r} || {}`),qg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ew}),items:xw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ew(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ee._)`{}`);return e!==void 0&&qg(t,r,e),r}ae.evaluatedPropsToName=Ew;function qg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ee._)`${e}${(0,Ee.getProperty)(n)}`,!0))}ae.setEvaluated=qg;var vw={};function uL(t,e){return t.scopeValue("func",{ref:e,code:vw[e.code]||(vw[e.code]=new tL._Code(e.code))})}ae.useFunc=uL;var Bg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Bg||(ae.Type=Bg={}));function lL(t,e,r){if(t instanceof Ee.Name){let n=e===Bg.Num;return r?n?(0,Ee._)`"[" + ${t} + "]"`:(0,Ee._)`"['" + ${t} + "']"`:n?(0,Ee._)`"/" + ${t}`:(0,Ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ee.getProperty)(t).toString():"/"+Zg(t)}ae.getErrorPath=lL;function $w(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=$w});var cn=L(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var ft=oe(),dL={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Vg.default=dL});var $a=L(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extendErrors=ht.resetErrorsCount=ht.reportExtraError=ht.reportError=ht.keyword$DataError=ht.keywordError=void 0;var fe=oe(),nl=me(),$t=cn();ht.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ht.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function pL(t,e=ht.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Rw(t,e,r);n??(i||a)?Tw(s,c):Pw(o,(0,fe._)`[${c}]`)}ht.reportError=pL;function mL(t,e=ht.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Rw(t,e,r);Tw(o,a),s||i||Pw(n,$t.default.vErrors)}ht.reportExtraError=mL;function fL(t,e){t.assign($t.default.errors,e),t.if((0,fe._)`${$t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${$t.default.vErrors}.length`,e),()=>t.assign($t.default.vErrors,null)))}ht.resetErrorsCount=fL;function hL({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,$t.default.errors,a=>{t.const(i,(0,fe._)`${$t.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)($t.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ht.extendErrors=hL;function Tw(t,e){let r=t.const("err",e);t.if((0,fe._)`${$t.default.vErrors} === null`,()=>t.assign($t.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${$t.default.vErrors}.push(${r})`),t.code((0,fe._)`${$t.default.errors}++`)}function Pw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Uo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function Rw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:gL(t,e,r)}function gL(t,e,r={}){let{gen:n,it:o}=t,s=[yL(o,r),_L(t,r)];return bL(t,e,s),n.object(...s)}function yL({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,nl.getErrorPath)(e,nl.Type.Str)}`:t;return[$t.default.instancePath,(0,fe.strConcat)($t.default.instancePath,r)]}function _L({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,nl.getErrorPath)(r,nl.Type.Str)}`),[Uo.schemaPath,o]}function bL(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([Uo.keyword,o],[Uo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Uo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Uo.schema,i],[Uo.parentSchema,(0,fe._)`${l}${d}`],[$t.default.data,s]),u&&n.push([Uo.propertyName,u])}});var Ow=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.boolOrEmptySchema=Ws.topBoolOrEmptySchema=void 0;var xL=$a(),vL=oe(),SL=cn(),kL={message:"boolean schema is false"};function wL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Cw(t,!1):typeof r=="object"&&r.$async===!0?e.return(SL.default.data):(e.assign((0,vL._)`${n}.errors`,null),e.return(!0))}Ws.topBoolOrEmptySchema=wL;function EL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Cw(t)):r.var(e,!0)}Ws.boolOrEmptySchema=EL;function Cw(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,xL.reportError)(o,kL,void 0,e)}});var Wg=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getRules=Ks.isJSONType=void 0;var $L=["string","number","integer","boolean","null","object","array"],TL=new Set($L);function PL(t){return typeof t=="string"&&TL.has(t)}Ks.isJSONType=PL;function RL(){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:{}}}Ks.getRules=RL});var Kg=L(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.shouldUseRule=zn.shouldUseGroup=zn.schemaHasRulesForType=void 0;function CL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Iw(t,n)}zn.schemaHasRulesForType=CL;function Iw(t,e){return e.rules.some(r=>Aw(t,r))}zn.shouldUseGroup=Iw;function Aw(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))}zn.shouldUseRule=Aw});var Ta=L(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var OL=Wg(),IL=Kg(),AL=$a(),re=oe(),Nw=me(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(gt.DataType=Gs={}));function NL(t){let e=Dw(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}gt.getSchemaTypes=NL;function Dw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(OL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=Dw;function DL(t,e){let{gen:r,data:n,opts:o}=t,s=ML(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,IL.schemaHasRulesForType)(t,e[0]));if(i){let a=Jg(e,n,o.strictNumbers,Gs.Wrong);r.if(a,()=>{s.length?jL(t,e,s):Xg(t)})}return i}gt.coerceAndCheckDataType=DL;var Mw=new Set(["string","number","integer","boolean","null"]);function ML(t,e){return e?t.filter(r=>Mw.has(r)||e==="array"&&r==="array"):[]}function jL(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,re._)`typeof ${o}`),a=n.let("coerced",(0,re._)`undefined`);s.coerceTypes==="array"&&n.if((0,re._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,re._)`${o}[0]`).assign(i,(0,re._)`typeof ${o}`).if(Jg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,re._)`${a} !== undefined`);for(let u of r)(Mw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Xg(t),n.endIf(),n.if((0,re._)`${a} !== undefined`,()=>{n.assign(o,a),LL(t,a)});function c(u){switch(u){case"string":n.elseIf((0,re._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,re._)`"" + ${o}`).elseIf((0,re._)`${o} === null`).assign(a,(0,re._)`""`);return;case"number":n.elseIf((0,re._)`${i} == "boolean" || ${o} === null
|
|
475
|
+
]`;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}var og,yr,Lj,Vu=S(()=>{Ln();yr={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:()=>(og===void 0&&(og=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),og),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-_]*$/};Lj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Wu(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===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=qu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Bu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Ku=S(()=>{qi();Ge();Vu();Zu();ir()});function J0(t,e){if(e.mapStrategy==="record")return Wu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ze(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var ig=S(()=>{Ge();Ku();ir()});function X0(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}}var ag=S(()=>{});function Y0(t){return t.target==="openAi"?void 0:{not:ze({...t,currentPath:[...t.currentPath,"not"]})}}var cg=S(()=>{ir()});function Q0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ug=S(()=>{});function tw(t,e){if(e.target==="openApi3")return ew(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ya&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ya[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"];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 ew(t,e)}var ya,ew,Gu=S(()=>{Ge();ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ew=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(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 rw(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:ya[t.innerType._def.typeName],nullable:!0}:{type:[ya[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var lg=S(()=>{Ge();Gu()});function nw(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",Vh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var dg=S(()=>{Ln()});function ow(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=Hj(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Y(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=Fj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Fj(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(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 Hj(t){try{return t.isOptional()}catch{return!0}}var pg=S(()=>{Ge()});var sw,mg=S(()=>{Ge();ir();sw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ze(e)},r]}:ze(e)}});var iw,fg=S(()=>{Ge();iw=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function aw(t,e){return Y(t.type._def,e)}var hg=S(()=>{Ge()});function cw(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var gg=S(()=>{Ln();Ge()});function uw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var yg=S(()=>{Ge()});function lw(t){return{not:ze(t)}}var _g=S(()=>{ir()});function dw(t){return ze(t)}var xg=S(()=>{ir()});var pw,bg=S(()=>{Ge();pw=(t,e)=>Y(t.innerType._def,e)});var mw,vg=S(()=>{qi();ir();Wh();Kh();Gh();Zu();Jh();Yh();Qh();eg();tg();rg();ng();ig();ag();cg();ug();lg();dg();pg();mg();fg();hg();Ku();gg();Vu();yg();_g();Gu();xg();bg();mw=(t,e,r)=>{switch(e){case D.ZodString:return qu(t,r);case D.ZodNumber:return nw(t,r);case D.ZodObject:return ow(t,r);case D.ZodBigInt:return H0(t,r);case D.ZodBoolean:return U0();case D.ZodDate:return Xh(t,r);case D.ZodUndefined:return lw(r);case D.ZodNull:return Q0(r);case D.ZodArray:return F0(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return tw(t,r);case D.ZodIntersection:return W0(t,r);case D.ZodTuple:return uw(t,r);case D.ZodRecord:return Wu(t,r);case D.ZodLiteral:return K0(t,r);case D.ZodEnum:return V0(t);case D.ZodNativeEnum:return X0(t);case D.ZodNullable:return rw(t,r);case D.ZodOptional:return sw(t,r);case D.ZodMap:return J0(t,r);case D.ZodSet:return cw(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return aw(t,r);case D.ZodNaN:case D.ZodNever:return Y0(r);case D.ZodEffects:return q0(t,r);case D.ZodAny:return ze(r);case D.ZodUnknown:return dw(r);case D.ZodDefault:return Z0(t,r);case D.ZodBranded:return Bu(t,r);case D.ZodReadonly:return pw(t,r);case D.ZodCatch:return B0(t,r);case D.ZodPipeline:return iw(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==j0)return a}if(n&&!r){let a=Uj(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=mw(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Bj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Uj,Bj,Ge=S(()=>{Fu();vg();Uu();ir();Uj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Hu(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`),ze(e)):e.$refStrategy==="seen"?ze(e):void 0}},Bj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var fw=S(()=>{});var Sg,kg=S(()=>{Ge();qh();ir();Sg=(t,e)=>{let r=z0(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ze(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}});var hw=S(()=>{Fu();qh();Ln();Uu();Ge();fw();ir();Wh();Kh();Gh();Zu();Jh();Yh();Qh();eg();tg();rg();ng();ig();ag();cg();ug();lg();dg();pg();mg();fg();hg();bg();Ku();gg();Vu();yg();_g();Gu();xg();vg();kg();kg()});function Zj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wg(t,e){return nr(t)?dh(t,{target:Zj(e?.target),io:e?.pipeStrategy??"input"}):Sg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Eg(t){let r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $g(t,e){let r=Nn(t,e);if(!r.success)throw r.error;return r.data}var Tg=S(()=>{fh();oa();hw()});function gw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yw(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];gw(i)&&gw(s)?r[o]={...i,...s}:r[o]=s}return r}var qj,Ju,_w=S(()=>{oa();jo();D0();Tg();qj=6e4,Ju=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(Tu,r=>{this._oncancel(r)}),this.setNotificationHandler(Ru,r=>{this._onprogress(r)}),this.setRequestHandler(Pu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Cu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Iu,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Z(G.InvalidParams,`Task not found: ${s}`);if(!jn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(jn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Mn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Au,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 Z(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Du,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(jn(o.status))throw new Z(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Z(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(G.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),Z.fromError(G.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),ca(s)||w0(s)?this._onresponse(s):Oh(s)?this._onrequest(s,i):k0(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=Z.fromError(G.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?.[Mn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=b0(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new Z(G.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let m=h.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ca(e))n(e);else{let i=new Z(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(ca(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),ca(e))o(e);else{let i=Z.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 Z?i:new Z(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},jn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(G.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 Z?i:new Z(G.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=_=>{l(_)};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(_){d(_);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Mn]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let x=_ instanceof Z?_:new Z(G.RequestTimeout,String(_));l(x)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Nn(r,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let f=n?.timeout??qj,g=()=>m(Z.fromError(G.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(p,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let v=this._responseHandlers.get(p);v?v(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),l(x)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ou,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},Nu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},T0,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||{},[Mn]: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||{},[Mn]: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||{},[Mn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Eg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=$g(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=Eg(e);this._notificationHandlers.set(n,o=>{let s=$g(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Oh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Z(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Z(G.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 Z(G.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=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(c),jn(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 Z(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(jn(a.status))throw new Z(G.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=ma.parse({method:"notifications/tasks/status",params:c});await this.notification(u),jn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ba=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var _a=class{};he._CodeOrName=_a;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lo=class extends _a{constructor(e){if(super(),!he.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}}};he.Name=Lo;var ar=class extends _a{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 Lo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ar;he.nil=new ar("");function xw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Rg(r,e[n]),r.push(t[++n]);return new ar(r)}he._=xw;var Pg=new ar("+");function bw(t,...e){let r=[xa(t[0])],n=0;for(;n<e.length;)r.push(Pg),Rg(r,e[n]),r.push(Pg,xa(t[++n]));return Vj(r),new ar(r)}he.str=bw;function Rg(t,e){e instanceof ar?t.push(...e._items):e instanceof Lo?t.push(e):t.push(Gj(e))}he.addCodeArg=Rg;function Vj(t){let e=1;for(;e<t.length-1;){if(t[e]===Pg){let r=Wj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Wj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Lo||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 Lo))return`"${t}${e.slice(1)}`}function Kj(t,e){return e.emptyStr()?t:t.emptyStr()?e:bw`${t}${e}`}he.strConcat=Kj;function Gj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:xa(Array.isArray(t)?t.join(","):t)}function Jj(t){return new ar(xa(t))}he.stringify=Jj;function xa(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=xa;function Xj(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ar(`.${t}`):xw`[${t}]`}he.getProperty=Xj;function Yj(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ar(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Yj;function Qj(t){return new ar(t.toString())}he.regexpCode=Qj});var Ig=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Nt=ba(),Cg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Xu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Xu||(Dt.UsedValueState=Xu={}));Dt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var Yu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.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}}};Dt.Scope=Yu;var Qu=class extends Nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(r)}[${n}]`}};Dt.ValueScopeName=Qu;var eL=(0,Nt._)`\n`,Og=class extends Yu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?eL:Nt.nil}}get(){return this._scope}name(e){return new Qu(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,Nt._)`${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=Nt.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,Xu.Started);let l=r(u);if(l){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;s=(0,Nt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Nt._)`${s}${l}${this.opts._n}`;else throw new Cg(u);c.set(u,Xu.Completed)})}return s}};Dt.ValueScope=Og});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=ba(),xr=Ig(),zn=ba();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return zn._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return zn.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return zn.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return zn.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return zn.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return zn.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return zn.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return zn.Name}});var nl=Ig();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return nl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return nl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return nl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return nl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var an=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ag=class extends an{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?xr.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=Vs(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},el=class extends an{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 pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return rl(e,this.rhs)}},Ng=class extends el{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Dg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},jg=class extends an{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Lg=class extends an{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=Vs(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},va=class extends an{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)||(tL(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},cn=class extends va{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zg=class extends va{},qs=class extends cn{};qs.kind="else";var zo=class t extends cn{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 qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(vw(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=Vs(this.condition,e,r),this}get names(){let e=super.names;return rl(e,this.condition),this.else&&Ho(e,this.else.names),e}};zo.kind="if";var Fo=class extends cn{};Fo.kind="for";var Fg=class extends Fo{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=Vs(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},Hg=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?xr.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=rl(super.names,this.from);return rl(e,this.to)}},tl=class extends Fo{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=Vs(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},Sa=class extends cn{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)}};Sa.kind="func";var ka=class extends va{render(e){return"return "+super.render(e)}};ka.kind="return";var Ug=class extends cn{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&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},wa=class extends cn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wa.kind="catch";var Ea=class extends cn{render(e){return"finally"+super.render(e)}};Ea.kind="finally";var Bg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
476
|
+
`:""},this._extScope=e,this._scope=new xr.Scope({parent:e}),this._nodes=[new zg]}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 Ag(e,s,n)),s}const(e,r,n){return this._def(xr.varKinds.const,e,r,n)}let(e,r,n){return this._def(xr.varKinds.let,e,r,n)}var(e,r,n){return this._def(xr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new el(e,r,n))}add(e,r){return this._leafNode(new Ng(e,se.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Lg(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,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new zo(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 zo(e))}else(){return this._elseNode(new qs)}endIf(){return this._endBlockNode(zo,qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fg(e),r)}forRange(e,r,n,o,s=this.opts.es5?xr.varKinds.var:xr.varKinds.let){let i=this._scope.toName(e);return this._for(new Hg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=xr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new tl("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?xr.varKinds.var:xr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new tl("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Dg(e))}break(e){return this._leafNode(new Mg(e))}return(e){let r=new ka;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ka)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ug;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wa(s),r(s)}return n&&(this._currNode=o.finally=new Ea,this.code(n)),this._endBlockNode(wa,Ea)}throw(e){return this._leafNode(new jg(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=pe.nil,n,o){return this._blockNode(new Sa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sa)}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 zo))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}};se.CodeGen=Bg;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function rl(t,e){return e instanceof pe._CodeOrName?Ho(t,e.names):t}function Vs(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._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 pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function tL(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function vw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Zg(t)}`}se.not=vw;var rL=Sw(se.operators.AND);function nL(...t){return t.reduce(rL)}se.and=nL;var oL=Sw(se.operators.OR);function sL(...t){return t.reduce(oL)}se.or=sL;function Sw(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${Zg(e)} ${t} ${Zg(r)}`}function Zg(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var Ee=oe(),iL=ba();function aL(t){let e={};for(let r of t)e[r]=!0;return e}ae.toHash=aL;function cL(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ew(t,e),!$w(e,t.self.RULES.all))}ae.alwaysValidSchema=cL;function Ew(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]||Rw(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=Ew;function $w(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ae.schemaHasRules=$w;function uL(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ae.schemaHasRulesButRef=uL;function lL({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ee._)`${r}`}return(0,Ee._)`${t}${e}${(0,Ee.getProperty)(n)}`}ae.schemaRefOrVal=lL;function dL(t){return Tw(decodeURIComponent(t))}ae.unescapeFragment=dL;function pL(t){return encodeURIComponent(Vg(t))}ae.escapeFragment=pL;function Vg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Vg;function Tw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=Tw;function mL(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ae.eachItem=mL;function kw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ee.Name?(s instanceof Ee.Name?t(o,s,i):e(o,s,i),i):s instanceof Ee.Name?(e(o,i,s),s):r(s,i);return a===Ee.Name&&!(c instanceof Ee.Name)?n(o,c):c}}ae.mergeEvaluated={props:kw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ee._)`${r} || {}`).code((0,Ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ee._)`${r} || {}`),Wg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pw}),items:kw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Pw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ee._)`{}`);return e!==void 0&&Wg(t,r,e),r}ae.evaluatedPropsToName=Pw;function Wg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ee._)`${e}${(0,Ee.getProperty)(n)}`,!0))}ae.setEvaluated=Wg;var ww={};function fL(t,e){return t.scopeValue("func",{ref:e,code:ww[e.code]||(ww[e.code]=new iL._Code(e.code))})}ae.useFunc=fL;var qg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(qg||(ae.Type=qg={}));function hL(t,e,r){if(t instanceof Ee.Name){let n=e===qg.Num;return r?n?(0,Ee._)`"[" + ${t} + "]"`:(0,Ee._)`"['" + ${t} + "']"`:n?(0,Ee._)`"/" + ${t}`:(0,Ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ee.getProperty)(t).toString():"/"+Vg(t)}ae.getErrorPath=hL;function Rw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=Rw});var un=L(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var ft=oe(),gL={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Kg.default=gL});var $a=L(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extendErrors=ht.resetErrorsCount=ht.reportExtraError=ht.reportError=ht.keyword$DataError=ht.keywordError=void 0;var fe=oe(),ol=me(),$t=un();ht.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ht.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function yL(t,e=ht.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Iw(t,e,r);n??(i||a)?Cw(s,c):Ow(o,(0,fe._)`[${c}]`)}ht.reportError=yL;function _L(t,e=ht.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Iw(t,e,r);Cw(o,a),s||i||Ow(n,$t.default.vErrors)}ht.reportExtraError=_L;function xL(t,e){t.assign($t.default.errors,e),t.if((0,fe._)`${$t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${$t.default.vErrors}.length`,e),()=>t.assign($t.default.vErrors,null)))}ht.resetErrorsCount=xL;function bL({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,$t.default.errors,a=>{t.const(i,(0,fe._)`${$t.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)($t.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ht.extendErrors=bL;function Cw(t,e){let r=t.const("err",e);t.if((0,fe._)`${$t.default.vErrors} === null`,()=>t.assign($t.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${$t.default.vErrors}.push(${r})`),t.code((0,fe._)`${$t.default.errors}++`)}function Ow(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Uo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function Iw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:vL(t,e,r)}function vL(t,e,r={}){let{gen:n,it:o}=t,s=[SL(o,r),kL(t,r)];return wL(t,e,s),n.object(...s)}function SL({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,ol.getErrorPath)(e,ol.Type.Str)}`:t;return[$t.default.instancePath,(0,fe.strConcat)($t.default.instancePath,r)]}function kL({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,ol.getErrorPath)(r,ol.Type.Str)}`),[Uo.schemaPath,o]}function wL(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([Uo.keyword,o],[Uo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Uo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Uo.schema,i],[Uo.parentSchema,(0,fe._)`${l}${d}`],[$t.default.data,s]),u&&n.push([Uo.propertyName,u])}});var Nw=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.boolOrEmptySchema=Ws.topBoolOrEmptySchema=void 0;var EL=$a(),$L=oe(),TL=un(),PL={message:"boolean schema is false"};function RL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Aw(t,!1):typeof r=="object"&&r.$async===!0?e.return(TL.default.data):(e.assign((0,$L._)`${n}.errors`,null),e.return(!0))}Ws.topBoolOrEmptySchema=RL;function CL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Aw(t)):r.var(e,!0)}Ws.boolOrEmptySchema=CL;function Aw(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,EL.reportError)(o,PL,void 0,e)}});var Gg=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getRules=Ks.isJSONType=void 0;var OL=["string","number","integer","boolean","null","object","array"],IL=new Set(OL);function AL(t){return typeof t=="string"&&IL.has(t)}Ks.isJSONType=AL;function NL(){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:{}}}Ks.getRules=NL});var Jg=L(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.shouldUseRule=Fn.shouldUseGroup=Fn.schemaHasRulesForType=void 0;function DL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Dw(t,n)}Fn.schemaHasRulesForType=DL;function Dw(t,e){return e.rules.some(r=>Mw(t,r))}Fn.shouldUseGroup=Dw;function Mw(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))}Fn.shouldUseRule=Mw});var Ta=L(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var ML=Gg(),jL=Jg(),LL=$a(),re=oe(),jw=me(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(gt.DataType=Gs={}));function zL(t){let e=Lw(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}gt.getSchemaTypes=zL;function Lw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ML.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=Lw;function FL(t,e){let{gen:r,data:n,opts:o}=t,s=HL(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jL.schemaHasRulesForType)(t,e[0]));if(i){let a=Yg(e,n,o.strictNumbers,Gs.Wrong);r.if(a,()=>{s.length?UL(t,e,s):Qg(t)})}return i}gt.coerceAndCheckDataType=FL;var zw=new Set(["string","number","integer","boolean","null"]);function HL(t,e){return e?t.filter(r=>zw.has(r)||e==="array"&&r==="array"):[]}function UL(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,re._)`typeof ${o}`),a=n.let("coerced",(0,re._)`undefined`);s.coerceTypes==="array"&&n.if((0,re._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,re._)`${o}[0]`).assign(i,(0,re._)`typeof ${o}`).if(Yg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,re._)`${a} !== undefined`);for(let u of r)(zw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Qg(t),n.endIf(),n.if((0,re._)`${a} !== undefined`,()=>{n.assign(o,a),BL(t,a)});function c(u){switch(u){case"string":n.elseIf((0,re._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,re._)`"" + ${o}`).elseIf((0,re._)`${o} === null`).assign(a,(0,re._)`""`);return;case"number":n.elseIf((0,re._)`${i} == "boolean" || ${o} === null
|
|
474
477
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,re._)`+${o}`);return;case"integer":n.elseIf((0,re._)`${i} === "boolean" || ${o} === null
|
|
475
478
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,re._)`+${o}`);return;case"boolean":n.elseIf((0,re._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,re._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,re._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,re._)`${i} === "string" || ${i} === "number"
|
|
476
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,re._)`[${o}]`)}}}function LL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,re._)`${e} !== undefined`,()=>t.assign((0,re._)`${e}[${r}]`,n))}function Gg(t,e,r,n=Gs.Correct){let o=n===Gs.Correct?re.operators.EQ:re.operators.NEQ,s;switch(t){case"null":return(0,re._)`${e} ${o} null`;case"array":s=(0,re._)`Array.isArray(${e})`;break;case"object":s=(0,re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,re._)`typeof ${e} ${o} ${t}`}return n===Gs.Correct?s:(0,re.not)(s);function i(a=re.nil){return(0,re.and)((0,re._)`typeof ${e} == "number"`,a,r?(0,re._)`isFinite(${e})`:re.nil)}}gt.checkDataType=Gg;function Jg(t,e,r,n){if(t.length===1)return Gg(t[0],e,r,n);let o,s=(0,Nw.toHash)(t);if(s.array&&s.object){let i=(0,re._)`typeof ${e} != "object"`;o=s.null?i:(0,re._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=re.nil;s.number&&delete s.integer;for(let i in s)o=(0,re.and)(o,Gg(i,e,r,n));return o}gt.checkDataTypes=Jg;var zL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,re._)`{type: ${t}}`:(0,re._)`{type: ${e}}`};function Xg(t){let e=FL(t);(0,AL.reportError)(e,zL)}gt.reportTypeError=Xg;function FL(t){let{gen:e,data:r,schema:n}=t,o=(0,Nw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Lw=L(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.assignDefaults=void 0;var Js=oe(),HL=me();function UL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)jw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>jw(t,s,o.default))}ol.assignDefaults=UL;function jw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,HL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Js._)`${a} = ${(0,Js.stringify)(r)}`)}});var cr=L(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.validateUnion=Se.validateArray=Se.usePattern=Se.callValidateCode=Se.schemaProperties=Se.allSchemaProperties=Se.noPropertyInData=Se.propertyInData=Se.isOwnProperty=Se.hasPropFunc=Se.reportMissingProp=Se.checkMissingProp=Se.checkReportMissingProp=void 0;var Ae=oe(),Yg=me(),Fn=cn(),BL=me();function ZL(t,e){let{gen:r,data:n,it:o}=t;r.if(ey(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}Se.checkReportMissingProp=ZL;function qL({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(ey(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}Se.checkMissingProp=qL;function VL(t,e){t.setParams({missingProperty:e},!0),t.error()}Se.reportMissingProp=VL;function zw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}Se.hasPropFunc=zw;function Qg(t,e,r){return(0,Ae._)`${zw(t)}.call(${e}, ${r})`}Se.isOwnProperty=Qg;function WL(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${Qg(t,e,r)}`:o}Se.propertyInData=WL;function ey(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(Qg(t,e,r))):o}Se.noPropertyInData=ey;function Fw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Se.allSchemaProperties=Fw;function KL(t,e){return Fw(e).filter(r=>!(0,Yg.alwaysValidSchema)(t,e[r]))}Se.schemaProperties=KL;function GL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,d=[[Fn.default.instancePath,(0,Ae.strConcat)(Fn.default.instancePath,s)],[Fn.default.parentData,i.parentData],[Fn.default.parentDataProperty,i.parentDataProperty],[Fn.default.rootData,Fn.default.rootData]];i.opts.dynamicRef&&d.push([Fn.default.dynamicAnchors,Fn.default.dynamicAnchors]);let m=(0,Ae._)`${l}, ${r.object(...d)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${m})`:(0,Ae._)`${a}(${m})`}Se.callValidateCode=GL;var JL=(0,Ae._)`new RegExp`;function XL({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,Ae._)`${o.code==="new RegExp"?JL:(0,BL.useFunc)(t,o)}(${r}, ${n})`})}Se.usePattern=XL;function YL(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,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Yg.Type.Num},s),e.if((0,Ae.not)(s),a)})}}Se.validateArray=YL;function QL(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,Yg.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,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Se.validateUnion=QL});var Bw=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.validateKeywordUsage=zr.validSchemaType=zr.funcKeywordCode=zr.macroKeywordCode=void 0;var Tt=oe(),Bo=cn(),ez=cr(),tz=$a();function rz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Uw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Tt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}zr.macroKeywordCode=rz;function nz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;sz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Uw(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)f(),e.modifying&&Hw(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Hw(t),g(()=>oz(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,Tt._)`await `),_=>n.assign(d,!1).if((0,Tt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Tt._)`${_}.errors`),()=>n.throw(_))),y}function p(){let y=(0,Tt._)`${l}.errors`;return n.assign(y,null),f(Tt.nil),y}function f(y=e.async?(0,Tt._)`await `:Tt.nil){let _=c.opts.passContext?Bo.default.this:Bo.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Tt._)`${y}${(0,ez.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;n.if((0,Tt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}zr.funcKeywordCode=nz;function Hw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Tt._)`${n.parentData}[${n.parentDataProperty}]`))}function oz(t,e){let{gen:r}=t;r.if((0,Tt._)`Array.isArray(${e})`,()=>{r.assign(Bo.default.vErrors,(0,Tt._)`${Bo.default.vErrors} === null ? ${e} : ${Bo.default.vErrors}.concat(${e})`).assign(Bo.default.errors,(0,Tt._)`${Bo.default.vErrors}.length`),(0,tz.extendErrors)(t)},()=>t.error())}function sz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Uw(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,Tt.stringify)(r)})}function iz(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")}zr.validSchemaType=iz;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)}}zr.validateKeywordUsage=az});var qw=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.extendSubschemaMode=Hn.extendSubschemaData=Hn.getSubschema=void 0;var Fr=oe(),Zw=me();function cz(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,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}${(0,Fr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Zw.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')}Hn.getSubschema=cz;function uz(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,Fr._)`${e.data}${(0,Fr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Fr.str)`${u}${(0,Zw.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Fr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Fr.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]}}Hn.extendSubschemaData=uz;function lz(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}Hn.extendSubschemaMode=lz});var ty=L((UG,Vw)=>{"use strict";Vw.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 Kw=L((BG,Ww)=>{"use strict";var Un=Ww.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(){};sl(e,n,o,t,"",t)};Un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Un.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 sl(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 Un.arrayKeywords)for(var m=0;m<d.length;m++)sl(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in Un.propsKeywords){if(d&&typeof d=="object")for(var h in d)sl(t,e,r,d[h],o+"/"+l+"/"+dz(h),s,o,l,n,h)}else(l in Un.keywords||t.allKeys&&!(l in Un.skipKeywords))&&sl(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function dz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Pa=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;var pz=me(),mz=ty(),fz=Kw(),hz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ry(t):e?Gw(t)<=e:!1}Mt.inlineRef=gz;var yz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ry(t){for(let e in t){if(yz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ry)||typeof r=="object"&&ry(r))return!0}return!1}function Gw(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!hz.has(r)&&(typeof t[r]=="object"&&(0,pz.eachItem)(t[r],n=>e+=Gw(n)),e===1/0))return 1/0}return e}function Jw(t,e="",r){r!==!1&&(e=Xs(e));let n=t.parse(e);return Xw(t,n)}Mt.getFullPath=Jw;function Xw(t,e){return t.serialize(e).split("#")[0]+"#"}Mt._getFullPath=Xw;var _z=/#\/?$/;function Xs(t){return t?t.replace(_z,""):""}Mt.normalizeId=Xs;function bz(t,e,r){return r=Xs(r),t.resolve(e,r)}Mt.resolveUrl=bz;var xz=/^[a-z_][-a-z0-9._]*$/i;function vz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xs(t[r]||e),s={"":o},i=Jw(n,o,!1),a={},c=new Set;return fz(t,{allKeys:!0},(d,m,h,p)=>{if(p===void 0)return;let f=i+m,g=s[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[m]=g;function y(b){let v=this.opts.uriResolver.resolve;if(b=Xs(g?v(g,b):b),c.has(b))throw l(b);c.add(b);let E=this.refs[b];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,b):b!==Xs(f)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=f),b}function _(b){if(typeof b=="string"){if(!xz.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,m,h){if(m!==void 0&&!mz(d,m))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Mt.getSchemaRefs=vz});var Oa=L(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getData=Bn.KeywordCxt=Bn.validateFunctionCode=void 0;var rE=Ow(),Yw=Ta(),oy=Kg(),il=Ta(),Sz=Lw(),Ca=Bw(),ny=qw(),V=oe(),ee=cn(),kz=Pa(),un=me(),Ra=$a();function wz(t){if(sE(t)&&(iE(t),oE(t))){Tz(t);return}nE(t,()=>(0,rE.topBoolOrEmptySchema)(t))}Bn.validateFunctionCode=wz;function nE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${Qw(r,o)}`),$z(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${Ez(o)}`,n.$async,()=>t.code(Qw(r,o)).code(s))}function Ez(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function $z(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function Tz(t){let{schema:e,opts:r,gen:n}=t;nE(t,()=>{r.$comment&&e.$comment&&cE(t),Iz(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&Pz(t),aE(t),Dz(t)})}function Pz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function Qw(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function Rz(t,e){if(sE(t)&&(iE(t),oE(t))){Cz(t,e);return}(0,rE.boolOrEmptySchema)(t,e)}function oE({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 sE(t){return typeof t.schema!="boolean"}function Cz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&cE(t),Az(t),Nz(t);let s=n.const("_errs",ee.default.errors);aE(t,s),n.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function iE(t){(0,un.checkUnknownRules)(t),Oz(t)}function aE(t,e){if(t.opts.jtd)return eE(t,[],!1,e);let r=(0,Yw.getSchemaTypes)(t.schema),n=(0,Yw.coerceAndCheckDataType)(t,r);eE(t,r,!n,e)}function Oz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,un.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Iz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,un.checkStrictMode)(t,"default is ignored in the schema root")}function Az(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,kz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Nz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function cE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Dz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&Mz(t),e.return((0,V._)`${ee.default.errors} === 0`))}function Mz({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function eE(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,un.schemaHasRulesButRef)(s,l))){o.block(()=>lE(t,"$ref",l.all.$ref.definition));return}c.jtd||jz(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,oy.shouldUseGroup)(s,m)&&(m.type?(o.if((0,il.checkDataType)(m.type,i,c.strictNumbers)),tE(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,il.reportTypeError)(t)),o.endIf()):tE(t,m),a||o.if((0,V._)`${ee.default.errors} === ${n||0}`))}}function tE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Sz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,oy.shouldUseRule)(n,s)&&lE(t,s.keyword,s.definition,e.type)})}function jz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Lz(t,e),t.opts.allowUnionTypes||zz(t,e),Fz(t,t.dataTypes))}function Lz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{uE(t.dataTypes,r)||sy(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Uz(t,e)}}function zz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&sy(t,"use allowUnionTypes to allow union type keyword")}function Fz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,oy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Hz(e,i))&&sy(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Hz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function uE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Uz(t,e){let r=[];for(let n of t.dataTypes)uE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function sy(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,un.checkStrictMode)(t,e,t.opts.strictTypes)}var al=class{constructor(e,r,n){if((0,Ca.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,un.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",dE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ca.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",ee.default.errors))}result(e,r,n){this.failResult((0,V.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,V.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,V._)`${r} !== undefined && (${(0,V.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?Ra.reportExtraError:Ra.reportError)(this,this.def.error,r)}$dataError(){(0,Ra.reportError)(this,this.def.$dataError||Ra.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ra.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=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,il.checkDataTypes)(c,r,s.opts.strictNumbers,il.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,ny.getSubschema)(this.it,e);(0,ny.extendSubschemaData)(n,this.it,e),(0,ny.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Rz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=un.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=un.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,V.Name)),!0}};Bn.KeywordCxt=al;function lE(t,e,r,n){let o=new al(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ca.funcKeywordCode)(o,r):"macro"in r?(0,Ca.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ca.funcKeywordCode)(o,r)}var Bz=/^\/(?:[^~]|~0|~1)*$/,Zz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!Bz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=Zz.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,V._)`${s}${(0,V.getProperty)((0,un.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Bn.getData=dE});var cl=L(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var iy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ay.default=iy});var Ia=L(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});var cy=Pa(),uy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,cy.resolveUrl)(e,r,n),this.missingSchema=(0,cy.normalizeId)((0,cy.getFullPath)(e,this.missingRef))}};ly.default=uy});var ll=L(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;var xr=oe(),qz=cl(),Zo=cn(),vr=Pa(),pE=me(),Vz=Oa(),Ys=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,vr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ur.SchemaEnv=Ys;function py(t){let e=mE.call(this,t);if(e)return e;let r=(0,vr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:qz.default,code:(0,xr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Zo.default.data,parentData:Zo.default.parentData,parentDataProperty:Zo.default.parentDataProperty,dataNames:[Zo.default.data],dataPathArr:[xr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,xr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:xr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xr._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Vz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Zo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Zo.default.self}`,`${Zo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:f}=u;h.evaluated={props:p instanceof xr.Name?void 0:p,items:f instanceof xr.Name?void 0:f,dynamicProps:p instanceof xr.Name,dynamicItems:f instanceof xr.Name},h.source&&(h.source.evaluated=(0,xr.stringify)(h.evaluated))}return t.validate=h,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)}}ur.compileSchema=py;function Wz(t,e,r){var n;r=(0,vr.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 Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Kz.call(this,s)}ur.resolveRef=Wz;function Kz(t){return(0,vr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:py.call(this,t)}function mE(t){for(let e of this._compilations)if(Gz(e,t))return e}ur.getCompilingSchema=mE;function Gz(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]||ul.call(this,t,e)}function ul(t,e){let r=this.opts.uriResolver.parse(e),n=(0,vr._getFullPath)(this.opts.uriResolver,r),o=(0,vr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return dy.call(this,r,t);let s=(0,vr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ul.call(this,t,i);return typeof a?.schema!="object"?void 0:dy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||py.call(this,i),s===(0,vr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,vr.resolveUrl)(this.opts.uriResolver,o,u)),new Ys({schema:a,schemaId:c,root:t,baseId:o})}return dy.call(this,r,i)}}ur.resolveSchema=ul;var Xz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function dy(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,pE.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Xz.has(a)&&u&&(e=(0,vr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,pE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,vr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ul.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var fE=L((GG,Yz)=>{Yz.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 fy=L((JG,_E)=>{"use strict";var Qz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),gE=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);function my(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 eF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hE(t){return t.length=0,!0}function tF(t,e,r){if(t.length){let n=my(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function rF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=tF;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=hE}else{o.push(u);continue}}return o.length&&(a===hE?r.zone=o.join(""):i?n.push(o.join("")):n.push(my(o))),r.address=n.join(""),r}function yE(t){if(nF(t,":")<2)return{host:t,isIPV6:!1};let e=rF(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function nF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function oF(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 sF(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function iF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!gE(r)){let n=yE(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}_E.exports={nonSimpleDomain:eF,recomposeAuthority:iF,normalizeComponentEncoding:sF,removeDotSegments:oF,isIPv4:gE,isUUID:Qz,normalizeIPv6:yE,stringArrayToHexStripped:my}});var kE=L((XG,SE)=>{"use strict";var{isUUID:aF}=fy(),cF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,uF=["http","https","ws","wss","urn","urn:uuid"];function lF(t){return uF.indexOf(t)!==-1}function hy(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 bE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function xE(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 dF(t){return t.secure=hy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function pF(t){if((t.port===(hy(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,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function mF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(cF);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=gy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function fF(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=gy(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 hF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!aF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function gF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vE={scheme:"http",domainHost:!0,parse:bE,serialize:xE},yF={scheme:"https",domainHost:vE.domainHost,parse:bE,serialize:xE},dl={scheme:"ws",domainHost:!0,parse:dF,serialize:pF},_F={scheme:"wss",domainHost:dl.domainHost,parse:dl.parse,serialize:dl.serialize},bF={scheme:"urn",parse:mF,serialize:fF,skipNormalize:!0},xF={scheme:"urn:uuid",parse:hF,serialize:gF,skipNormalize:!0},pl={http:vE,https:yF,ws:dl,wss:_F,urn:bF,"urn:uuid":xF};Object.setPrototypeOf(pl,null);function gy(t){return t&&(pl[t]||pl[t.toLowerCase()])||void 0}SE.exports={wsIsSecure:hy,SCHEMES:pl,isValidSchemeName:lF,getSchemeHandler:gy}});var $E=L((YG,fl)=>{"use strict";var{normalizeIPv6:vF,removeDotSegments:Aa,recomposeAuthority:SF,normalizeComponentEncoding:ml,isIPv4:kF,nonSimpleDomain:wF}=fy(),{SCHEMES:EF,getSchemeHandler:wE}=kE();function $F(t,e){return typeof t=="string"?t=Hr(ln(t,e),e):typeof t=="object"&&(t=ln(Hr(t,e),e)),t}function TF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=EE(ln(t,n),ln(e,n),n,!0);return n.skipEscape=!0,Hr(o,n)}function EE(t,e,r,n){let o={};return n||(t=ln(Hr(t,r),r),e=ln(Hr(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=Aa(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=Aa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Aa(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=Aa(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 PF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Hr(ml(ln(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Hr(ml(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Hr(ml(ln(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Hr(ml(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Hr(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=[],s=wE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=SF(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Aa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var RF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ln(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;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(RF);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(kF(n.host)===!1){let c=vF(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=wE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&wF(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var yy={SCHEMES:EF,normalize:$F,resolve:TF,resolveComponent:EE,equal:PF,serialize:Hr,parse:ln};fl.exports=yy;fl.exports.default=yy;fl.exports.fastUri=yy});var PE=L(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var TE=$E();TE.code='require("ajv/dist/runtime/uri").default';_y.default=TE});var ME=L(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.CodeGen=ut.Name=ut.nil=ut.stringify=ut.str=ut._=ut.KeywordCxt=void 0;var CF=Oa();Object.defineProperty(ut,"KeywordCxt",{enumerable:!0,get:function(){return CF.KeywordCxt}});var Qs=oe();Object.defineProperty(ut,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(ut,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(ut,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(ut,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(ut,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(ut,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var OF=cl(),AE=Ia(),IF=Wg(),Na=ll(),AF=oe(),Da=Pa(),hl=Ta(),xy=me(),RE=fE(),NF=PE(),NE=(t,e)=>new RegExp(t,e);NE.code="new RegExp";var DF=["removeAdditional","useDefaults","coerceTypes"],MF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),jF={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."},LF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},CE=200;function zF(t){var e,r,n,o,s,i,a,c,u,l,d,m,h,p,f,g,y,_,b,v,E,C,x,k,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,O=R===!0||R===void 0?1:R||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:NE,K=(o=t.uriResolver)!==null&&o!==void 0?o:NF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&m!==void 0?m:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:O,regExp:F}:{optimize:O,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:CE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:CE,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(v=t.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(x=t.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(k=t.unicodeRegExp)!==null&&k!==void 0?k:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:K}}var Ma=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,...zF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new AF.ValueScope({scope:{},prefixes:MF,es5:r,lines:n}),this.logger=qF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,IF.getRules)(),OE.call(this,jF,e,"NOT SUPPORTED"),OE.call(this,LF,e,"DEPRECATED","warn"),this._metaOpts=BF.call(this),e.formats&&HF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&UF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),FF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=RE;n==="id"&&(o={...RE},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 AE.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,Da.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=IE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Na.SchemaEnv({schema:{},schemaId:n});if(r=Na.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=IE.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,Da.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(WF.call(this,n,r),!r)return(0,xy.eachItem)(n,s=>by.call(this,s)),this;GF.call(this,r);let o={...r,type:(0,hl.getJSONTypes)(r.type),schemaType:(0,hl.getJSONTypes)(r.schemaType)};return(0,xy.eachItem)(n,o.type.length===0?s=>by.call(this,s,o):s=>o.type.forEach(i=>by.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]=DE(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,Da.normalizeId)(i||n);let u=Da.getSchemaRefs.call(this,e,n);return c=new Na.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):Na.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{Na.compileSchema.call(this,e)}finally{this.opts=r}}};Ma.ValidationError=OF.default;Ma.MissingRefError=AE.default;ut.default=Ma;function OE(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 IE(t){return t=(0,Da.normalizeId)(t),this.schemas[t]||this.refs[t]}function FF(){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 HF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function UF(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 BF(){let t={...this.opts};for(let e of DF)delete t[e];return t}var ZF={log(){},warn(){},error(){}};function qF(t){if(t===!1)return ZF;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 VF=/^[a-z_$][a-z0-9_$:-]*$/i;function WF(t,e){let{RULES:r}=this;if((0,xy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!VF.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 by(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,hl.getJSONTypes)(e.type),schemaType:(0,hl.getJSONTypes)(e.schemaType)}};e.before?KF.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 KF(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 GF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=DE(e)),t.validateSchema=this.compile(e,!0))}var JF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function DE(t){return{anyOf:[t,JF]}}});var jE=L(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var XF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vy.default=XF});var HE=L(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.callRef=qo.getValidate=void 0;var YF=Ia(),LE=cr(),jt=oe(),ei=cn(),zE=ll(),gl=me(),QF={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=zE.resolveRef.call(c,u,o,r);if(l===void 0)throw new YF.default(n.opts.uriResolver,o,r);if(l instanceof zE.SchemaEnv)return m(l);return h(l);function d(){if(s===u)return yl(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return yl(t,(0,jt._)`${p}.validate`,u,u.$async)}function m(p){let f=FE(t,p);yl(t,f,p,p.$async)}function h(p){let f=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,jt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:jt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function FE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,jt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qo.getValidate=FE;function yl(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,LE.callValidateCode)(t,e,u)}`),h(e),i||o.assign(p,!0)},f=>{o.if((0,jt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),m(f),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,LE.callValidateCode)(t,e,u),()=>h(e),()=>m(e))}function m(p){let f=(0,jt._)`${p}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${f} : ${ei.default.vErrors}.concat(${f})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function h(p){var f;if(!s.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=gl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${p}.evaluated.props`);s.props=gl.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=gl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${p}.evaluated.items`);s.items=gl.mergeEvaluated.items(o,y,s.items,jt.Name)}}}qo.callRef=yl;qo.default=QF});var UE=L(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var eH=jE(),tH=HE(),rH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",eH.default,tH.default];Sy.default=rH});var BE=L(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var _l=oe(),Zn=_l.operators,bl={maximum:{okStr:"<=",ok:Zn.LTE,fail:Zn.GT},minimum:{okStr:">=",ok:Zn.GTE,fail:Zn.LT},exclusiveMaximum:{okStr:"<",ok:Zn.LT,fail:Zn.GTE},exclusiveMinimum:{okStr:">",ok:Zn.GT,fail:Zn.LTE}},nH={message:({keyword:t,schemaCode:e})=>(0,_l.str)`must be ${bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,_l._)`{comparison: ${bl[t].okStr}, limit: ${e}}`},oH={keyword:Object.keys(bl),type:"number",schemaType:"number",$data:!0,error:nH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,_l._)`${r} ${bl[e].fail} ${n} || isNaN(${r})`)}};ky.default=oH});var ZE=L(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var ja=oe(),sH={message:({schemaCode:t})=>(0,ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ja._)`{multipleOf: ${t}}`},iH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:sH,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ja._)`${i} !== parseInt(${i})`;t.fail$data((0,ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wy.default=iH});var VE=L(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});function qE(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}Ey.default=qE;qE.code='require("ajv/dist/runtime/ucs2length").default'});var WE=L($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var Vo=oe(),aH=me(),cH=VE(),uH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},lH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:uH,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vo.operators.GT:Vo.operators.LT,i=o.opts.unicode===!1?(0,Vo._)`${r}.length`:(0,Vo._)`${(0,aH.useFunc)(t.gen,cH.default)}(${r})`;t.fail$data((0,Vo._)`${i} ${s} ${n}`)}};$y.default=lH});var KE=L(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});var dH=cr(),pH=me(),ti=oe(),mH={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},fH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mH,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,ti._)`new RegExp`:(0,pH.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,dH.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${r})`)}}};Ty.default=fH});var GE=L(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var La=oe(),hH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},gH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:hH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`Object.keys(${r}).length ${o} ${n}`)}};Py.default=gH});var JE=L(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var za=cr(),Fa=oe(),yH=me(),_H={message:({params:{missingProperty:t}})=>(0,Fa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Fa._)`{missingProperty: ${t}}`},bH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_H,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 h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let f of r)if(h?.[f]===void 0&&!p.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,yH.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Fa.nil,d);else for(let h of r)(0,za.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>m(h,p)),t.ok(p)}else e.if((0,za.checkMissingProp)(t,r,h)),(0,za.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,za.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function m(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,za.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Fa.not)(p),()=>{t.error(),e.break()})},Fa.nil)}}};Ry.default=bH});var XE=L(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});var Ha=oe(),xH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ha.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ha._)`{limit: ${t}}`},vH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ha.operators.GT:Ha.operators.LT;t.fail$data((0,Ha._)`${r}.length ${o} ${n}`)}};Cy.default=vH});var xl=L(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var YE=ty();YE.code='require("ajv/dist/runtime/equal").default';Oy.default=YE});var QE=L(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var Iy=Ta(),lt=oe(),SH=me(),kH=xl(),wH={message:({params:{i:t,j:e}})=>(0,lt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,lt._)`{i: ${t}, j: ${e}}`},EH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:wH,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,Iy.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,lt._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,lt._)`${r}.length`),f=e.let("j");t.setParams({i:p,j:f}),e.assign(c,!0),e.if((0,lt._)`${p} > 1`,()=>(d()?m:h)(p,f))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,f){let g=e.name("item"),y=(0,Iy.checkDataTypes)(u,g,a.opts.strictNumbers,Iy.DataType.Wrong),_=e.const("indices",(0,lt._)`{}`);e.for((0,lt._)`;${p}--;`,()=>{e.let(g,(0,lt._)`${r}[${p}]`),e.if(y,(0,lt._)`continue`),u.length>1&&e.if((0,lt._)`typeof ${g} == "string"`,(0,lt._)`${g} += "_"`),e.if((0,lt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,lt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,lt._)`${_}[${g}] = ${p}`)})}function h(p,f){let g=(0,SH.useFunc)(e,kH.default),y=e.name("outer");e.label(y).for((0,lt._)`;${p}--;`,()=>e.for((0,lt._)`${f} = ${p}; ${f}--;`,()=>e.if((0,lt._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Ay.default=EH});var e$=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=oe(),$H=me(),TH=xl(),PH={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ny._)`{allowedValue: ${t}}`},RH={keyword:"const",$data:!0,error:PH,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ny._)`!${(0,$H.useFunc)(e,TH.default)}(${r}, ${o})`):t.fail((0,Ny._)`${s} !== ${r}`)}};Dy.default=RH});var t$=L(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var Ua=oe(),CH=me(),OH=xl(),IH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ua._)`{allowedValues: ${t}}`},AH={keyword:"enum",schemaType:"array",$data:!0,error:IH,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,CH.useFunc)(e,OH.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 h=e.const("vSchema",s);l=(0,Ua.or)(...o.map((p,f)=>m(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Ua._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function m(h,p){let f=o[p];return typeof f=="object"&&f!==null?(0,Ua._)`${u()}(${r}, ${h}[${p}])`:(0,Ua._)`${r} === ${f}`}}};My.default=AH});var r$=L(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var NH=BE(),DH=ZE(),MH=WE(),jH=KE(),LH=GE(),zH=JE(),FH=XE(),HH=QE(),UH=e$(),BH=t$(),ZH=[NH.default,DH.default,MH.default,jH.default,LH.default,zH.default,FH.default,HH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},UH.default,BH.default];jy.default=ZH});var zy=L(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.validateAdditionalItems=void 0;var Wo=oe(),Ly=me(),qH={message:({params:{len:t}})=>(0,Wo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wo._)`{limit: ${t}}`},VH={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:qH,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ly.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}n$(t,n)}};function n$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Wo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Wo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ly.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Wo._)`${a} <= ${e.length}`);r.if((0,Wo.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Ly.Type.Num},u),i.allErrors||r.if((0,Wo.not)(u),()=>r.break())})}}Ba.validateAdditionalItems=n$;Ba.default=VH});var Fy=L(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateTuple=void 0;var o$=oe(),vl=me(),WH=cr(),KH={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return s$(t,"additionalItems",e);r.items=!0,!(0,vl.alwaysValidSchema)(r,e)&&t.ok((0,WH.validateArray)(t))}};function s$(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=vl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,o$._)`${s}.length`);r.forEach((d,m)=>{(0,vl.alwaysValidSchema)(a,d)||(n.if((0,o$._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:h}=a,p=r.length,f=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(m.strictTuples&&!f){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,vl.checkStrictMode)(a,g,m.strictTuples)}}}Za.validateTuple=s$;Za.default=KH});var i$=L(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});var GH=Fy(),JH={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,GH.validateTuple)(t,"items")};Hy.default=JH});var c$=L(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var a$=oe(),XH=me(),YH=cr(),QH=zy(),eU={message:({params:{len:t}})=>(0,a$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,a$._)`{limit: ${t}}`},tU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:eU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,XH.alwaysValidSchema)(n,e)&&(o?(0,QH.validateAdditionalItems)(t,o):t.ok((0,YH.validateArray)(t)))}};Uy.default=tU});var u$=L(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var lr=oe(),Sl=me(),rU={message:({params:{min:t,max:e}})=>e===void 0?(0,lr.str)`must contain at least ${t} valid item(s)`:(0,lr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,lr._)`{minContains: ${t}}`:(0,lr._)`{minContains: ${t}, maxContains: ${e}}`},nU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:rU,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,lr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Sl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Sl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Sl.alwaysValidSchema)(s,r)){let f=(0,lr._)`${l} >= ${i}`;a!==void 0&&(f=(0,lr._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,lr._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>p(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Sl.Type.Num,compositeRule:!0},f),g()})}function p(f){e.code((0,lr._)`${f}++`),a===void 0?e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,lr._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};By.default=nU});var p$=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateSchemaDeps=Ur.validatePropertyDeps=Ur.error=void 0;var Zy=oe(),oU=me(),qa=cr();Ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zy._)`{property: ${t},
|
|
479
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,re._)`[${o}]`)}}}function BL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,re._)`${e} !== undefined`,()=>t.assign((0,re._)`${e}[${r}]`,n))}function Xg(t,e,r,n=Gs.Correct){let o=n===Gs.Correct?re.operators.EQ:re.operators.NEQ,s;switch(t){case"null":return(0,re._)`${e} ${o} null`;case"array":s=(0,re._)`Array.isArray(${e})`;break;case"object":s=(0,re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,re._)`typeof ${e} ${o} ${t}`}return n===Gs.Correct?s:(0,re.not)(s);function i(a=re.nil){return(0,re.and)((0,re._)`typeof ${e} == "number"`,a,r?(0,re._)`isFinite(${e})`:re.nil)}}gt.checkDataType=Xg;function Yg(t,e,r,n){if(t.length===1)return Xg(t[0],e,r,n);let o,s=(0,jw.toHash)(t);if(s.array&&s.object){let i=(0,re._)`typeof ${e} != "object"`;o=s.null?i:(0,re._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=re.nil;s.number&&delete s.integer;for(let i in s)o=(0,re.and)(o,Xg(i,e,r,n));return o}gt.checkDataTypes=Yg;var ZL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,re._)`{type: ${t}}`:(0,re._)`{type: ${e}}`};function Qg(t){let e=qL(t);(0,LL.reportError)(e,ZL)}gt.reportTypeError=Qg;function qL(t){let{gen:e,data:r,schema:n}=t,o=(0,jw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Hw=L(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.assignDefaults=void 0;var Js=oe(),VL=me();function WL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Fw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Fw(t,s,o.default))}sl.assignDefaults=WL;function Fw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,VL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Js._)`${a} = ${(0,Js.stringify)(r)}`)}});var cr=L(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.validateUnion=Se.validateArray=Se.usePattern=Se.callValidateCode=Se.schemaProperties=Se.allSchemaProperties=Se.noPropertyInData=Se.propertyInData=Se.isOwnProperty=Se.hasPropFunc=Se.reportMissingProp=Se.checkMissingProp=Se.checkReportMissingProp=void 0;var Ae=oe(),ey=me(),Hn=un(),KL=me();function GL(t,e){let{gen:r,data:n,it:o}=t;r.if(ry(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}Se.checkReportMissingProp=GL;function JL({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(ry(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}Se.checkMissingProp=JL;function XL(t,e){t.setParams({missingProperty:e},!0),t.error()}Se.reportMissingProp=XL;function Uw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}Se.hasPropFunc=Uw;function ty(t,e,r){return(0,Ae._)`${Uw(t)}.call(${e}, ${r})`}Se.isOwnProperty=ty;function YL(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${ty(t,e,r)}`:o}Se.propertyInData=YL;function ry(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(ty(t,e,r))):o}Se.noPropertyInData=ry;function Bw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Se.allSchemaProperties=Bw;function QL(t,e){return Bw(e).filter(r=>!(0,ey.alwaysValidSchema)(t,e[r]))}Se.schemaProperties=QL;function ez({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,d=[[Hn.default.instancePath,(0,Ae.strConcat)(Hn.default.instancePath,s)],[Hn.default.parentData,i.parentData],[Hn.default.parentDataProperty,i.parentDataProperty],[Hn.default.rootData,Hn.default.rootData]];i.opts.dynamicRef&&d.push([Hn.default.dynamicAnchors,Hn.default.dynamicAnchors]);let p=(0,Ae._)`${l}, ${r.object(...d)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${p})`:(0,Ae._)`${a}(${p})`}Se.callValidateCode=ez;var tz=(0,Ae._)`new RegExp`;function rz({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,Ae._)`${o.code==="new RegExp"?tz:(0,KL.useFunc)(t,o)}(${r}, ${n})`})}Se.usePattern=rz;function nz(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,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ey.Type.Num},s),e.if((0,Ae.not)(s),a)})}}Se.validateArray=nz;function oz(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,ey.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,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Se.validateUnion=oz});var Vw=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.validateKeywordUsage=zr.validSchemaType=zr.funcKeywordCode=zr.macroKeywordCode=void 0;var Tt=oe(),Bo=un(),sz=cr(),iz=$a();function az(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=qw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Tt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}zr.macroKeywordCode=az;function cz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;lz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=qw(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)f(),e.modifying&&Zw(t),g(()=>t.error());else{let y=e.async?h():m();e.modifying&&Zw(t),g(()=>uz(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,Tt._)`await `),_=>n.assign(d,!1).if((0,Tt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Tt._)`${_}.errors`),()=>n.throw(_))),y}function m(){let y=(0,Tt._)`${l}.errors`;return n.assign(y,null),f(Tt.nil),y}function f(y=e.async?(0,Tt._)`await `:Tt.nil){let _=c.opts.passContext?Bo.default.this:Bo.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Tt._)`${y}${(0,sz.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;n.if((0,Tt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}zr.funcKeywordCode=cz;function Zw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Tt._)`${n.parentData}[${n.parentDataProperty}]`))}function uz(t,e){let{gen:r}=t;r.if((0,Tt._)`Array.isArray(${e})`,()=>{r.assign(Bo.default.vErrors,(0,Tt._)`${Bo.default.vErrors} === null ? ${e} : ${Bo.default.vErrors}.concat(${e})`).assign(Bo.default.errors,(0,Tt._)`${Bo.default.vErrors}.length`),(0,iz.extendErrors)(t)},()=>t.error())}function lz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function qw(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,Tt.stringify)(r)})}function dz(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")}zr.validSchemaType=dz;function pz({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)}}zr.validateKeywordUsage=pz});var Kw=L(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.extendSubschemaMode=Un.extendSubschemaData=Un.getSubschema=void 0;var Fr=oe(),Ww=me();function mz(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,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}${(0,Fr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ww.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')}Un.getSubschema=mz;function fz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Fr._)`${e.data}${(0,Fr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Fr.str)`${u}${(0,Ww.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Fr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Fr.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]}}Un.extendSubschemaData=fz;function hz(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}Un.extendSubschemaMode=hz});var ny=L((WG,Gw)=>{"use strict";Gw.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 Xw=L((KG,Jw)=>{"use strict";var Bn=Jw.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(){};il(e,n,o,t,"",t)};Bn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Bn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Bn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Bn.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 il(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 Bn.arrayKeywords)for(var p=0;p<d.length;p++)il(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in Bn.propsKeywords){if(d&&typeof d=="object")for(var h in d)il(t,e,r,d[h],o+"/"+l+"/"+gz(h),s,o,l,n,h)}else(l in Bn.keywords||t.allKeys&&!(l in Bn.skipKeywords))&&il(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function gz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Pa=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;var yz=me(),_z=ny(),xz=Xw(),bz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!oy(t):e?Yw(t)<=e:!1}Mt.inlineRef=vz;var Sz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function oy(t){for(let e in t){if(Sz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(oy)||typeof r=="object"&&oy(r))return!0}return!1}function Yw(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!bz.has(r)&&(typeof t[r]=="object"&&(0,yz.eachItem)(t[r],n=>e+=Yw(n)),e===1/0))return 1/0}return e}function Qw(t,e="",r){r!==!1&&(e=Xs(e));let n=t.parse(e);return eE(t,n)}Mt.getFullPath=Qw;function eE(t,e){return t.serialize(e).split("#")[0]+"#"}Mt._getFullPath=eE;var kz=/#\/?$/;function Xs(t){return t?t.replace(kz,""):""}Mt.normalizeId=Xs;function wz(t,e,r){return r=Xs(r),t.resolve(e,r)}Mt.resolveUrl=wz;var Ez=/^[a-z_][-a-z0-9._]*$/i;function $z(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xs(t[r]||e),s={"":o},i=Qw(n,o,!1),a={},c=new Set;return xz(t,{allKeys:!0},(d,p,h,m)=>{if(m===void 0)return;let f=i+p,g=s[m];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(x){let v=this.opts.uriResolver.resolve;if(x=Xs(g?v(g,x):x),c.has(x))throw l(x);c.add(x);let E=this.refs[x];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,x):x!==Xs(f)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=f),x}function _(x){if(typeof x=="string"){if(!Ez.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,p,h){if(p!==void 0&&!_z(d,p))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Mt.getSchemaRefs=$z});var Oa=L(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.getData=Zn.KeywordCxt=Zn.validateFunctionCode=void 0;var sE=Nw(),tE=Ta(),iy=Jg(),al=Ta(),Tz=Hw(),Ca=Vw(),sy=Kw(),V=oe(),ee=un(),Pz=Pa(),ln=me(),Ra=$a();function Rz(t){if(cE(t)&&(uE(t),aE(t))){Iz(t);return}iE(t,()=>(0,sE.topBoolOrEmptySchema)(t))}Zn.validateFunctionCode=Rz;function iE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${rE(r,o)}`),Oz(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${Cz(o)}`,n.$async,()=>t.code(rE(r,o)).code(s))}function Cz(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function Oz(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function Iz(t){let{schema:e,opts:r,gen:n}=t;iE(t,()=>{r.$comment&&e.$comment&&dE(t),jz(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&Az(t),lE(t),Fz(t)})}function Az(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function rE(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function Nz(t,e){if(cE(t)&&(uE(t),aE(t))){Dz(t,e);return}(0,sE.boolOrEmptySchema)(t,e)}function aE({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 cE(t){return typeof t.schema!="boolean"}function Dz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&dE(t),Lz(t),zz(t);let s=n.const("_errs",ee.default.errors);lE(t,s),n.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function uE(t){(0,ln.checkUnknownRules)(t),Mz(t)}function lE(t,e){if(t.opts.jtd)return nE(t,[],!1,e);let r=(0,tE.getSchemaTypes)(t.schema),n=(0,tE.coerceAndCheckDataType)(t,r);nE(t,r,!n,e)}function Mz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ln.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function jz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ln.checkStrictMode)(t,"default is ignored in the schema root")}function Lz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Pz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function dE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Fz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&Hz(t),e.return((0,V._)`${ee.default.errors} === 0`))}function Hz({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function nE(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,ln.schemaHasRulesButRef)(s,l))){o.block(()=>mE(t,"$ref",l.all.$ref.definition));return}c.jtd||Uz(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,iy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,al.checkDataType)(p.type,i,c.strictNumbers)),oE(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,al.reportTypeError)(t)),o.endIf()):oE(t,p),a||o.if((0,V._)`${ee.default.errors} === ${n||0}`))}}function oE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Tz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,iy.shouldUseRule)(n,s)&&mE(t,s.keyword,s.definition,e.type)})}function Uz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Bz(t,e),t.opts.allowUnionTypes||Zz(t,e),qz(t,t.dataTypes))}function Bz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{pE(t.dataTypes,r)||ay(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Wz(t,e)}}function Zz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ay(t,"use allowUnionTypes to allow union type keyword")}function qz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,iy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Vz(e,i))&&ay(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Vz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function pE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Wz(t,e){let r=[];for(let n of t.dataTypes)pE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ay(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ln.checkStrictMode)(t,e,t.opts.strictTypes)}var cl=class{constructor(e,r,n){if((0,Ca.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,ln.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",fE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ca.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",ee.default.errors))}result(e,r,n){this.failResult((0,V.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,V.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,V._)`${r} !== undefined && (${(0,V.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?Ra.reportExtraError:Ra.reportError)(this,this.def.error,r)}$dataError(){(0,Ra.reportError)(this,this.def.$dataError||Ra.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ra.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=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,al.checkDataTypes)(c,r,s.opts.strictNumbers,al.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,sy.getSubschema)(this.it,e);(0,sy.extendSubschemaData)(n,this.it,e),(0,sy.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Nz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ln.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ln.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,V.Name)),!0}};Zn.KeywordCxt=cl;function mE(t,e,r,n){let o=new cl(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ca.funcKeywordCode)(o,r):"macro"in r?(0,Ca.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ca.funcKeywordCode)(o,r)}var Kz=/^\/(?:[^~]|~0|~1)*$/,Gz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!Kz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=Gz.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,V._)`${s}${(0,V.getProperty)((0,ln.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Zn.getData=fE});var ul=L(uy=>{"use strict";Object.defineProperty(uy,"__esModule",{value:!0});var cy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};uy.default=cy});var Ia=L(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var ly=Pa(),dy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,ly.resolveUrl)(e,r,n),this.missingSchema=(0,ly.normalizeId)((0,ly.getFullPath)(e,this.missingRef))}};py.default=dy});var dl=L(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;var br=oe(),Jz=ul(),Zo=un(),vr=Pa(),hE=me(),Xz=Oa(),Ys=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,vr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ur.SchemaEnv=Ys;function fy(t){let e=gE.call(this,t);if(e)return e;let r=(0,vr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new br.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Jz.default,code:(0,br._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Zo.default.data,parentData:Zo.default.parentData,parentDataProperty:Zo.default.parentDataProperty,dataNames:[Zo.default.data],dataPathArr:[br.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,br.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:br.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,br._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Xz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Zo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Zo.default.self}`,`${Zo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:f}=u;h.evaluated={props:m instanceof br.Name?void 0:m,items:f instanceof br.Name?void 0:f,dynamicProps:m instanceof br.Name,dynamicItems:f instanceof br.Name},h.source&&(h.source.evaluated=(0,br.stringify)(h.evaluated))}return t.validate=h,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)}}ur.compileSchema=fy;function Yz(t,e,r){var n;r=(0,vr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=tF.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 Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Qz.call(this,s)}ur.resolveRef=Yz;function Qz(t){return(0,vr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:fy.call(this,t)}function gE(t){for(let e of this._compilations)if(eF(e,t))return e}ur.getCompilingSchema=gE;function eF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function tF(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ll.call(this,t,e)}function ll(t,e){let r=this.opts.uriResolver.parse(e),n=(0,vr._getFullPath)(this.opts.uriResolver,r),o=(0,vr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return my.call(this,r,t);let s=(0,vr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ll.call(this,t,i);return typeof a?.schema!="object"?void 0:my.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||fy.call(this,i),s===(0,vr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,vr.resolveUrl)(this.opts.uriResolver,o,u)),new Ys({schema:a,schemaId:c,root:t,baseId:o})}return my.call(this,r,i)}}ur.resolveSchema=ll;var rF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function my(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,hE.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!rF.has(a)&&u&&(e=(0,vr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,hE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,vr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ll.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var yE=L((eJ,nF)=>{nF.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 gy=L((tJ,vE)=>{"use strict";var oF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),xE=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);function hy(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 sF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _E(t){return t.length=0,!0}function iF(t,e,r){if(t.length){let n=hy(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function aF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=iF;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=_E}else{o.push(u);continue}}return o.length&&(a===_E?r.zone=o.join(""):i?n.push(o.join("")):n.push(hy(o))),r.address=n.join(""),r}function bE(t){if(cF(t,":")<2)return{host:t,isIPV6:!1};let e=aF(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function cF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function uF(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 lF(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function dF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!xE(r)){let n=bE(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}vE.exports={nonSimpleDomain:sF,recomposeAuthority:dF,normalizeComponentEncoding:lF,removeDotSegments:uF,isIPv4:xE,isUUID:oF,normalizeIPv6:bE,stringArrayToHexStripped:hy}});var $E=L((rJ,EE)=>{"use strict";var{isUUID:pF}=gy(),mF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fF=["http","https","ws","wss","urn","urn:uuid"];function hF(t){return fF.indexOf(t)!==-1}function yy(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 SE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function kE(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 gF(t){return t.secure=yy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yF(t){if((t.port===(yy(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,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function _F(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mF);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=_y(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function xF(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=_y(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 bF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function vF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var wE={scheme:"http",domainHost:!0,parse:SE,serialize:kE},SF={scheme:"https",domainHost:wE.domainHost,parse:SE,serialize:kE},pl={scheme:"ws",domainHost:!0,parse:gF,serialize:yF},kF={scheme:"wss",domainHost:pl.domainHost,parse:pl.parse,serialize:pl.serialize},wF={scheme:"urn",parse:_F,serialize:xF,skipNormalize:!0},EF={scheme:"urn:uuid",parse:bF,serialize:vF,skipNormalize:!0},ml={http:wE,https:SF,ws:pl,wss:kF,urn:wF,"urn:uuid":EF};Object.setPrototypeOf(ml,null);function _y(t){return t&&(ml[t]||ml[t.toLowerCase()])||void 0}EE.exports={wsIsSecure:yy,SCHEMES:ml,isValidSchemeName:hF,getSchemeHandler:_y}});var RE=L((nJ,hl)=>{"use strict";var{normalizeIPv6:$F,removeDotSegments:Aa,recomposeAuthority:TF,normalizeComponentEncoding:fl,isIPv4:PF,nonSimpleDomain:RF}=gy(),{SCHEMES:CF,getSchemeHandler:TE}=$E();function OF(t,e){return typeof t=="string"?t=Hr(dn(t,e),e):typeof t=="object"&&(t=dn(Hr(t,e),e)),t}function IF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=PE(dn(t,n),dn(e,n),n,!0);return n.skipEscape=!0,Hr(o,n)}function PE(t,e,r,n){let o={};return n||(t=dn(Hr(t,r),r),e=dn(Hr(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=Aa(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=Aa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Aa(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=Aa(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 AF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Hr(fl(dn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Hr(fl(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Hr(fl(dn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Hr(fl(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Hr(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=[],s=TE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=TF(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Aa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var NF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function dn(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;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(NF);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(PF(n.host)===!1){let c=$F(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=TE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&RF(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var xy={SCHEMES:CF,normalize:OF,resolve:IF,resolveComponent:PE,equal:AF,serialize:Hr,parse:dn};hl.exports=xy;hl.exports.default=xy;hl.exports.fastUri=xy});var OE=L(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var CE=RE();CE.code='require("ajv/dist/runtime/uri").default';by.default=CE});var zE=L(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.CodeGen=ut.Name=ut.nil=ut.stringify=ut.str=ut._=ut.KeywordCxt=void 0;var DF=Oa();Object.defineProperty(ut,"KeywordCxt",{enumerable:!0,get:function(){return DF.KeywordCxt}});var Qs=oe();Object.defineProperty(ut,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(ut,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(ut,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(ut,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(ut,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(ut,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var MF=ul(),ME=Ia(),jF=Gg(),Na=dl(),LF=oe(),Da=Pa(),gl=Ta(),Sy=me(),IE=yE(),zF=OE(),jE=(t,e)=>new RegExp(t,e);jE.code="new RegExp";var FF=["removeAdditional","useDefaults","coerceTypes"],HF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UF={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."},BF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},AE=200;function ZF(t){var e,r,n,o,s,i,a,c,u,l,d,p,h,m,f,g,y,_,x,v,E,C,b,k,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,O=R===!0||R===void 0?1:R||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:jE,K=(o=t.uriResolver)!==null&&o!==void 0?o:zF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&p!==void 0?p:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:O,regExp:F}:{optimize:O,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:AE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:AE,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(v=t.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(b=t.validateFormats)!==null&&b!==void 0?b:!0,unicodeRegExp:(k=t.unicodeRegExp)!==null&&k!==void 0?k:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:K}}var Ma=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,...ZF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new LF.ValueScope({scope:{},prefixes:HF,es5:r,lines:n}),this.logger=JF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jF.getRules)(),NE.call(this,UF,e,"NOT SUPPORTED"),NE.call(this,BF,e,"DEPRECATED","warn"),this._metaOpts=KF.call(this),e.formats&&VF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&WF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),qF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=IE;n==="id"&&(o={...IE},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof ME.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,Da.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=DE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Na.SchemaEnv({schema:{},schemaId:n});if(r=Na.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=DE.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,Da.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(YF.call(this,n,r),!r)return(0,Sy.eachItem)(n,s=>vy.call(this,s)),this;eH.call(this,r);let o={...r,type:(0,gl.getJSONTypes)(r.type),schemaType:(0,gl.getJSONTypes)(r.schemaType)};return(0,Sy.eachItem)(n,o.type.length===0?s=>vy.call(this,s,o):s=>o.type.forEach(i=>vy.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]=LE(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,Da.normalizeId)(i||n);let u=Da.getSchemaRefs.call(this,e,n);return c=new Na.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):Na.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{Na.compileSchema.call(this,e)}finally{this.opts=r}}};Ma.ValidationError=MF.default;Ma.MissingRefError=ME.default;ut.default=Ma;function NE(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 DE(t){return t=(0,Da.normalizeId)(t),this.schemas[t]||this.refs[t]}function qF(){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 VF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function WF(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 KF(){let t={...this.opts};for(let e of FF)delete t[e];return t}var GF={log(){},warn(){},error(){}};function JF(t){if(t===!1)return GF;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 XF=/^[a-z_$][a-z0-9_$:-]*$/i;function YF(t,e){let{RULES:r}=this;if((0,Sy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XF.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 vy(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,gl.getJSONTypes)(e.type),schemaType:(0,gl.getJSONTypes)(e.schemaType)}};e.before?QF.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 QF(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 eH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=LE(e)),t.validateSchema=this.compile(e,!0))}var tH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function LE(t){return{anyOf:[t,tH]}}});var FE=L(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var rH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ky.default=rH});var ZE=L(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.callRef=qo.getValidate=void 0;var nH=Ia(),HE=cr(),jt=oe(),ei=un(),UE=dl(),yl=me(),oH={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=UE.resolveRef.call(c,u,o,r);if(l===void 0)throw new nH.default(n.opts.uriResolver,o,r);if(l instanceof UE.SchemaEnv)return p(l);return h(l);function d(){if(s===u)return _l(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return _l(t,(0,jt._)`${m}.validate`,u,u.$async)}function p(m){let f=BE(t,m);_l(t,f,m,m.$async)}function h(m){let f=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,jt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:jt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function BE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,jt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qo.getValidate=BE;function _l(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,HE.callValidateCode)(t,e,u)}`),h(e),i||o.assign(m,!0)},f=>{o.if((0,jt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),p(f),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,HE.callValidateCode)(t,e,u),()=>h(e),()=>p(e))}function p(m){let f=(0,jt._)`${m}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${f} : ${ei.default.vErrors}.concat(${f})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function h(m){var f;if(!s.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=yl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${m}.evaluated.props`);s.props=yl.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=yl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${m}.evaluated.items`);s.items=yl.mergeEvaluated.items(o,y,s.items,jt.Name)}}}qo.callRef=_l;qo.default=oH});var qE=L(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var sH=FE(),iH=ZE(),aH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sH.default,iH.default];wy.default=aH});var VE=L(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var xl=oe(),qn=xl.operators,bl={maximum:{okStr:"<=",ok:qn.LTE,fail:qn.GT},minimum:{okStr:">=",ok:qn.GTE,fail:qn.LT},exclusiveMaximum:{okStr:"<",ok:qn.LT,fail:qn.GTE},exclusiveMinimum:{okStr:">",ok:qn.GT,fail:qn.LTE}},cH={message:({keyword:t,schemaCode:e})=>(0,xl.str)`must be ${bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,xl._)`{comparison: ${bl[t].okStr}, limit: ${e}}`},uH={keyword:Object.keys(bl),type:"number",schemaType:"number",$data:!0,error:cH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,xl._)`${r} ${bl[e].fail} ${n} || isNaN(${r})`)}};Ey.default=uH});var WE=L($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var ja=oe(),lH={message:({schemaCode:t})=>(0,ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ja._)`{multipleOf: ${t}}`},dH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lH,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ja._)`${i} !== parseInt(${i})`;t.fail$data((0,ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};$y.default=dH});var GE=L(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});function KE(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}Ty.default=KE;KE.code='require("ajv/dist/runtime/ucs2length").default'});var JE=L(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var Vo=oe(),pH=me(),mH=GE(),fH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},hH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fH,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vo.operators.GT:Vo.operators.LT,i=o.opts.unicode===!1?(0,Vo._)`${r}.length`:(0,Vo._)`${(0,pH.useFunc)(t.gen,mH.default)}(${r})`;t.fail$data((0,Vo._)`${i} ${s} ${n}`)}};Py.default=hH});var XE=L(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var gH=cr(),yH=me(),ti=oe(),_H={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},xH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_H,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,ti._)`new RegExp`:(0,yH.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,gH.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${r})`)}}};Ry.default=xH});var YE=L(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});var La=oe(),bH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},vH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`Object.keys(${r}).length ${o} ${n}`)}};Cy.default=vH});var QE=L(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var za=cr(),Fa=oe(),SH=me(),kH={message:({params:{missingProperty:t}})=>(0,Fa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Fa._)`{missingProperty: ${t}}`},wH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kH,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 h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let f of r)if(h?.[f]===void 0&&!m.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,SH.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Fa.nil,d);else for(let h of r)(0,za.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(h,m)),t.ok(m)}else e.if((0,za.checkMissingProp)(t,r,h)),(0,za.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,za.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function p(h,m){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(m,(0,za.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Fa.not)(m),()=>{t.error(),e.break()})},Fa.nil)}}};Oy.default=wH});var e$=L(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});var Ha=oe(),EH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ha.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ha._)`{limit: ${t}}`},$H={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ha.operators.GT:Ha.operators.LT;t.fail$data((0,Ha._)`${r}.length ${o} ${n}`)}};Iy.default=$H});var vl=L(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var t$=ny();t$.code='require("ajv/dist/runtime/equal").default';Ay.default=t$});var r$=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=Ta(),lt=oe(),TH=me(),PH=vl(),RH={message:({params:{i:t,j:e}})=>(0,lt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,lt._)`{i: ${t}, j: ${e}}`},CH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RH,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,Ny.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,lt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,lt._)`${r}.length`),f=e.let("j");t.setParams({i:m,j:f}),e.assign(c,!0),e.if((0,lt._)`${m} > 1`,()=>(d()?p:h)(m,f))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,f){let g=e.name("item"),y=(0,Ny.checkDataTypes)(u,g,a.opts.strictNumbers,Ny.DataType.Wrong),_=e.const("indices",(0,lt._)`{}`);e.for((0,lt._)`;${m}--;`,()=>{e.let(g,(0,lt._)`${r}[${m}]`),e.if(y,(0,lt._)`continue`),u.length>1&&e.if((0,lt._)`typeof ${g} == "string"`,(0,lt._)`${g} += "_"`),e.if((0,lt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,lt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,lt._)`${_}[${g}] = ${m}`)})}function h(m,f){let g=(0,TH.useFunc)(e,PH.default),y=e.name("outer");e.label(y).for((0,lt._)`;${m}--;`,()=>e.for((0,lt._)`${f} = ${m}; ${f}--;`,()=>e.if((0,lt._)`${g}(${r}[${m}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Dy.default=CH});var n$=L(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var My=oe(),OH=me(),IH=vl(),AH={message:"must be equal to constant",params:({schemaCode:t})=>(0,My._)`{allowedValue: ${t}}`},NH={keyword:"const",$data:!0,error:AH,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,My._)`!${(0,OH.useFunc)(e,IH.default)}(${r}, ${o})`):t.fail((0,My._)`${s} !== ${r}`)}};jy.default=NH});var o$=L(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var Ua=oe(),DH=me(),MH=vl(),jH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ua._)`{allowedValues: ${t}}`},LH={keyword:"enum",schemaType:"array",$data:!0,error:jH,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,DH.useFunc)(e,MH.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 h=e.const("vSchema",s);l=(0,Ua.or)(...o.map((m,f)=>p(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Ua._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function p(h,m){let f=o[m];return typeof f=="object"&&f!==null?(0,Ua._)`${u()}(${r}, ${h}[${m}])`:(0,Ua._)`${r} === ${f}`}}};Ly.default=LH});var s$=L(zy=>{"use strict";Object.defineProperty(zy,"__esModule",{value:!0});var zH=VE(),FH=WE(),HH=JE(),UH=XE(),BH=YE(),ZH=QE(),qH=e$(),VH=r$(),WH=n$(),KH=o$(),GH=[zH.default,FH.default,HH.default,UH.default,BH.default,ZH.default,qH.default,VH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WH.default,KH.default];zy.default=GH});var Hy=L(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.validateAdditionalItems=void 0;var Wo=oe(),Fy=me(),JH={message:({params:{len:t}})=>(0,Wo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wo._)`{limit: ${t}}`},XH={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JH,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Fy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}i$(t,n)}};function i$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Wo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Wo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Fy.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Wo._)`${a} <= ${e.length}`);r.if((0,Wo.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Fy.Type.Num},u),i.allErrors||r.if((0,Wo.not)(u),()=>r.break())})}}Ba.validateAdditionalItems=i$;Ba.default=XH});var Uy=L(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateTuple=void 0;var a$=oe(),Sl=me(),YH=cr(),QH={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return c$(t,"additionalItems",e);r.items=!0,!(0,Sl.alwaysValidSchema)(r,e)&&t.ok((0,YH.validateArray)(t))}};function c$(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=Sl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,a$._)`${s}.length`);r.forEach((d,p)=>{(0,Sl.alwaysValidSchema)(a,d)||(n.if((0,a$._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:h}=a,m=r.length,f=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!f){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Sl.checkStrictMode)(a,g,p.strictTuples)}}}Za.validateTuple=c$;Za.default=QH});var u$=L(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var eU=Uy(),tU={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,eU.validateTuple)(t,"items")};By.default=tU});var d$=L(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var l$=oe(),rU=me(),nU=cr(),oU=Hy(),sU={message:({params:{len:t}})=>(0,l$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,l$._)`{limit: ${t}}`},iU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,rU.alwaysValidSchema)(n,e)&&(o?(0,oU.validateAdditionalItems)(t,o):t.ok((0,nU.validateArray)(t)))}};Zy.default=iU});var p$=L(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var lr=oe(),kl=me(),aU={message:({params:{min:t,max:e}})=>e===void 0?(0,lr.str)`must contain at least ${t} valid item(s)`:(0,lr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,lr._)`{minContains: ${t}}`:(0,lr._)`{minContains: ${t}, maxContains: ${e}}`},cU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aU,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,lr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,kl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,kl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,kl.alwaysValidSchema)(s,r)){let f=(0,lr._)`${l} >= ${i}`;a!==void 0&&(f=(0,lr._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,lr._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>m(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:kl.Type.Num,compositeRule:!0},f),g()})}function m(f){e.code((0,lr._)`${f}++`),a===void 0?e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,lr._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};qy.default=cU});var h$=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateSchemaDeps=Ur.validatePropertyDeps=Ur.error=void 0;var Vy=oe(),uU=me(),qa=cr();Ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Vy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Vy._)`{property: ${t},
|
|
477
480
|
missingProperty: ${n},
|
|
478
481
|
depsCount: ${e},
|
|
479
|
-
deps: ${r}}`};var sU={keyword:"dependencies",type:"object",schemaType:"object",error:Ur.error,code(t){let[e,r]=iU(t);l$(t,e),d$(t,r)}};function iU({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 l$(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,qa.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,qa.checkReportMissingProp)(t,u)}):(r.if((0,Zy._)`${c} && (${(0,qa.checkMissingProp)(t,a,s)})`),(0,qa.reportMissingProp)(t,s),r.else())}}Ur.validatePropertyDeps=l$;function d$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,oU.alwaysValidSchema)(s,e[a])||(r.if((0,qa.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))}Ur.validateSchemaDeps=d$;Ur.default=sU});var f$=L(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var m$=oe(),aU=me(),cU={message:"property name must be valid",params:({params:t})=>(0,m$._)`{propertyName: ${t.propertyName}}`},uU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:cU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,aU.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,m$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};qy.default=uU});var Wy=L(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var kl=cr(),Sr=oe(),lU=cn(),wl=me(),dU={message:"must NOT have additional properties",params:({params:t})=>(0,Sr._)`{additionalProperty: ${t.additionalProperty}}`},pU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:dU,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,wl.alwaysValidSchema)(i,r))return;let u=(0,kl.allSchemaProperties)(n.properties),l=(0,kl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Sr._)`${s} === ${lU.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let _=(0,wl.schemaRefOrVal)(i,n.properties,"properties");y=(0,kl.isOwnProperty)(e,_,g)}else u.length?y=(0,Sr.or)(...u.map(_=>(0,Sr._)`${g} === ${_}`)):y=Sr.nil;return l.length&&(y=(0,Sr.or)(y,...l.map(_=>(0,Sr._)`${(0,kl.usePattern)(t,_)}.test(${g})`))),(0,Sr.not)(y)}function h(g){e.code((0,Sr._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,wl.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sr.not)(y),()=>e.break()))}}function f(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:wl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};Vy.default=pU});var y$=L(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var mU=Oa(),h$=cr(),Ky=me(),g$=Wy(),fU={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&&g$.default.code(new mU.KeywordCxt(s,g$.default,"additionalProperties"));let i=(0,h$.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ky.mergeEvaluated.props(e,(0,Ky.toHash)(i),s.props));let a=i.filter(d=>!(0,Ky.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,h$.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)}}};Gy.default=fU});var v$=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var _$=cr(),El=oe(),b$=me(),x$=me(),hU={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,_$.allSchemaProperties)(r),c=a.filter(f=>(0,b$.alwaysValidSchema)(s,r[f]));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 El.Name)&&(s.props=(0,x$.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let f of a)u&&h(f),s.allErrors?p(f):(e.var(l,!0),p(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,b$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){e.forIn("key",n,g=>{e.if((0,El._)`${(0,_$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:x$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,El._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,El.not)(l),()=>e.break())})})}}};Jy.default=hU});var S$=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var gU=me(),yU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,gU.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"}};Xy.default=yU});var k$=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var _U=cr(),bU={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_U.validateUnion,error:{message:"must match a schema in anyOf"}};Yy.default=bU});var w$=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var $l=oe(),xU=me(),vU={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,$l._)`{passingSchemas: ${t.passing}}`},SU={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:vU,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,xU.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,$l._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$l._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,$l.Name)})})}}};Qy.default=SU});var E$=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var kU=me(),wU={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,kU.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};e_.default=wU});var P$=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Tl=oe(),T$=me(),EU={message:({params:t})=>(0,Tl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Tl._)`{failingKeyword: ${t.ifClause}}`},$U={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:EU,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,T$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=$$(n,"then"),s=$$(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,Tl.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,Tl._)`${l}`):t.setParams({ifClause:l})}}}};function $$(t,e){let r=t.schema[e];return r!==void 0&&!(0,T$.alwaysValidSchema)(t,r)}t_.default=$U});var R$=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var TU=me(),PU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,TU.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};r_.default=PU});var C$=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var RU=zy(),CU=i$(),OU=Fy(),IU=c$(),AU=u$(),NU=p$(),DU=f$(),MU=Wy(),jU=y$(),LU=v$(),zU=S$(),FU=k$(),HU=w$(),UU=E$(),BU=P$(),ZU=R$();function qU(t=!1){let e=[zU.default,FU.default,HU.default,UU.default,BU.default,ZU.default,DU.default,MU.default,NU.default,jU.default,LU.default];return t?e.push(CU.default,IU.default):e.push(RU.default,OU.default),e.push(AU.default),e}n_.default=qU});var O$=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var Ke=oe(),VU={message:({schemaCode:t})=>(0,Ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ke._)`{format: ${t}}`},WU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:VU,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():h();function m(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=r.const("fDef",(0,Ke._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ke._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Ke._)`${f}.type || "string"`).assign(y,(0,Ke._)`${f}.validate`),()=>r.assign(g,(0,Ke._)`"string"`).assign(y,f)),t.fail$data((0,Ke.or)(_(),b()));function _(){return c.strictSchema===!1?Ke.nil:(0,Ke._)`${i} && !${y}`}function b(){let v=l.$async?(0,Ke._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ke._)`${y}(${n})`,E=(0,Ke._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,Ke._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[f,g,y]=b(p);f===e&&t.pass(v());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(E){let C=E instanceof RegExp?(0,Ke.regexpCode)(E):c.code.formats?(0,Ke._)`${c.code.formats}${(0,Ke.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:E,code:C});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ke._)`${x}.validate`]:["string",E,x]}function v(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ke._)`await ${y}(${n})`}return typeof g=="function"?(0,Ke._)`${y}(${n})`:(0,Ke._)`${y}.test(${n})`}}}};o_.default=WU});var I$=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var KU=O$(),GU=[KU.default];s_.default=GU});var A$=L(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.contentVocabulary=ri.metadataVocabulary=void 0;ri.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ri.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var D$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var JU=UE(),XU=r$(),YU=C$(),QU=I$(),N$=A$(),e2=[JU.default,XU.default,(0,YU.default)(),QU.default,N$.metadataVocabulary,N$.contentVocabulary];i_.default=e2});var j$=L(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.DiscrError=void 0;var M$;(function(t){t.Tag="tag",t.Mapping="mapping"})(M$||(Pl.DiscrError=M$={}))});var z$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var ni=oe(),a_=j$(),L$=ll(),t2=Ia(),r2=me(),n2={message:({params:{discrError:t,tagName:e}})=>t===a_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ni._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},o2={keyword:"discriminator",type:"object",schemaType:"object",error:n2,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,ni._)`${r}${(0,ni.getProperty)(a)}`);e.if((0,ni._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:a_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=m();e.if(!1);for(let p in h)e.elseIf((0,ni._)`${u} === ${p}`),e.assign(c,d(h[p]));e.else(),t.error(!1,{discrError:a_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let p=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(f,ni.Name),p}function m(){var h;let p={},f=y(o),g=!0;for(let v=0;v<i.length;v++){let E=i[v];if(E?.$ref&&!(0,r2.schemaHasRulesButRef)(E,s.self.RULES)){let x=E.$ref;if(E=L$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),E instanceof L$.SchemaEnv&&(E=E.schema),E===void 0)throw new t2.default(s.opts.uriResolver,s.baseId,x)}let C=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(C,v)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:v}){return Array.isArray(v)&&v.includes(a)}function _(v,E){if(v.const)b(v.const,E);else if(v.enum)for(let C of v.enum)b(C,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(v,E){if(typeof v!="string"||v in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[v]=E}}}};c_.default=o2});var F$=L((FJ,s2)=>{s2.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 l_=L((Ne,u_)=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.MissingRefError=Ne.ValidationError=Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=Ne.Ajv=void 0;var i2=ME(),a2=D$(),c2=z$(),H$=F$(),u2=["/properties"],Rl="http://json-schema.org/draft-07/schema",oi=class extends i2.default{_addVocabularies(){super._addVocabularies(),a2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(c2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(H$,u2):H$;this.addMetaSchema(e,Rl,!1),this.refs["http://json-schema.org/schema"]=Rl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rl)?Rl:void 0)}};Ne.Ajv=oi;u_.exports=Ne=oi;u_.exports.Ajv=oi;Object.defineProperty(Ne,"__esModule",{value:!0});Ne.default=oi;var l2=Oa();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return l2.KeywordCxt}});var si=oe();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var d2=cl();Object.defineProperty(Ne,"ValidationError",{enumerable:!0,get:function(){return d2.default}});var p2=Ia();Object.defineProperty(Ne,"MissingRefError",{enumerable:!0,get:function(){return p2.default}})});var G$=L(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.formatNames=Zr.fastFormats=Zr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Zr.fullFormats={date:Br(q$,f_),time:Br(p_(!0),h_),"date-time":Br(U$(!0),W$),"iso-time":Br(p_(),V$),"iso-date-time":Br(U$(),K$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_2,"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:E2,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:b2,int32:{type:"number",validate:S2},int64:{type:"number",validate:k2},float:{type:"number",validate:Z$},double:{type:"number",validate:Z$},password:!0,binary:!0};Zr.fastFormats={...Zr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,f_),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h_),"date-time":Br(/^\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,W$),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,V$),"iso-date-time":Br(/^\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,K$),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};Zr.formatNames=Object.keys(Zr.fullFormats);function m2(t){return t%4===0&&(t%100!==0||t%400===0)}var f2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,h2=[0,31,28,31,30,31,30,31,31,30,31,30,31];function q$(t){let e=f2.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&&m2(r)?29:h2[n])}function f_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var d_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function p_(t){return function(r){let n=d_.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 h_(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 V$(t,e){if(!(t&&e))return;let r=d_.exec(t),n=d_.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 m_=/t|\s/i;function U$(t){let e=p_(t);return function(n){let o=n.split(m_);return o.length===2&&q$(o[0])&&e(o[1])}}function W$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function K$(t,e){if(!(t&&e))return;let[r,n]=t.split(m_),[o,s]=e.split(m_),i=f_(r,o);if(i!==void 0)return i||h_(n,s)}var g2=/\/|:/,y2=/^(?:[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 _2(t){return g2.test(t)&&y2.test(t)}var B$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function b2(t){return B$.lastIndex=0,B$.test(t)}var x2=-(2**31),v2=2**31-1;function S2(t){return Number.isInteger(t)&&t<=v2&&t>=x2}function k2(t){return Number.isInteger(t)}function Z$(){return!0}var w2=/[^\\]\\Z/;function E2(t){if(w2.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var J$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var $2=l_(),kr=oe(),qn=kr.operators,Cl={formatMaximum:{okStr:"<=",ok:qn.LTE,fail:qn.GT},formatMinimum:{okStr:">=",ok:qn.GTE,fail:qn.LT},formatExclusiveMaximum:{okStr:"<",ok:qn.LT,fail:qn.GTE},formatExclusiveMinimum:{okStr:">",ok:qn.GT,fail:qn.LTE}},T2={message:({keyword:t,schemaCode:e})=>(0,kr.str)`should be ${Cl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kr._)`{comparison: ${Cl[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(Cl),type:"string",schemaType:"string",$data:!0,error:T2,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 $2.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}),h=e.const("fmt",(0,kr._)`${m}[${c.schemaCode}]`);t.fail$data((0,kr.or)((0,kr._)`typeof ${h} != "object"`,(0,kr._)`${h} instanceof RegExp`,(0,kr._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let m=c.schema,h=a.formats[m];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:h,code:i.code.formats?(0,kr._)`${i.code.formats}${(0,kr.getProperty)(m)}`:void 0});t.fail$data(d(p))}function d(m){return(0,kr._)`${m}.compare(${r}, ${n}) ${Cl[o].fail} 0`}},dependencies:["format"]};var P2=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=P2});var eT=L((Va,Q$)=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var ai=G$(),R2=J$(),g_=oe(),X$=new g_.Name("fullFormats"),C2=new g_.Name("fastFormats"),y_=(t,e={keywords:!0})=>{if(Array.isArray(e))return Y$(t,e,ai.fullFormats,X$),t;let[r,n]=e.mode==="fast"?[ai.fastFormats,C2]:[ai.fullFormats,X$],o=e.formats||ai.formatNames;return Y$(t,o,r,n),e.keywords&&(0,R2.default)(t),t};y_.get=(t,e="full")=>{let n=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Y$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,g_._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Q$.exports=Va=y_;Object.defineProperty(Va,"__esModule",{value:!0});Va.default=y_});function O2(){let t=new tT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,rT.default)(t),t}var tT,rT,Ol,nT=S(()=>{tT=bi(l_(),1),rT=bi(eT(),1);Ol=class{constructor(e){this._ajv=e??O2()}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)}}}});var Il,oT=S(()=>{jo();Il=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},ga,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},Zs,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 sT(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 iT(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 aT=S(()=>{});var Al,cT=S(()=>{hw();jo();nT();oa();oT();aT();Al=class extends Gu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ha.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 Ol,this.setRequestHandler(Ih,n=>this._oninitialize(n)),this.setNotificationHandler(Ah,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ha.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Il(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fw(this._capabilities,e)}setRequestHandler(e,r){let o=Nn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(nr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}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=An(Bs,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new Z(G.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let p=An(js,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new Z(G.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let h=An(ju,m);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new Z(G.InvalidParams,`Invalid tools/call result: ${p}`)}return h.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){iT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&sT(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:f0.includes(r)?r:Th,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"},Eu)}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},Hh,r):this.request({method:"sampling/createMessage",params:e},ga,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},Zs,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},Zs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(G.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},Uh,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"})}}});function __(t){return!!t&&typeof t=="object"&&lT in t}function dT(t){return t[lT]?.complete}var lT,uT,pT=S(()=>{lT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(uT||(uT={}))});var mT=S(()=>{});function A2(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"),!I2.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 N2(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 b_(t){let e=A2(t);return N2(t,e.warnings),e.isValid}var I2,fT=S(()=>{I2=/^[A-Za-z0-9._-]{1,128}$/});var Nl,hT=S(()=>{Nl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Dl=S(()=>{Gc();Gc()});function _T(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function bT(t){return"_def"in t||"_zod"in t||_T(t)}function x_(t){return typeof t!="object"||t===null||bT(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(_T)}function gT(t){if(t){if(x_(t))return Mo(t);if(!bT(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function M2(t){let e=Nn(t);return e?Object.entries(e).map(([r,n])=>{let o=zk(n),s=Fk(n);return{name:r,description:o,required:!s}}):[]}function Vn(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function yT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ml,D2,Wa,xT=S(()=>{cT();oa();Eg();jo();pT();mT();fT();hT();Dl();Ml=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 Al(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Nl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(Us)),this.server.assertCanSetRequestHandler(Vn(Bs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({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=Ds(r.inputSchema);return o?Sg(o,{strictUnions:!0,pipeStrategy:"input"}):D2})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ds(r.outputSchema);o&&(n.outputSchema=Sg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Bs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Z(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(G.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 Z(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(G.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 Z&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ds(e.inputSchema)??e.inputSchema,i=await yu(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=_u(a);throw new Z(G.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 Z(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ds(e.outputSchema),s=await yu(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=_u(i);throw new Z(G.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 Z(G.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vn(Lu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Lu,async e=>{switch(e.params.ref.type){case"ref/prompt":return C0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return O0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Wa;let s=Nn(n.argsSchema)?.[e.params.argument.name];if(!__(s))return Wa;let i=dT(s);if(!i)return Wa;let a=await i(e.params.argument.value,e.params.context);return yT(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 Wa;throw new Z(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Wa;let s=await o(e.params.argument.value,e.params.context);return yT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(zs)),this.server.assertCanSetRequestHandler(Vn(Fs)),this.server.assertCanSetRequestHandler(Vn(Du)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,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(Fs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Du,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(G.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 Z(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(Hs)),this.server.assertCanSetRequestHandler(Vn(Mu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?M2(r.argsSchema):void 0}))})),this.server.setRequestHandler(Mu,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ds(n.argsSchema),s=await yu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=_u(c);throw new Z(G.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:Mo(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=Mo(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 Ot?c._def?.innerType:c;return __(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){b_(e);let l={title:r,description:n,inputSchema:gT(o),outputSchema:gT(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"&&b_(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=Mo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Mo(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(x_(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!x_(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()}},D2={type:"object",properties:{}};Wa={completion:{values:[],hasMore:!1}}});function j2(t){return S0.parse(JSON.parse(t))}function vT(t){return JSON.stringify(t)+`
|
|
480
|
-
`}var
|
|
481
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
482
|
-
${t}`}function
|
|
482
|
+
deps: ${r}}`};var lU={keyword:"dependencies",type:"object",schemaType:"object",error:Ur.error,code(t){let[e,r]=dU(t);m$(t,e),f$(t,r)}};function dU({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 m$(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,qa.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,qa.checkReportMissingProp)(t,u)}):(r.if((0,Vy._)`${c} && (${(0,qa.checkMissingProp)(t,a,s)})`),(0,qa.reportMissingProp)(t,s),r.else())}}Ur.validatePropertyDeps=m$;function f$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,uU.alwaysValidSchema)(s,e[a])||(r.if((0,qa.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))}Ur.validateSchemaDeps=f$;Ur.default=lU});var y$=L(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var g$=oe(),pU=me(),mU={message:"property name must be valid",params:({params:t})=>(0,g$._)`{propertyName: ${t.propertyName}}`},fU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,pU.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,g$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Wy.default=fU});var Gy=L(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var wl=cr(),Sr=oe(),hU=un(),El=me(),gU={message:"must NOT have additional properties",params:({params:t})=>(0,Sr._)`{additionalProperty: ${t.additionalProperty}}`},yU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gU,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,El.alwaysValidSchema)(i,r))return;let u=(0,wl.allSchemaProperties)(n.properties),l=(0,wl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Sr._)`${s} === ${hU.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,El.schemaRefOrVal)(i,n.properties,"properties");y=(0,wl.isOwnProperty)(e,_,g)}else u.length?y=(0,Sr.or)(...u.map(_=>(0,Sr._)`${g} === ${_}`)):y=Sr.nil;return l.length&&(y=(0,Sr.or)(y,...l.map(_=>(0,Sr._)`${(0,wl.usePattern)(t,_)}.test(${g})`))),(0,Sr.not)(y)}function h(g){e.code((0,Sr._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,El.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sr.not)(y),()=>e.break()))}}function f(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:El.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};Ky.default=yU});var b$=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var _U=Oa(),_$=cr(),Jy=me(),x$=Gy(),xU={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&&x$.default.code(new _U.KeywordCxt(s,x$.default,"additionalProperties"));let i=(0,_$.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Jy.mergeEvaluated.props(e,(0,Jy.toHash)(i),s.props));let a=i.filter(d=>!(0,Jy.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,_$.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)}}};Xy.default=xU});var w$=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var v$=cr(),$l=oe(),S$=me(),k$=me(),bU={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,v$.allSchemaProperties)(r),c=a.filter(f=>(0,S$.alwaysValidSchema)(s,r[f]));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 $l.Name)&&(s.props=(0,k$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let f of a)u&&h(f),s.allErrors?m(f):(e.var(l,!0),m(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,S$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",n,g=>{e.if((0,$l._)`${(0,v$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:k$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,$l._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,$l.not)(l),()=>e.break())})})}}};Yy.default=bU});var E$=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var vU=me(),SU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,vU.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"}};Qy.default=SU});var $$=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var kU=cr(),wU={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kU.validateUnion,error:{message:"must match a schema in anyOf"}};e_.default=wU});var T$=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Tl=oe(),EU=me(),$U={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Tl._)`{passingSchemas: ${t.passing}}`},TU={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$U,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,EU.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Tl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Tl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Tl.Name)})})}}};t_.default=TU});var P$=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var PU=me(),RU={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,PU.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};r_.default=RU});var O$=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Pl=oe(),C$=me(),CU={message:({params:t})=>(0,Pl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Pl._)`{failingKeyword: ${t.ifClause}}`},OU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CU,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,C$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=R$(n,"then"),s=R$(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,Pl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Pl._)`${l}`):t.setParams({ifClause:l})}}}};function R$(t,e){let r=t.schema[e];return r!==void 0&&!(0,C$.alwaysValidSchema)(t,r)}n_.default=OU});var I$=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var IU=me(),AU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,IU.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};o_.default=AU});var A$=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var NU=Hy(),DU=u$(),MU=Uy(),jU=d$(),LU=p$(),zU=h$(),FU=y$(),HU=Gy(),UU=b$(),BU=w$(),ZU=E$(),qU=$$(),VU=T$(),WU=P$(),KU=O$(),GU=I$();function JU(t=!1){let e=[ZU.default,qU.default,VU.default,WU.default,KU.default,GU.default,FU.default,HU.default,zU.default,UU.default,BU.default];return t?e.push(DU.default,jU.default):e.push(NU.default,MU.default),e.push(LU.default),e}s_.default=JU});var N$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Ke=oe(),XU={message:({schemaCode:t})=>(0,Ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ke._)`{format: ${t}}`},YU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XU,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():h();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=r.const("fDef",(0,Ke._)`${m}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ke._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Ke._)`${f}.type || "string"`).assign(y,(0,Ke._)`${f}.validate`),()=>r.assign(g,(0,Ke._)`"string"`).assign(y,f)),t.fail$data((0,Ke.or)(_(),x()));function _(){return c.strictSchema===!1?Ke.nil:(0,Ke._)`${i} && !${y}`}function x(){let v=l.$async?(0,Ke._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ke._)`${y}(${n})`,E=(0,Ke._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,Ke._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[f,g,y]=x(m);f===e&&t.pass(v());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(E){let C=E instanceof RegExp?(0,Ke.regexpCode)(E):c.code.formats?(0,Ke._)`${c.code.formats}${(0,Ke.getProperty)(s)}`:void 0,b=r.scopeValue("formats",{key:s,ref:E,code:C});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ke._)`${b}.validate`]:["string",E,b]}function v(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ke._)`await ${y}(${n})`}return typeof g=="function"?(0,Ke._)`${y}(${n})`:(0,Ke._)`${y}.test(${n})`}}}};i_.default=YU});var D$=L(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});var QU=N$(),e2=[QU.default];a_.default=e2});var M$=L(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.contentVocabulary=ri.metadataVocabulary=void 0;ri.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ri.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var L$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var t2=qE(),r2=s$(),n2=A$(),o2=D$(),j$=M$(),s2=[t2.default,r2.default,(0,n2.default)(),o2.default,j$.metadataVocabulary,j$.contentVocabulary];c_.default=s2});var F$=L(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.DiscrError=void 0;var z$;(function(t){t.Tag="tag",t.Mapping="mapping"})(z$||(Rl.DiscrError=z$={}))});var U$=L(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});var ni=oe(),u_=F$(),H$=dl(),i2=Ia(),a2=me(),c2={message:({params:{discrError:t,tagName:e}})=>t===u_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ni._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},u2={keyword:"discriminator",type:"object",schemaType:"object",error:c2,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,ni._)`${r}${(0,ni.getProperty)(a)}`);e.if((0,ni._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:u_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=p();e.if(!1);for(let m in h)e.elseIf((0,ni._)`${u} === ${m}`),e.assign(c,d(h[m]));e.else(),t.error(!1,{discrError:u_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(f,ni.Name),m}function p(){var h;let m={},f=y(o),g=!0;for(let v=0;v<i.length;v++){let E=i[v];if(E?.$ref&&!(0,a2.schemaHasRulesButRef)(E,s.self.RULES)){let b=E.$ref;if(E=H$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,b),E instanceof H$.SchemaEnv&&(E=E.schema),E===void 0)throw new i2.default(s.opts.uriResolver,s.baseId,b)}let C=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(C,v)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:v}){return Array.isArray(v)&&v.includes(a)}function _(v,E){if(v.const)x(v.const,E);else if(v.enum)for(let C of v.enum)x(C,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(v,E){if(typeof v!="string"||v in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[v]=E}}}};l_.default=u2});var B$=L((qJ,l2)=>{l2.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 p_=L((Ne,d_)=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.MissingRefError=Ne.ValidationError=Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=Ne.Ajv=void 0;var d2=zE(),p2=L$(),m2=U$(),Z$=B$(),f2=["/properties"],Cl="http://json-schema.org/draft-07/schema",oi=class extends d2.default{_addVocabularies(){super._addVocabularies(),p2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(m2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Z$,f2):Z$;this.addMetaSchema(e,Cl,!1),this.refs["http://json-schema.org/schema"]=Cl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Cl)?Cl:void 0)}};Ne.Ajv=oi;d_.exports=Ne=oi;d_.exports.Ajv=oi;Object.defineProperty(Ne,"__esModule",{value:!0});Ne.default=oi;var h2=Oa();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return h2.KeywordCxt}});var si=oe();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var g2=ul();Object.defineProperty(Ne,"ValidationError",{enumerable:!0,get:function(){return g2.default}});var y2=Ia();Object.defineProperty(Ne,"MissingRefError",{enumerable:!0,get:function(){return y2.default}})});var Y$=L(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.formatNames=Zr.fastFormats=Zr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Zr.fullFormats={date:Br(K$,g_),time:Br(f_(!0),y_),"date-time":Br(q$(!0),J$),"iso-time":Br(f_(),G$),"iso-date-time":Br(q$(),X$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:k2,"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:C2,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:w2,int32:{type:"number",validate:T2},int64:{type:"number",validate:P2},float:{type:"number",validate:W$},double:{type:"number",validate:W$},password:!0,binary:!0};Zr.fastFormats={...Zr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,g_),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,y_),"date-time":Br(/^\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,J$),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,G$),"iso-date-time":Br(/^\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,X$),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};Zr.formatNames=Object.keys(Zr.fullFormats);function _2(t){return t%4===0&&(t%100!==0||t%400===0)}var x2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,b2=[0,31,28,31,30,31,30,31,31,30,31,30,31];function K$(t){let e=x2.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&&_2(r)?29:b2[n])}function g_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var m_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function f_(t){return function(r){let n=m_.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function y_(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 G$(t,e){if(!(t&&e))return;let r=m_.exec(t),n=m_.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 h_=/t|\s/i;function q$(t){let e=f_(t);return function(n){let o=n.split(h_);return o.length===2&&K$(o[0])&&e(o[1])}}function J$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function X$(t,e){if(!(t&&e))return;let[r,n]=t.split(h_),[o,s]=e.split(h_),i=g_(r,o);if(i!==void 0)return i||y_(n,s)}var v2=/\/|:/,S2=/^(?:[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 k2(t){return v2.test(t)&&S2.test(t)}var V$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function w2(t){return V$.lastIndex=0,V$.test(t)}var E2=-(2**31),$2=2**31-1;function T2(t){return Number.isInteger(t)&&t<=$2&&t>=E2}function P2(t){return Number.isInteger(t)}function W$(){return!0}var R2=/[^\\]\\Z/;function C2(t){if(R2.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Q$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var O2=p_(),kr=oe(),Vn=kr.operators,Ol={formatMaximum:{okStr:"<=",ok:Vn.LTE,fail:Vn.GT},formatMinimum:{okStr:">=",ok:Vn.GTE,fail:Vn.LT},formatExclusiveMaximum:{okStr:"<",ok:Vn.LT,fail:Vn.GTE},formatExclusiveMinimum:{okStr:">",ok:Vn.GT,fail:Vn.LTE}},I2={message:({keyword:t,schemaCode:e})=>(0,kr.str)`should be ${Ol[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kr._)`{comparison: ${Ol[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(Ol),type:"string",schemaType:"string",$data:!0,error:I2,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 O2.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,kr._)`${p}[${c.schemaCode}]`);t.fail$data((0,kr.or)((0,kr._)`typeof ${h} != "object"`,(0,kr._)`${h} instanceof RegExp`,(0,kr._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:h,code:i.code.formats?(0,kr._)`${i.code.formats}${(0,kr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,kr._)`${p}.compare(${r}, ${n}) ${Ol[o].fail} 0`}},dependencies:["format"]};var A2=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=A2});var nT=L((Va,rT)=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var ai=Y$(),N2=Q$(),__=oe(),eT=new __.Name("fullFormats"),D2=new __.Name("fastFormats"),x_=(t,e={keywords:!0})=>{if(Array.isArray(e))return tT(t,e,ai.fullFormats,eT),t;let[r,n]=e.mode==="fast"?[ai.fastFormats,D2]:[ai.fullFormats,eT],o=e.formats||ai.formatNames;return tT(t,o,r,n),e.keywords&&(0,N2.default)(t),t};x_.get=(t,e="full")=>{let n=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function tT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,__._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}rT.exports=Va=x_;Object.defineProperty(Va,"__esModule",{value:!0});Va.default=x_});function M2(){let t=new oT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sT.default)(t),t}var oT,sT,Il,iT=S(()=>{oT=xi(p_(),1),sT=xi(nT(),1);Il=class{constructor(e){this._ajv=e??M2()}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)}}}});var Al,aT=S(()=>{jo();Al=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ga,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},Zs,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 cT(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 uT(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 lT=S(()=>{});var Nl,dT=S(()=>{_w();jo();iT();oa();aT();lT();Nl=class extends Ju{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ha.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 Il,this.setRequestHandler(Nh,n=>this._oninitialize(n)),this.setNotificationHandler(Dh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Uh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ha.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Al(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yw(this._capabilities,e)}setRequestHandler(e,r){let o=Dn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(nr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}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=Nn(Bs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(G.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Nn(js,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new Z(G.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let h=Nn(Lu,p);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Z(G.InvalidParams,`Invalid tools/call result: ${m}`)}return h.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){uT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&cT(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:y0.includes(r)?r:Rh,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"},$u)}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},Bh,r):this.request({method:"sampling/createMessage",params:e},ga,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},Zs,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},Zs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(G.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},Zh,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"})}}});function b_(t){return!!t&&typeof t=="object"&&mT in t}function fT(t){return t[mT]?.complete}var mT,pT,hT=S(()=>{mT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(pT||(pT={}))});var gT=S(()=>{});function L2(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"),!j2.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 z2(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 v_(t){let e=L2(t);return z2(t,e.warnings),e.isValid}var j2,yT=S(()=>{j2=/^[A-Za-z0-9._-]{1,128}$/});var Dl,_T=S(()=>{Dl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Ml=S(()=>{Jc();Jc()});function vT(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function ST(t){return"_def"in t||"_zod"in t||vT(t)}function S_(t){return typeof t!="object"||t===null||ST(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vT)}function xT(t){if(t){if(S_(t))return Mo(t);if(!ST(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function H2(t){let e=Dn(t);return e?Object.entries(e).map(([r,n])=>{let o=Uk(n),s=Bk(n);return{name:r,description:o,required:!s}}):[]}function Wn(t){let r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function bT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var jl,F2,Wa,kT=S(()=>{dT();oa();Tg();jo();hT();gT();yT();_T();Ml();jl=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 Nl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Dl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Us)),this.server.assertCanSetRequestHandler(Wn(Bs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({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=Ds(r.inputSchema);return o?wg(o,{strictUnions:!0,pipeStrategy:"input"}):F2})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ds(r.outputSchema);o&&(n.outputSchema=wg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Bs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Z(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(G.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 Z(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(G.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 Z&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ds(e.inputSchema)??e.inputSchema,i=await _u(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=xu(a);throw new Z(G.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 Z(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ds(e.outputSchema),s=await _u(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=xu(i);throw new Z(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new Z(G.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Wn(zu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zu,async e=>{switch(e.params.ref.type){case"ref/prompt":return A0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return N0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Wa;let s=Dn(n.argsSchema)?.[e.params.argument.name];if(!b_(s))return Wa;let i=fT(s);if(!i)return Wa;let a=await i(e.params.argument.value,e.params.context);return bT(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 Wa;throw new Z(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Wa;let s=await o(e.params.argument.value,e.params.context);return bT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(zs)),this.server.assertCanSetRequestHandler(Wn(Fs)),this.server.assertCanSetRequestHandler(Wn(Mu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,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(Fs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Mu,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(G.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 Z(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Hs)),this.server.assertCanSetRequestHandler(Wn(ju)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?H2(r.argsSchema):void 0}))})),this.server.setRequestHandler(ju,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ds(n.argsSchema),s=await _u(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=xu(c);throw new Z(G.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:Mo(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=Mo(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 Ot?c._def?.innerType:c;return b_(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){v_(e);let l={title:r,description:n,inputSchema:xT(o),outputSchema:xT(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"&&v_(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=Mo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Mo(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(S_(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!S_(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()}},F2={type:"object",properties:{}};Wa={completion:{values:[],hasMore:!1}}});function U2(t){return E0.parse(JSON.parse(t))}function wT(t){return JSON.stringify(t)+`
|
|
483
|
+
`}var Ll,ET=S(()=>{jo();Ll=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
484
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),U2(r)}clear(){this._buffer=void 0}}});import $T from"node:process";var zl,TT=S(()=>{ET();zl=class{constructor(e=$T.stdin,r=$T.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ll,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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=wT(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var jT={};we(jT,{PolyglotExecutor:()=>ci,buildScriptFilename:()=>NT,buildShellScriptContent:()=>MT,buildSpawnOptions:()=>DT});import{spawn as PT,execSync as B2,execFileSync as IT}from"node:child_process";import{mkdtempSync as Z2,writeFileSync as RT,rmSync as CT,existsSync as OT}from"node:fs";import{join as Fl,resolve as AT}from"node:path";import{tmpdir as q2}from"node:os";function NT(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";if(n.includes("powershell")||n.includes("pwsh"))return"script.ps1";let o=n.split(/[\\/]/).pop()??n;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${V2[t]}`}function DT(t){return{windowsHide:t==="win32"}}function W2(t){return`'${t.replace(/'/g,"'\\''")}'`}function MT(t,e,r){return r==="win32"||!e?t:`export PATH=${W2(e)}
|
|
485
|
+
${t}`}function k_(t){if(dr&&t.pid)try{B2(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var dr,V2,K2,ci,w_=S(()=>{"use strict";Xo();dr=process.platform==="win32",V2={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};K2=(()=>{if(dr)return process.env.TEMP??process.env.TMP??q2();try{let t=IT(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:AT(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();ci=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Qn()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(dr?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1,cwd:i}=e,a=Z2(Fl(K2,".ctx-mode-"));try{let c=this.#a(a,n,r),u=Ld(this.#n,r,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=r==="shell"?i??this.#o:a,d=await this.#i(u,l,a,o,s);if(!d.backgrounded)try{CT(a,{recursive:!0,force:!0})}catch{}return d}catch(c){try{CT(a,{recursive:!0,force:!0})}catch{}throw c}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=AT(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
|
|
483
486
|
|
|
484
487
|
import "fmt"
|
|
485
488
|
|
|
@@ -487,12 +490,12 @@ func main() {
|
|
|
487
490
|
${r}
|
|
488
491
|
}
|
|
489
492
|
`),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
|
|
490
|
-
${r}`),n==="elixir"&&
|
|
493
|
+
${r}`),n==="elixir"&&OT(Fl(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Fl(this.#o,"_build/dev/lib"))}, "*/ebin"))
|
|
491
494
|
|> Enum.each(&Code.prepend_path/1)
|
|
492
495
|
|
|
493
|
-
${r}`);let o=
|
|
494
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=dr&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;dr&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=dr?e.slice(1).map(
|
|
495
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:v,stderr:E,exitCode:
|
|
496
|
+
${r}`);let o=Fl(e,NT(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?RT(o,MT(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):RT(o,r,"utf-8"),o}async#c(e,r,n){let o=dr?".exe":"",s=e.replace(/\.rs$/,"")+o;try{IT("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
497
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=dr&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;dr&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=dr?e.slice(1).map(x=>x.replace(/\\/g,"/")):e.slice(1);let l={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!dr,...DT(process.platform)},d;if(a){let x=[c,...u].map(v=>/\s/.test(v)?JSON.stringify(v):v).join(" ");d=PT(x,[],{...l,shell:!0})}else d=PT(c,u,{...l,shell:!1});let p=!1,h=!1,m=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){h=!0,d.pid&&this.#s.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let x=Buffer.concat(f).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");i({stdout:x,stderr:v,exitCode:0,timedOut:!0,backgrounded:!0})}else k_(d)},o),f=[],g=[],y=0,_=!1;d.stdout.on("data",x=>{y+=x.length,y<=this.#e?f.push(x):_||(_=!0,k_(d))}),d.stderr.on("data",x=>{y+=x.length,y<=this.#e?g.push(x):_||(_=!0,k_(d))}),d.on("close",x=>{if(clearTimeout(m),h)return;let v=Buffer.concat(f).toString("utf-8"),E=Buffer.concat(g).toString("utf-8");_&&(E+=`
|
|
498
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:v,stderr:E,exitCode:p?1:x??1,timedOut:p})}),d.on("error",x=>{clearTimeout(m),!h&&i({stdout:"",stderr:x.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",dr&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=dr?"":"/usr/local/bin:/usr/bin:/bin"),dr){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=dr?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(OT(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
|
|
496
499
|
const file_path = FILE_CONTENT_PATH;
|
|
497
500
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
498
501
|
${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
|
|
@@ -550,89 +553,89 @@ file_content = File.read!(file_content_path)
|
|
|
550
553
|
${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
|
|
551
554
|
var file_path = FILE_CONTENT_PATH;
|
|
552
555
|
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
553
|
-
${n}`}}}});import{cpus as
|
|
556
|
+
${n}`}}}});import{cpus as G2}from"node:os";async function E_(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,G2().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let h=l++;if(h>=t.length)return;try{let m=await t[h].run();u[h]={status:"fulfilled",value:m}}catch(m){u[h]={status:"rejected",reason:m}}o?.(h,u[h])}}let p=[];for(let h=0;h<a;h++)p.push(d());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var LT=S(()=>{"use strict"});function $_(t,e){return t===void 0?e:`${t}::${e}`}var zT=S(()=>{"use strict"});function T_(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
|
|
554
557
|
|
|
555
558
|
stdout:
|
|
556
559
|
${n}
|
|
557
560
|
|
|
558
561
|
stderr:
|
|
559
|
-
${o}`}}var
|
|
560
|
-
`)}for(let f of
|
|
562
|
+
${o}`}}var FT=S(()=>{"use strict"});import{execFileSync as J2}from"node:child_process";function X2(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=J2("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function Y2(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??X2,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}function eB(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function HT(t){let e=t.checkIntervalMs??eB(),r=t.isParentAlive??Q2,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var Q2,UT=S(()=>{"use strict";Q2=Y2()});function BT(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}var ZT=S(()=>{"use strict"});import{existsSync as P_,unlinkSync as tB}from"node:fs";import{join as Ka}from"node:path";function R_(t,e){try{return tB(t),e.push(t),!0}catch{return!1}}function Hl(t,e){let r=!1;for(let n of rB)R_(`${t}${n}`,e)&&n===""&&(r=!0);return r}function qT(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let x=Ci(e),v=nt(e),E=Ar(e),C=v===E?[v]:[v,E],b=!1;for(let N of C){let R=Ka(r,`${N}${x}.db`);if(!P_(R))continue;let O=null;try{O=new Gt({dbPath:R});let F=O.getEvents(a).length;O.deleteSession(a),F>0&&(b=!0)}catch{}finally{try{O?.close()}catch{}}}b&&u.push(`session rows for ${a}`);let k=[];if(n&&P_(n)&&k.push(n),o){let N=nt(e),R=Ar(e),O=N===R?[N]:[N,R];for(let F of O){let K=Ka(o,`${F}.db`);P_(K)&&!k.includes(K)&&k.push(K)}}let P=!1;for(let N of k)try{let R=rt(),O=new R(N,{timeout:3e4});try{let F=O.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;O.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),O.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(P=!0)}finally{try{O.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(n&&Hl(n,l)&&(p=!0),o){let x=nt(e),v=Ar(e),E=x===v?[x]:[x,v];for(let C of E){let b=Ka(o,`${C}.db`);Hl(b,l)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let x=Ka(s,`${i}.db`);Hl(x,l)}let h=Ci(e),m=nt(e),f=Ar(e),g=m===f?[m]:[m,f],y=!1,_=!1;for(let x of g){let v=Ka(r,`${x}${h}`);Hl(`${v}.db`,l)&&(y=!0),R_(`${v}-events.md`,l)&&(_=!0),R_(`${v}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var rB,VT=S(()=>{"use strict";bn();Jt();rB=["","-wal","-shm"]});import{existsSync as nB}from"node:fs";function C_(t,e){try{if(!nB(t))return;let r=new Gt({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function WT(t){C_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function KT(t){C_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function GT(t){C_(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var JT=S(()=>{"use strict";Jt()});import{existsSync as XT}from"node:fs";function YT(t,e,r){try{if(!XT(t))return;let n=new Gt({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function QT(t){try{if(!XT(t))return null;let e=new Gt({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var eP=S(()=>{"use strict";Jt()});import{existsSync as O_,readFileSync as oB,readdirSync as sB,statSync as iB}from"node:fs";import{join as ui,isAbsolute as aB}from"node:path";function nP(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?rP(r,a):null)??n??qe(),l=o?.getMemoryDir(r),d=ui(u,"memory"),p=r?ui(d,nt(r)):d,h=l?rP(r,l):p,m=[];if(r)for(let f of i){let g=ui(r,f);O_(g)&&m.push({path:g,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let g=ui(u,f);O_(g)&&m.push({path:g,label:`user/${f}`})}if(h&&O_(h))try{let f=sB(h).filter(g=>g.endsWith(".md"));for(let g of f)m.push({path:ui(h,g),label:`memory/${g}`})}catch(f){tP&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
|
|
563
|
+
`)}for(let f of m){if(s.length>=e)break;try{let g;try{if(g=iB(f.path),g.size>1e6)continue}catch{continue}let y=oB(f.path,"utf-8"),_=y.toLowerCase();for(let x of t){if(s.length>=e)break;let E=x.toLowerCase().split(/\s+/).filter(b=>b.length>=3);if(E.some(b=>{try{return new RegExp(`\\b${b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(b)}})){let b=E.reduce((F,K)=>{let ge=_.indexOf(K);return ge>=0&&(F<0||ge<F)?ge:F},-1),k=Math.max(0,b-200),P=Math.min(y.length,b+500),N=y.lastIndexOf(`
|
|
561
564
|
|
|
562
565
|
`,k),R=y.indexOf(`
|
|
563
566
|
|
|
564
|
-
`,P);N>=0&&(k=N+2),R>=0&&(P=R);let O=y.slice(k,P).trim();s.push({title:`[auto-memory] ${f.label}`,content:O,source:f.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){
|
|
565
|
-
`)}}return s.slice(0,e)}function
|
|
566
|
-
`)}try{let f=n.searchWithFallback(e,r,s,i,"like",
|
|
567
|
-
`)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);
|
|
568
|
-
`)}try{let f=
|
|
569
|
-
`)}}for(let f of
|
|
570
|
-
`).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Je.closeSync(n)}}catch{}}function
|
|
571
|
-
`).slice(0,10))if(h.trim())try{let
|
|
572
|
-
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function
|
|
573
|
-
FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Ja(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Bt(
|
|
567
|
+
`,P);N>=0&&(k=N+2),R>=0&&(P=R);let O=y.slice(k,P).trim();s.push({title:`[auto-memory] ${f.label}`,content:O,source:f.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){tP&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
568
|
+
`)}}return s.slice(0,e)}function rP(t,e){return e?aB(e)||!t?e:ui(t,e):t??""}var tP,oP=S(()=>{"use strict";wn();Jt();tP=process.env.DEBUG?.includes("context-mode")});function sP(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],h=new Date().toISOString(),m;if(typeof d=="string"&&a)try{m=new Set(a.getSessionIdsForProject(d))}catch(f){Ul&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${f}
|
|
569
|
+
`)}try{let f=n.searchWithFallback(e,r,s,i,"like",m);p.push(...f.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||h,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(f){Ul&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
|
|
570
|
+
`)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);p.push(...f.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(f){Ul&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
|
|
571
|
+
`)}try{let f=nP([e],r,c,u,l);p.push(...f)}catch(f){Ul&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
|
|
572
|
+
`)}}for(let f of p)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((f,g)=>(f.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,r)}var Ul,iP=S(()=>{"use strict";oP();Ul=process.env.DEBUG?.includes("context-mode")});function cB(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function aP(t){let e=t?{project:M.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return M.object({queries:M.preprocess(cB,M.array(M.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:M.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:M.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:M.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:M.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory."),...e})}function cP(t,e,r){if(e)return t===void 0?r():t==="global"?null:t}var I_,uP=S(()=>{"use strict";Ml();I_=!!process.env.CONTEXT_MODE_PROJECT_DIR});import*as Je from"node:fs";import*as lP from"node:os";import*as li from"node:path";function Bl(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function dB(t){if(!Je.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Je.readdirSync(t.projectsRoot)){let o=li.join(t.projectsRoot,n),s;try{s=Je.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Je.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=li.join(o,a);try{let u=Je.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=Je.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Je.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
|
|
573
|
+
`).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Je.closeSync(n)}}catch{}}function pB(t){let e=t?.codexHome??process.env.CODEX_HOME??li.join(lP.homedir(),".codex"),r=li.join(e,"sessions");if(!Je.existsSync(r))return null;let n=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Je.readdirSync(u)}catch{return}d.sort().reverse();for(let p of d){if(s>=o)return;s++;let h=li.join(u,p),m;try{m=Je.statSync(h)}catch{continue}if(m.isDirectory()){l<n&&c(h,l+1);continue}if(!m.isFile()||!p.endsWith(".jsonl"))continue;let f=m.mtimeMs;f>a&&(a=f,i=h)}};try{c(r,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Je.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Je.readSync(u,l,0,l.length,0),p=l.subarray(0,d).toString("utf-8");for(let h of p.split(`
|
|
574
|
+
`).slice(0,10))if(h.trim())try{let m=JSON.parse(h),f=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof f!="string"||f.length===0)continue;return Bl(f)?null:f}catch{return null}}finally{Je.closeSync(u)}}catch{return null}return null}function dP(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...Bp(a),...uB]:lB;for(let l of u){let d=e[l];if(d&&!Bl(d))return d}if(o){let l=dB({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Bl(l))return l}if(a==="codex"){let l=pB({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return n&&!Bl(n)?n:r}var uB,lB,pP=S(()=>{"use strict";Tn();uB=["CONTEXT_MODE_PROJECT_DIR"],lB=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"]});import{execFileSync as mB}from"node:child_process";import{existsSync as pn,readdirSync as di,statSync as fB}from"node:fs";import{homedir as Kl}from"node:os";import{join as Bt,sep as hB}from"node:path";function bP(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function yB(t){let e=t?.home??Kl();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Bt(e,...o,"context-mode");return{name:n,sessionsDir:Bt(s,"sessions"),contentDir:Bt(s,"content")}})}function _B(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Ga(t){let e=qe(),r=t?.sessionsDir??Bt(e,"context-mode","sessions"),n=t?.memoryRoot??Bt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(pn(r)){let h=[];try{h=di(r).filter(m=>m.endsWith(".db"))}catch{}if(h.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():rt()}catch{}if(m)for(let f of h){let g=Bt(r,f);try{let y=new m(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let v=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let E of v)E.category&&(u[E.category]=(u[E.category]??0)+(E.cnt??0))}catch{}try{let v=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();v?.bytes&&(i+=v.bytes)}catch{}try{let v=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(v?.t){let E=v.t.endsWith("Z")?v.t:v.t+"Z",C=Date.parse(E);Number.isFinite(C)&&C<a&&(a=C)}}catch{}try{let v=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let E of v)E.p&&c.add(E.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,p={};if(pn(n)){let h=[];try{h=di(n).filter(m=>{try{return fB(Bt(n,m)).isDirectory()}catch{return!1}})}catch{}for(let m of h){let f=Bt(n,m,"memory");if(!pn(f))continue;let g=[];try{g=di(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=_B(y);p[_]=(p[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function vP(t){let e=t.sessionsDir??Bt(Kl(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!pn(e))return n;let o=[];try{o=di(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():rt()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,h=0,m=new Map,f=x=>Math.floor(x/864e5)*864e5;for(let x of o){let v=Bt(e,x),E=!1;try{let C=new s(v,{readonly:!0});try{let b=C.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let P of b)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,E=!0);let k=C.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(k?.mn){let P=Date.parse(k.mn+(k.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P<d&&(d=P)}if(k?.mx){let P=Date.parse(k.mx+(k.mx.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P>p&&(p=P)}try{let P=C.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let N of P){if(!N.sec)continue;let R=parseInt(N.sec,10)*1e3;if(!Number.isFinite(R))continue;let O=f(R),F=m.get(O)??{count:0,rescueBytes:0};F.count+=N.cnt??0,m.set(O,F)}}catch{}try{let P=C.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let N=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(N)&&N>h&&(h=N),Number.isFinite(N)&&(P?.bytes??0)>0){let R=f(N),O=m.get(R)??{count:0,rescueBytes:0};O.rescueBytes=Math.max(O.rescueBytes,P.bytes),m.set(R,O)}}}catch{}}finally{C.close()}}catch{}E&&c++}let g=d<p?(p-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,v])=>({category:x,count:v,label:ql[x]||x})).sort((x,v)=>v.count-x.count),_=[...m.entries()].sort((x,v)=>x[0]-v[0]).map(([x,v])=>({ms:x,count:v.count,...v.rescueBytes>0?{rescueBytes:v.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:h>0?h:void 0,byDay:_}}function xB(t,e,r){if(!t||!e||!pn(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():rt()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
575
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function SP(t,e){if(!t||!pn(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():rt()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
576
|
+
FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Ja(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Bt(Kl(),".claude","context-mode","sessions");if(!pn(r))return e;let n=[];try{n=di(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():rt()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of n){let p=Bt(r,d);Vd(p,o);try{let h=new o(p,{readonly:!0});try{if(t.sessionId){let m=h.prepare(`SELECT
|
|
574
577
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
575
578
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
576
579
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
577
|
-
FROM session_events WHERE session_id = ?`).get(t.sessionId);
|
|
580
|
+
FROM session_events WHERE session_id = ?`).get(t.sessionId);m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);f?.bytes&&(c+=Number(f.bytes))}catch{}}else if(t.projectDir){let m=h.prepare(`SELECT
|
|
578
581
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
579
582
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
580
583
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
581
584
|
FROM session_events
|
|
582
585
|
WHERE session_id IN (
|
|
583
586
|
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
584
|
-
)`).get(t.projectDir);
|
|
587
|
+
)`).get(t.projectDir);m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
|
|
585
588
|
FROM session_resume
|
|
586
589
|
WHERE session_id IN (
|
|
587
590
|
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
588
|
-
)`).get(t.projectDir);f?.bytes&&(c+=Number(f.bytes))}catch{}}else{let
|
|
591
|
+
)`).get(t.projectDir);f?.bytes&&(c+=Number(f.bytes))}catch{}}else{let m=h.prepare(`SELECT
|
|
589
592
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
590
593
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
591
594
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
592
|
-
FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=fB(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function gB(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!dn(t.sessionsDir))return n;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Bt(t.sessionsDir,l);try{let m=new s(d,{readonly:!0});try{let h=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let f=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(p?.mx){let f=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of p)f.p&&i.add(f.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of p)f.s&&a.add(f.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Kl(t){let e=pB({home:t?.home}),r=t?.loadDatabase??rt,n={...hB,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!dn(c.sessionsDir))continue;let u=gB(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function ql(t){return yB[t]??t}function dt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function _B(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Bl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function bB(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Bl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=cB("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Bl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Bl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Bl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function lP(t){let e=Wl();return e?t===e?"~":t.startsWith(e+lB)?"~"+t.slice(e.length):t:t}function xB(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*Xa(),o=(y,_=2)=>y.toFixed(_),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),h=(e*.8/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&f?g.push(` $${o(n)} of ${f} tokens your team didn't burn.`):p?g.push(` $${o(n)} of tokens your team didn't burn.`):g.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),g.push(` context-mode kept ${dt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function vB(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],m=e.events*hP,h=Math.round((e.snapshotBytes??0)/4),p=m+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(p,f),y=(r?.totalEvents??0)*hP,_=Math.round((r?.rescueBytes??0)/4),b=y+_,v=o?.lifetime?.totalSavedTokens??0,E=Math.max(b,v),C=o?.lifetime?.bytesReturned??0,x=o?.lifetime?.bytesAvoided??0,k=C+x>0?Math.max(1,Math.floor(C/4)):Math.max(1,Math.round(E*.02)),P=n?.totalBytes&&n.totalBytes>0?n.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,O=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=O>0?Math.max(1,Math.round((c-O)/864e5)):0,K=n?.totalSessions??r?.totalSessions??1,ge=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,We;if(n&&ge>=2)We=`across ${ge} AI tools`;else if(n&&ge===1){let Ze=n.perAdapter.find(pr=>pr.isReal);We=`in ${Ze?ql(Ze.name):"Claude Code"}`}else We="in Claude Code";F>0?d.push(` Across ${F} days you ran ${wr(K)} conversations ${We}.`):d.push(` You ran ${wr(K)} conversations ${We}.`);let _t=F>0?P/F:0;d.push(` context-mode kept ${dt(P)} out of your context window \u2014 about ${dt(_t)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Pr=e.firstEventMs&&e.firstEventMs>0?dP(e.firstEventMs,i,a):"";if(Pr?d.push(` This conversation started ${Pr} in ${lP(s)}.`):d.push(` This conversation lives in ${lP(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?dP(e.lastRescueMs,i,a):"",pr=Math.round(e.snapshotBytes/1024);Ze?d.push(` On ${Ze}, /compact fired \u2014 ${pr} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pr} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let ic=o?.conversation,ac=ic?.bytesAvoided??0,hd=ic?.bytesReturned??0;if(ac+hd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ze=ac+hd,pr=Math.max(1,hd),mr=Math.max(1,Math.floor(Ze/4)),Gr=Math.max(1,Math.floor(pr/4)),gd=Wn(mr,mr,32),NR=Wn(Gr,mr,32),DR=(1-Gr/mr)*100,MR=Math.max(1,Math.round(mr/Gr));d.push(` Without context-mode ${dt(Ze).padStart(8)} ${gd} ${wr(mr).padStart(7)} tokens`),d.push(` With context-mode ${dt(pr).padStart(8)} ${NR} ${wr(Gr).padStart(7)} tokens`),d.push(` ${DR.toFixed(0)}% kept out of context \xB7 your AI ran ${MR}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${dt(N)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),d.push(""),d.push(...kB(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let CR=e.byCategory.reduce((Ze,pr)=>Ze+pr.count,0).toLocaleString(i);d.push(` ${CR} things \u2014 files, errors, decisions, agent runs:`),d.push("");let OR=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)d.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${Wn(Ze.count,OR,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let nb=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",ob=O>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(O)):"",sb=r?.distinctProjects??0,IR=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${dt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${nb?` \xB7 started ${nb}`:""}.`),d.push(` All your work: ${dt(P)} kept out \xB7 ${IR.toLocaleString(i)} captures across ${sb} project${sb===1?"":"s"}${ob?` \xB7 since ${ob}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...xB(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((mr,Gr)=>Gr[1]-mr[1]),pr=Ze.length>0?Ze[0][1]:1;for(let[mr,Gr]of Ze){let gd=xP[mr]??mr;d.push(` ${gd.padEnd(26)} ${String(Gr).padStart(2)} ${Wn(Gr,pr,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let AR=u?`v${u}`:"context-mode";return d.push(` ${AR}`),u&&l&&l!=="unknown"&&yP(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),SB(d)}function SB(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function kB(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,h)=>m.ms-h.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let h=Math.round((m.ms-o.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[h]=p}let l=m=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${p} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let m of n){let h=l(m.ms).padEnd(7),p=`${m.count} captures`,f=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${p}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function dP(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(m=>m.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function wr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Xa(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 15/1e6}function Vl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Xa()).toFixed(2)}`}function Wn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function pP(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${wr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${wr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${wr(f)} sessions`,y=a*256+r;o.push(` ${wr(a)} events \xB7 ${g} \xB7 ~${Vl(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:Zl[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let m=d.slice(0,n),h=m.length>0?m[0].count:1;for(let f of m)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Wn(f.count,h,30)}`);let p=Math.max(0,d.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function mP(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=xP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Wn(s,n,20)}`)}return e}function fP(t,e){let r=[],n=Vl(t),o=(e?.totalEvents??0)*256+t,s=Vl(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function gP(t){if(!t)return[];let e=[],r=[];for(let o of t.perAdapter)(o.isReal?e:r).push(o);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?wr(u.eventCount):"\u2014",m=dt(u.dataBytes),h=dt(l);n.push(` ${ql(u.name).padEnd(o)}${d.padStart(s)}${m.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>ql(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Gl(t,e,r,n){let o=[],s=_B(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(C=>C.isReal).length??0;if(l&&d>0){let C=l.totalSessions||i?.totalSessions||0,x=i?.firstEventMs??0,k=x>0?Math.max(1,Math.round((Date.now()-x)/864e5)):0,P=k>0?`Across ${k} day${k===1?"":"s"} `:"",N=C>0?`you ran ${wr(C)} conversation${C===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let O=l.perAdapter.find(F=>F.isReal);R=`in ${O?ql(O.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let C=bB(),x=n?.cwd??process.cwd(),k=n?.now??Date.now(),P=n?.locale??C.locale,N=n?.tz??C.tz;return o.push(...vB({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:x,locale:P,tz:N,now:k,version:e,latestVersion:r})),o.join(`
|
|
593
|
-
`)}let
|
|
594
|
-
`)}o.push(`${wr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${
|
|
595
|
-
`)}var
|
|
595
|
+
FROM session_events`).get();m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=xB(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function vB(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!pn(t.sessionsDir))return n;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Bt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let h=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(n.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let f=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(m?.mx){let f=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of m)f.p&&i.add(f.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of m)f.s&&a.add(f.s)}catch{}}finally{p.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Gl(t){let e=yB({home:t?.home}),r=t?.loadDatabase??rt,n={...bB,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!pn(c.sessionsDir))continue;let u=vB(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function Vl(t){return SB[t]??t}function dt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function kB(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Zl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function wB(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Zl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=mB("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Zl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Zl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Zl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function mP(t){let e=Kl();return e?t===e?"~":t.startsWith(e+hB)?"~"+t.slice(e.length):t:t}function EB(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*Xa(),o=(y,_=2)=>y.toFixed(_),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),h=(e*.8/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&f?g.push(` $${o(n)} of ${f} tokens your team didn't burn.`):m?g.push(` $${o(n)} of tokens your team didn't burn.`):g.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),g.push(` context-mode kept ${dt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function $B(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*_P,h=Math.round((e.snapshotBytes??0)/4),m=p+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(m,f),y=(r?.totalEvents??0)*_P,_=Math.round((r?.rescueBytes??0)/4),x=y+_,v=o?.lifetime?.totalSavedTokens??0,E=Math.max(x,v),C=o?.lifetime?.bytesReturned??0,b=o?.lifetime?.bytesAvoided??0,k=C+b>0?Math.max(1,Math.floor(C/4)):Math.max(1,Math.round(E*.02)),P=n?.totalBytes&&n.totalBytes>0?n.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,O=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=O>0?Math.max(1,Math.round((c-O)/864e5)):0,K=n?.totalSessions??r?.totalSessions??1,ge=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,We;if(n&&ge>=2)We=`across ${ge} AI tools`;else if(n&&ge===1){let Ze=n.perAdapter.find(pr=>pr.isReal);We=`in ${Ze?Vl(Ze.name):"Claude Code"}`}else We="in Claude Code";F>0?d.push(` Across ${F} days you ran ${wr(K)} conversations ${We}.`):d.push(` You ran ${wr(K)} conversations ${We}.`);let _t=F>0?P/F:0;d.push(` context-mode kept ${dt(P)} out of your context window \u2014 about ${dt(_t)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Pr=e.firstEventMs&&e.firstEventMs>0?fP(e.firstEventMs,i,a):"";if(Pr?d.push(` This conversation started ${Pr} in ${mP(s)}.`):d.push(` This conversation lives in ${mP(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?fP(e.lastRescueMs,i,a):"",pr=Math.round(e.snapshotBytes/1024);Ze?d.push(` On ${Ze}, /compact fired \u2014 ${pr} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pr} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let ic=o?.conversation,ac=ic?.bytesAvoided??0,gd=ic?.bytesReturned??0;if(ac+gd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ze=ac+gd,pr=Math.max(1,gd),mr=Math.max(1,Math.floor(Ze/4)),Gr=Math.max(1,Math.floor(pr/4)),yd=Kn(mr,mr,32),jR=Kn(Gr,mr,32),LR=(1-Gr/mr)*100,zR=Math.max(1,Math.round(mr/Gr));d.push(` Without context-mode ${dt(Ze).padStart(8)} ${yd} ${wr(mr).padStart(7)} tokens`),d.push(` With context-mode ${dt(pr).padStart(8)} ${jR} ${wr(Gr).padStart(7)} tokens`),d.push(` ${LR.toFixed(0)}% kept out of context \xB7 your AI ran ${zR}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${dt(N)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),d.push(""),d.push(...PB(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let AR=e.byCategory.reduce((Ze,pr)=>Ze+pr.count,0).toLocaleString(i);d.push(` ${AR} things \u2014 files, errors, decisions, agent runs:`),d.push("");let NR=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)d.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${Kn(Ze.count,NR,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let sx=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",ix=O>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(O)):"",ax=r?.distinctProjects??0,DR=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${dt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${sx?` \xB7 started ${sx}`:""}.`),d.push(` All your work: ${dt(P)} kept out \xB7 ${DR.toLocaleString(i)} captures across ${ax} project${ax===1?"":"s"}${ix?` \xB7 since ${ix}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...EB(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((mr,Gr)=>Gr[1]-mr[1]),pr=Ze.length>0?Ze[0][1]:1;for(let[mr,Gr]of Ze){let yd=kP[mr]??mr;d.push(` ${yd.padEnd(26)} ${String(Gr).padStart(2)} ${Kn(Gr,pr,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let MR=u?`v${u}`:"context-mode";return d.push(` ${MR}`),u&&l&&l!=="unknown"&&bP(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),TB(d)}function TB(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function PB(t,e,r){if(t.length===0)return[];let n=[...t].sort((p,h)=>p.ms-h.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let p of n)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of n){let h=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[h]=m}let l=p=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${m} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of n){let h=l(p.ms).padEnd(7),m=`${p.count} captures`,f=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${m}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function fP(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(p=>p.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function wr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Xa(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 15/1e6}function Wl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Xa()).toFixed(2)}`}function Kn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function hP(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${wr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${wr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${wr(f)} sessions`,y=a*256+r;o.push(` ${wr(a)} events \xB7 ${g} \xB7 ~${Wl(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:ql[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let p=d.slice(0,n),h=p.length>0?p[0].count:1;for(let f of p)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Kn(f.count,h,30)}`);let m=Math.max(0,d.length-n);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function gP(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=kP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Kn(s,n,20)}`)}return e}function yP(t,e){let r=[],n=Wl(t),o=(e?.totalEvents??0)*256+t,s=Wl(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function xP(t){if(!t)return[];let e=[],r=[];for(let o of t.perAdapter)(o.isReal?e:r).push(o);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?wr(u.eventCount):"\u2014",p=dt(u.dataBytes),h=dt(l);n.push(` ${Vl(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>Vl(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Jl(t,e,r,n){let o=[],s=kB(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(C=>C.isReal).length??0;if(l&&d>0){let C=l.totalSessions||i?.totalSessions||0,b=i?.firstEventMs??0,k=b>0?Math.max(1,Math.round((Date.now()-b)/864e5)):0,P=k>0?`Across ${k} day${k===1?"":"s"} `:"",N=C>0?`you ran ${wr(C)} conversation${C===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let O=l.perAdapter.find(F=>F.isReal);R=`in ${O?Vl(O.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let C=wB(),b=n?.cwd??process.cwd(),k=n?.now??Date.now(),P=n?.locale??C.locale,N=n?.tz??C.tz;return o.push(...$B({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:b,locale:P,tz:N,now:k,version:e,latestVersion:r})),o.join(`
|
|
596
|
+
`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,m=t.savings.total_calls,f=p+h,g=f>0?p/f*100:0,y=Math.round(p/4),_=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${dt(h)} entered context | 0 tokens saved`),o.push(...hP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...xP(l)),o.push(...gP(i)),o.push(...yP(0,i)),o.push("");let C=e?`v${e}`:"context-mode";return o.push(C),e&&r&&r!=="unknown"&&bP(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
|
|
597
|
+
`)}o.push(`${wr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Wl(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Kn(f,f)}| ${dt(f)}`),o.push(`With context-mode |${Kn(h,f)}| ${dt(h)}`),o.push(""),_>=2?o.push(`${dt(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${dt(p)} kept out of your conversation. Never entered context.`),o.push("");let x=[`${m} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${dt(t.cache.bytes_saved)})`),o.push(x.join(" \xB7 "));let v=t.savings.by_tool.filter(C=>C.calls>0);if(v.length>=2){o.push("");let C=v.map(b=>{let k=b.context_kb*1024,P=g<100?k/(1-g/100):k,N=Math.max(0,P-k);return{...b,returnedBytes:k,estimatedSaved:N}}).sort((b,k)=>k.estimatedSaved-b.estimatedSaved);for(let b of C){let k=b.tool.length>22?b.tool.slice(0,19)+"...":b.tool;o.push(` ${k.padEnd(22)} ${String(b.calls).padStart(4)} calls ${dt(b.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let C=a.filter(b=>b.median_concurrency!=null&&(b.max_concurrency??1)>1);if(C.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let b of C){let k=b.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${k.padEnd(22)} ${b.calls} batches \xB7 ${b.median_concurrency} typical, ${b.max_concurrency} peak`)}}}o.push(...hP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...xP(l)),o.push(...gP(i)),o.push(...yP(y,i)),o.push("");let E=e?`v${e}`:"context-mode";return o.push(E),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
|
|
598
|
+
`)}var ql,gB,pi,bB,kP,SB,fX,_P,wP=S(()=>{"use strict";bn();Jt();wn();ql={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},gB={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},pi=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((O,F)=>O+F,0),s=Object.values(e.calls).reduce((O,F)=>O+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(O=>({tool:O,calls:e.calls[O]||0,context_kb:Math.round((e.bytesReturned[O]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[O]||0)/4)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),m,f=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||f>0){let O=a+e.cacheBytesSaved,F=O/Math.max(o,1),K=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+f,We=ge>0?e.cacheHits/ge:0;m={hits:e.cacheHits,misses:f,hit_rate:We,bytes_saved:e.cacheBytesSaved,ttl_hours_left:K,total_with_cache:O,total_savings_ratio:F}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,v=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),E=v?!v.consumed:!1,C=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),b=new Map;for(let O of C){b.has(O.category)||b.set(O.category,new Set);let F=b.get(O.category);if(F.size<5){let K=O.data;O.category==="file"?K=O.data.split("/").pop()||O.data:(O.category==="prompt"||O.category==="user-prompt")&&(K=K.length>50?K.slice(0,47)+"...":K),K.length>40&&(K=K.slice(0,37)+"..."),F.add(K)}}let k=y.map(O=>({category:O.category,count:O.cnt,label:ql[O.category]||O.category,preview:b.get(O.category)?Array.from(b.get(O.category)).join(", "):"",why:gB[O.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),R=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(O=>O.cnt>0).map(O=>({category:O.category,count:O.cnt,label:ql[O.category]||O.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:m,session:{id:n,uptime_min:h},continuity:{total_events:g,by_category:k,compact_count:x,resume_ready:E},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};bB={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};kP={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},SB={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};fX=15/1e6;_P=256});var nR={};we(nR,{REGISTERED_CTX_TOOLS:()=>FP,__resetSuppressionDiagnosticForTests:()=>UB,browserOpenArgv:()=>rR,buildBatchNodeOptionsPrefix:()=>JP,buildFetchCode:()=>tR,classifyIp:()=>ec,currentAttribution:()=>Gn,emitSuppressionDiagnostic:()=>BP,extractSnippet:()=>W_,formatBatchQueryResults:()=>GP,getProjectDir:()=>Lt,killProcessOnPort:()=>X_,openBrowserSync:()=>U_,positionsFromHighlight:()=>KP,registerEmptyToolsListHandler:()=>ZP,resolveSessionIdFromSessionDB:()=>qP,runBatchCommands:()=>QP,server:()=>Fe,shouldSuppressMcpToolsForNativePluginHost:()=>HP,withProjectDirOverride:()=>qB});import{createRequire as DP}from"node:module";import{existsSync as ke,unlinkSync as hi,readdirSync as MP,readFileSync as tc,writeFileSync as B_,renameSync as RB,rmSync as rd,mkdirSync as jP,cpSync as CB,statSync as nd,symlinkSync as OB,lstatSync as LP,realpathSync as IB}from"node:fs";import{execSync as EP,spawnSync as zP}from"node:child_process";import{join as Ce,dirname as Zt,resolve as Ve,sep as L_,isAbsolute as AB}from"node:path";import{fileURLToPath as NB}from"node:url";import{homedir as gi,tmpdir as Z_,cpus as DB}from"node:os";import{request as MB}from"node:https";import{AsyncLocalStorage as jB}from"node:async_hooks";function HP(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??vt().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??zB(r);return FB(n)&&HB(n)}function LB(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
|
|
596
599
|
`;)s++;s<t.length&&(e+=`
|
|
597
|
-
`);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function
|
|
598
|
-
`)}function
|
|
600
|
+
`);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function zB(t){let e=t==="kilo"?"kilo":"opencode",r=[Ve(`${e}.json`),Ve(`${e}.jsonc`),Ve(`.${e}`,`${e}.json`),Ve(`.${e}`,`${e}.jsonc`),Ce(gi(),".config",e,`${e}.json`),Ce(gi(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!ke(n))continue;return JSON.parse(LB(tc(n,"utf8")))}catch{}return null}function FB(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function HB(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function BP(t={}){if(z_)return;z_=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
601
|
+
`)}function UB(){z_=!1}function ZP(t=Fe){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Us,async()=>({tools:[]}))}function ZB(t,e){return async r=>{try{return await e(r)}catch(n){let o=JB(n);if(o)try{return W(t,o)}catch(s){if(s instanceof Kt)return o;throw s}throw n}}}async function qB(t,e){let r=typeof t=="string"?{projectDir:t}:t;return q_.run(r,e)}function Gn(){let t=q_.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??qP();if(e)return{sessionId:e}}function qP(t){let e=Date.now();if(!t?.bypassCache&&Xl&&e-Xl.checkedAt<2e3)return Xl.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??Be(),o=cs({projectDir:r,sessionsDir:n});if(!ke(o))return;let s=rt(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(Xl={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function VB(t){try{let e=Be();if(!ke(e))return;let r=MP(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=Ce(e,n);try{t.index({path:o,source:"session-events",attribution:Gn()}),hi(o)}catch{}}}catch{}}async function WB(){if($r)return $r;try{let{getAdapter:t}=await Promise.resolve().then(()=>(Tn(),zc)),e=vt();return await t(e.platform)}catch{return null}}function mi(){if($r)return $r.getSessionDir();try{let t=vt(),e=Mi(t.platform);if(e)return $c({configDir:Ce(...e),configDirEnv:KB(e)})}catch{}return $c({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function KB(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Be(){return Ir(Jr(mi))}function Lt(){let t=q_.getStore();if(t)return t.projectDir;let e,r,n;try{let o=vt().platform;r=o,o==="claude-code"&&(e=Ce(gi(),".claude","projects")),o==="codex"&&(n=process.env.CODEX_HOME??Ce(gi(),".codex"))}catch{}return dP({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r,codexHome:n})}function GB(t){return AB(t)?t:Ve(Lt(),t)}function Qa(){return cs({projectDir:Lt(),sessionsDir:Be()})}function od(){let t=Ir(Sn(mi));return Zd({projectDir:Lt(),contentDir:t})}function Vr(){if(!Er){let t=od();Er=new vs(t),Er.setDenyChecker(e=>{try{let r=Lt(),n=lo("Read",r);return po(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=Zt(od());Jp(e,14),Er.cleanupStaleSources(14);let r=Ce(gi(),".context-mode","content");ke(r)&&Jp(r,0)}catch{}Gp()}return VB(Er),Er}function JB(t){return t instanceof Kt?{content:[{type:"text",text:is(t)}],isError:!0}:null}async function TP(){return new Promise(t=>{let e=MB("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function QB(){let t=$r?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function eZ(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function tZ(){return!hn||hn==="unknown"?!1:eZ(hn,fn)}function rZ(){if(!tZ())return!1;let t=Date.now();if(Yl>=XB){if(t-$P<YB)return!1;Yl=0}return Yl===0&&($P=t),Yl++,!0}function nZ(){if(!PP){PP=!0;try{let t=qe(),e=Ve(t,"plugins","installed_plugins.json");if(!ke(e))return;let r=JSON.parse(tc(e,"utf-8")),n=Ve(t,"plugins","cache"),o=ke(Ve(qt,"package.json"))?qt:Zt(qt);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||ke(c)||!Ve(c).startsWith(n+L_))continue;try{LP(c).isSymbolicLink()&&hi(c)}catch{}let u=Zt(c);ke(u)||jP(u,{recursive:!0}),ke(o)&&OB(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(nZ(),rZ()&&e.content.length>0){let n=QB();e.content[0].text=`\u26A0\uFE0F context-mode v${fn} outdated \u2192 v${hn} available. Upgrade: ${n}
|
|
599
602
|
|
|
600
|
-
`+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+r,
|
|
603
|
+
`+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+r,sd(),setImmediate(()=>YT(Qa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>WT({sessionDbPath:Qa(),toolName:t,bytesReturned:r})),e}function Tr(t,e="unknown"){ie.bytesIndexed+=t,sd(),t>0&&setImmediate(()=>KT({sessionDbPath:Qa(),source:e,bytesAvoided:t}))}function uZ(t){return cZ.test(t)?t:`pid-${process.ppid}`}function VP(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=uZ(t),r=Ir(ss(mi));return Ce(r,`stats-${e}.json`)}function sd(){let t=Date.now();if(!(t-F_<oZ)){F_=t;try{let e=Object.values(ie.bytesReturned).reduce((d,p)=>d+p,0),r=Object.values(ie.calls).reduce((d,p)=>d+p,0),n=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=Ql?.tokens??0;if(!Ql||t-Ql.computedAt>iZ)try{a=(Ga({sessionsDir:Be()})?.totalEvents??0)*aZ,Ql={tokens:a,computedAt:t}}catch{}let c={schemaVersion:sZ,version:fn,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*Xa()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Xa()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ie.calls,...ie.bytesReturned}).map(d=>[d,{calls:ie.calls[d]||0,bytes:ie.bytesReturned[d]||0}]))},u=VP(),l=`${u}.tmp`;B_(l,JSON.stringify(c)),RB(l,u)}catch{}}}function V_(t,e){try{let r=Qp(process.env.CLAUDE_PROJECT_DIR),n=em(t,r);if(n.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function WP(t,e,r){try{let n=Gv(t,e);if(n.length===0)return null;let o=Qp(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=em(s,o);if(i.decision==="deny")return W(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function H_(t,e){try{let r=Lt(),n=lo("Read",r),o=po(t,n,process.platform==="win32",r);if(o.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function KP(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===pZ){for(e.push(r),n++;n<t.length&&t[n]!==mZ;)r++,n++;n<t.length&&n++}else r++,n++;return e}function W_(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of KP(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,r)+`
|
|
601
604
|
\u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=r)break;let d=t.slice(u,Math.min(l,u+(r-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
|
|
602
605
|
|
|
603
|
-
`)}function
|
|
606
|
+
`)}function GP(t,e,r,n=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:r;for(let c of e){if(i>n){s.push(`## ${c}
|
|
604
607
|
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
|
|
605
|
-
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=
|
|
606
|
-
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function
|
|
607
|
-
\u2026 (truncated)`}function
|
|
608
|
+
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=W_(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
|
|
609
|
+
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function fZ(t){return`'${t.replace(/'/g,"'\\''")}'`}function hZ(t){return`'${t.replace(/'/g,"''")}'`}function JP(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${hZ(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${fZ(r)} `}function XP(t){let e=t.replace(/\s+/g," ").trim();return e.length<=RP?e:e.slice(0,RP)+"\u2026"}function gZ(t){return t.length<=CP?t:t.slice(0,CP)+`
|
|
610
|
+
\u2026 (truncated)`}function YP(t,e,r){let n=r?`path=${r}
|
|
608
611
|
`:"",o=`\`\`\`${t}
|
|
609
|
-
${
|
|
612
|
+
${gZ(e)}
|
|
610
613
|
\`\`\``;return`${n}${o}
|
|
611
614
|
|
|
612
|
-
`}function
|
|
615
|
+
`}function OP(t,e,r,n){let o=r||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(n?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=XP(e);return`# ${t}
|
|
613
616
|
|
|
614
617
|
$ ${a}
|
|
615
618
|
|
|
616
619
|
${o}
|
|
617
|
-
`}function
|
|
620
|
+
`}function IP(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
|
|
618
621
|
`)?"":`
|
|
619
|
-
`}${r}`:r:e}async function
|
|
622
|
+
`}${r}`:r:e}async function QP(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let d=[],p=Date.now(),h=!1;for(let m=0;m<t.length;m++){let f=t[m],g;if(n!==void 0){let _=Date.now()-p,x=n-_;if(x<=0){d.push(`# ${f.label}
|
|
620
623
|
|
|
621
624
|
(skipped \u2014 batch timeout exceeded)
|
|
622
|
-
`),h=!0;continue}g=
|
|
625
|
+
`),h=!0;continue}g=x}let y=await r.execute({language:"shell",code:`${s}${f.command}`,timeout:g});if(d.push(OP(f.label,f.command,IP(y),i)),y.timedOut){h=!0;for(let _=m+1;_<t.length;_++)d.push(`# ${t[_].label}
|
|
623
626
|
|
|
624
627
|
(skipped \u2014 batch timeout exceeded)
|
|
625
|
-
`);break}}return{outputs:d,timedOut:h}}let a=t.map(d=>({run:async()=>{let
|
|
628
|
+
`);break}}return{outputs:d,timedOut:h}}let a=t.map(d=>({run:async()=>{let p=await r.execute({language:"shell",code:`${s}${d.command}`,timeout:n}),h=OP(d.label,d.command,IP(p),i);return{output:p.timedOut?h.replace(/\n$/,"")+`
|
|
626
629
|
(timed out after ${n??"?"}ms)
|
|
627
|
-
`:h,timedOut:!!
|
|
630
|
+
`:h,timedOut:!!p.timedOut}}})),{settled:c}=await E_(a,{concurrency:o}),u=new Array(t.length),l=!1;for(let d=0;d<c.length;d++){let p=c[d];if(p.status==="fulfilled")u[d]=p.value.output,p.value.timedOut&&(l=!0);else{let h=p.reason instanceof Error?p.reason.message:String(p.reason);u[d]=`# ${t[d].label}
|
|
628
631
|
|
|
629
632
|
(executor error: ${h})
|
|
630
|
-
`}}return{outputs:u,timedOut:l}}function
|
|
633
|
+
`}}return{outputs:u,timedOut:l}}function eR(t,e){let r=Vr();Tr(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:Gn()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
|
|
631
634
|
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function fi(t,e,r,n=5){let o=t.split(`
|
|
632
|
-
`).length,s=Buffer.byteLength(t),i=Vr(),a=i.indexPlainText(t,r,void 0,
|
|
633
|
-
`)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let
|
|
634
|
-
`)[0].slice(0,120);l.push(` - ${d.title}: ${
|
|
635
|
-
`)}function
|
|
635
|
+
`).length,s=Buffer.byteLength(t),i=Vr(),a=i.indexPlainText(t,r,void 0,Gn()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
|
|
636
|
+
`)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let p=d.content.split(`
|
|
637
|
+
`)[0].slice(0,120);l.push(` - ${d.title}: ${p}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
|
|
638
|
+
`)}function K_(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?n:e}function G_(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function J_(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function _Z(t){let e=G_(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function xZ(){return D_||(D_=DP(import.meta.url).resolve("turndown")),D_}function bZ(){return M_||(M_=DP(import.meta.url).resolve("turndown-plugin-gfm")),M_}function tR(t,e){let r=JSON.stringify(xZ()),n=JSON.stringify(bZ()),o=JSON.stringify(e),s=ec.toString(),i=ec.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
|
|
636
639
|
var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
|
|
637
640
|
const TurndownService = require(${r});
|
|
638
641
|
const { gfm } = require(${n});
|
|
@@ -877,14 +880,14 @@ async function main() {
|
|
|
877
880
|
emit('text', text);
|
|
878
881
|
}
|
|
879
882
|
main();
|
|
880
|
-
`}function
|
|
883
|
+
`}function SZ(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function kZ(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=ec(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function ec(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?ec(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function wZ(t,e,r,n){let o=await kZ(t);if(o)return o;if(!r&&n!==0){let i=Vr(),a=$_(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=n??vZ;if(l<d){let p=Math.floor(l/36e5),h=Math.floor(l/(60*1e3)),m=p>0?`${p}h ago`:h>0?`${h}m ago`:"just now",f=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:f,ageStr:m,ttlStr:SZ(d)}}}}let s=Ce(Z_(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=tR(t,s),a=await rc.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",p=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${p}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=nd(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=tc(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{rd(s)}catch{}}}function EZ(t){let e=Vr(),r=$_(t.source,t.url),n=Gn(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),Tr(Buffer.byteLength(t.markdown));let s=t.markdown.length>AP?BT(t.markdown,AP)+`
|
|
881
884
|
|
|
882
|
-
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function
|
|
883
|
-
${wi(Ko)}`),
|
|
884
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var qt,
|
|
885
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function j_(t,e){if(!ke(e))return;let r=0;try{for(let n of MP(e))if(!(!n.startsWith("stats-")||!n.endsWith(".json")))try{let o=JSON.parse(tc(Ce(e,n),"utf-8"));r+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(r>0){let n=(t.rescueBytes??0)/4;t.totalEvents=Math.round((r/4+n)/256)}}function NP(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function rR(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function U_(t,e=process.platform,r=zP){let n=rR(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:Ya});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function X_(t,e=process.platform,r=zP){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ya});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],p=u[2],h=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Ya});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ya});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Ya});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}async function $Z(){let t=Gp();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Z_():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{rc.cleanupBackgrounded(),Er&&Er.close();try{hi(cd)}catch{}try{hi(r)}catch{}if(mn&&mn.pid&&!mn.killed)try{mn.kill("SIGTERM")}catch{}},o=async()=>{try{F_=0,sd()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),HT({onShutdown:()=>o()});let s=new zl;await Fe.connect(s);try{B_(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(Tn(),zc)),c=Fe.server.getClientVersion(),u=i(c??void 0);$r=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=QT(Qa());if(i){for(let[a,c]of Object.entries(i.calls))ie.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))ie.bytesReturned[a]=c;i.sessionStart>0&&(ie.sessionStart=i.sessionStart)}}catch{}TP().then(i=>{i!=="unknown"&&(hn=i)}),setInterval(()=>{TP().then(i=>{i!=="unknown"&&(hn=i)})},3600*1e3).unref(),setInterval(()=>sd(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${fn} running on stdio`),console.error(`Detected runtimes:
|
|
886
|
+
${wi(Ko)}`),_n()||(console.error(`
|
|
887
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var qt,fn,Ko,td,Fe,FP,UP,z_,BB,q_,rc,cd,Er,Xl,$r,mn,ie,hn,Yl,$P,XB,YB,PP,oZ,sZ,iZ,aZ,F_,Ql,cZ,lZ,dZ,pZ,mZ,RP,CP,id,ad,qr,A_,yZ,N_,ed,D_,M_,vZ,AP,Ya,oR=S(()=>{"use strict";kT();TT();Ml();w_();LT();Xp();zT();tm();Xo();FT();UT();ZT();Jt();VT();JT();eP();iP();uP();Cr();Tn();zd();wn();pP();bn();wP();jo();qt=Zt(NB(import.meta.url)),fn=(()=>{for(let t of["../package.json","./package.json"]){let e=Ve(qt,t);if(ke(e))try{return JSON.parse(tc(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
|
|
885
888
|
`)}),process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
|
|
886
|
-
`)}));Ko=
|
|
887
|
-
`);process.on("exit",()=>{try{hi(
|
|
889
|
+
`)}));Ko=Qn(),td=Ei(Ko),Fe=new jl({name:"context-mode",version:fn}),FP=[];UP=HP(),z_=!1;BB=Fe.registerTool.bind(Fe);Fe.registerTool=(...t)=>{let[e,r,n]=t;if(UP){BP();return}let o=ZB(e,n);return FP.push({name:e,config:r,handler:o}),t[2]=o,BB(...t)};UP&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&ZP(Fe);q_=new jB;Fe.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Fe.server.setRequestHandler(Hs,async()=>({prompts:[]}));Fe.server.setRequestHandler(zs,async()=>({resources:[]}));Fe.server.setRequestHandler(Fs,async()=>({resourceTemplates:[]}));rc=new ci({runtimes:Ko,projectRoot:()=>Lt()}),cd=Ce(Z_(),`cm-fs-preload-${process.pid}.js`);B_(cd,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
|
|
890
|
+
`);process.on("exit",()=>{try{hi(cd)}catch{}});Er=null;$r=null,mn=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};hn=null,Yl=0,$P=0,XB=3,YB=3600*1e3;PP=!1;oZ=500,sZ=2,iZ=3e4,aZ=256,F_=0,cZ=/^[A-Za-z0-9._-]+$/;lZ=td.join(", "),dZ=_n()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",pZ="",mZ="";RP=500;CP=2e3;Fe.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${dZ} Languages: ${lZ}.
|
|
888
891
|
|
|
889
892
|
Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
|
|
890
893
|
|
|
@@ -915,9 +918,9 @@ RETURNS:
|
|
|
915
918
|
Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
|
|
916
919
|
|
|
917
920
|
EXAMPLE: ctx_execute(language: "shell", code: "npm test 2>&1 | grep -E '(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))' | head -60")
|
|
918
|
-
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:M.object({language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:M.preprocess(
|
|
921
|
+
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:M.object({language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:M.preprocess(J_,M.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:M.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
|
|
919
922
|
|
|
920
|
-
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=
|
|
923
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=V_(e,"execute");if(s)return s}else{let s=WP(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
|
|
921
924
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
922
925
|
let __cm_fs=0;
|
|
923
926
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -976,14 +979,14 @@ ${e}
|
|
|
976
979
|
}
|
|
977
980
|
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
|
|
978
981
|
setInterval(()=>{},2147483647);`:""}
|
|
979
|
-
})(typeof require!=='undefined'?require:null);`);let i=await rc.execute({language:t,code:s,timeout:r,background:n}),a=
|
|
982
|
+
})(typeof require!=='undefined'?require:null);`);let i=await rc.execute({language:t,code:s,timeout:r,background:n}),a=YP(t,e),c=i.stderr?.match(/__CM_NET__:(\d+)/);c&&(ie.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let u=i.stderr?.match(/__CM_FS__:(\d+)/);if(u&&(ie.bytesSandboxed+=parseInt(u[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?W("ctx_execute",{content:[{type:"text",text:`${a}${d}
|
|
980
983
|
|
|
981
984
|
_(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?W("ctx_execute",{content:[{type:"text",text:`${a}${d}
|
|
982
985
|
|
|
983
986
|
_(timed out after ${r}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`${a}Execution timed out after ${r}ms
|
|
984
987
|
|
|
985
988
|
stderr:
|
|
986
|
-
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:
|
|
989
|
+
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:p}=T_({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>id?(Tr(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(p,o,d?`execute:${t}:error`:`execute:${t}`)}`}],isError:d})):Buffer.byteLength(p)>ad?(Tr(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(p,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}`}],isError:d})):W("ctx_execute",{content:[{type:"text",text:`${a}${p}`}],isError:d})}let l=i.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>id)return Tr(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:`${a}${fi(l,o,`execute:${t}`)}`}]});if(Buffer.byteLength(l)>ad){let d=eR(l,`execute:${t}`),p={...d,content:d.content.map((h,m)=>m===0&&h.type==="text"?{...h,text:`${a}${h.text}`}:h)};return W("ctx_execute",p)}return W("ctx_execute",{content:[{type:"text",text:`${a}${l}`}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});id=5e3,ad=102400;Fe.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
|
|
987
990
|
|
|
988
991
|
Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
|
|
989
992
|
|
|
@@ -1002,7 +1005,7 @@ RETURNS:
|
|
|
1002
1005
|
Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
|
|
1003
1006
|
|
|
1004
1007
|
EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
|
|
1005
|
-
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:M.object({path:M.string().describe("Absolute file path or relative to project root"),language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:M.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=
|
|
1008
|
+
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:M.object({path:M.string().describe("Absolute file path or relative to project root"),language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:M.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:M.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=H_(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=V_(r,"execute_file");if(i)return i}else{let i=WP(r,e,"execute_file");if(i)return i}try{let i=await rc.executeFile({path:t,language:e,code:r,timeout:n}),a=YP(e,r,t);if(i.timedOut)return W("ctx_execute_file",{content:[{type:"text",text:`${a}Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:u,output:l}=T_({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(l)>id?(Tr(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(l,o,u?`file:${t}:error`:`file:${t}`)}`}],isError:u})):Buffer.byteLength(l)>ad?(Tr(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(l,"errors failures exceptions",u?`file:${t}:error`:`file:${t}`)}`}],isError:u})):W("ctx_execute_file",{content:[{type:"text",text:`${a}${l}`}],isError:u})}let c=i.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(c)>id)return Tr(Buffer.byteLength(c)),W("ctx_execute_file",{content:[{type:"text",text:`${a}${fi(c,o,`file:${t}`)}`}]});if(Buffer.byteLength(c)>ad){let u=eR(c,`file:${t}`),l={...u,content:u.content.map((d,p)=>p===0&&d.type==="text"?{...d,text:`${a}${d.text}`}:d)};return W("ctx_execute_file",l)}return W("ctx_execute_file",{content:[{type:"text",text:`${a}${c}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Fe.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
|
|
1006
1009
|
|
|
1007
1010
|
WHEN:
|
|
1008
1011
|
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
@@ -1020,37 +1023,37 @@ RETURNS:
|
|
|
1020
1023
|
Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
|
|
1021
1024
|
|
|
1022
1025
|
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
1023
|
-
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:M.object({content:M.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:M.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:M.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:M.array(M.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:M.array(M.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:M.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:M.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:M.array(M.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:M.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:M.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=
|
|
1024
|
-
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Tr(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Tr(h.readFileSync(l).byteLength)}catch{}let
|
|
1025
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${
|
|
1026
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:M.object({content:M.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:M.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:M.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:M.array(M.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:M.array(M.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:M.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:M.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:M.array(M.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:M.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:M.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=H_(e,"ctx_index");if(l)return l}try{let l=e?GB(e):void 0;if(l&&ke(l)&&LP(l).isSymbolicLink()){let m;try{m=IB(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(m!==l){let f=H_(m,"ctx_index");if(f)return f}}if(l&&ke(l)&&nd(l).isDirectory()){let h=Vr(),m=Lt(),f=lo("Read",m),g=process.platform==="win32",y=C=>{try{return po(C,f,g,m).denied}catch{return!1}},_=h.indexDirectory({path:l,source:r??l,attribution:Gn(),perFileDeny:y,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",v=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",E=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${v}${E}
|
|
1027
|
+
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Tr(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Tr(h.readFileSync(l).byteLength)}catch{}let p=Vr().index({content:t,path:l,source:r??l,attribution:Gn()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${p.totalChunks} sections (${p.codeChunks} with code) from: ${p.label}
|
|
1028
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${p.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return W("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});qr=0,A_=Date.now(),yZ=K_("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),N_=K_("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),ed=K_("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8);Fe.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:aP(I_)},async t=>{try{let e=Vr(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
1026
1029
|
|
|
1027
1030
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
1028
1031
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
1029
1032
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
1030
1033
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
1031
1034
|
|
|
1032
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=
|
|
1035
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=cP(c,I_,()=>Lt()),l=Date.now();if(l-A_>yZ&&(qr=0,A_=l),qr++,qr>ed)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${qr} search calls in ${Math.round((l-A_)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let d=qr>N_?1:Math.min(s,2),p=40*1024,h=0,m=[],f=null;if(r==="timeline"||typeof u=="string")try{let C=Be(),b=Lt(),k=cs({projectDir:b,sessionsDir:C});ke(k)&&(f=new Gt({dbPath:k}))}catch{}let y;if(typeof u=="string"&&f)try{y=new Set(f.getSessionIdsForProject(u))}catch{}let _=$r?.getConfigDir()??qe();try{for(let C of o){if(h>p){m.push(`## ${C}
|
|
1033
1036
|
(output cap reached)
|
|
1034
|
-
`);continue}let
|
|
1035
|
-
No results found.`);continue}let k=
|
|
1037
|
+
`);continue}let b;if(r==="timeline"?b=sP({query:C,limit:d,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:Lt(),configDir:_,adapter:$r??void 0,projectScope:u}):b=e.searchWithFallback(C,d,i,a,"like",y),b.length===0){m.push(`## ${C}
|
|
1038
|
+
No results found.`);continue}let k=b.map((P,N)=>{let R=P.origin||"current-session",O=P.timestamp?P.timestamp.slice(0,16).replace("T"," "):"",F=`--- [${R}${O?" | "+O:""} | ${P.source}] ---`,K=`### ${P.title}`,ge=W_(P.content,C,1500,P.highlighted);return`${F}
|
|
1036
1039
|
${K}
|
|
1037
1040
|
|
|
1038
1041
|
${ge}`}).join(`
|
|
1039
1042
|
|
|
1040
|
-
`);
|
|
1043
|
+
`);m.push(`## ${C}
|
|
1041
1044
|
|
|
1042
|
-
${k}`),h+=k.length}}finally{try{f?.close()}catch{}}let
|
|
1045
|
+
${k}`),h+=k.length}}finally{try{f?.close()}catch{}}let x=m.join(`
|
|
1043
1046
|
|
|
1044
1047
|
---
|
|
1045
1048
|
|
|
1046
|
-
`);e.lastRefreshCount>0&&(
|
|
1049
|
+
`);e.lastRefreshCount>0&&(x=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
1047
1050
|
|
|
1048
|
-
`+
|
|
1051
|
+
`+x);let v=Math.max(0,ed-qr),E=Math.max(0,N_-qr);if(qr>=N_?x+=`
|
|
1049
1052
|
|
|
1050
|
-
\u26A0 search call #${qr}/${
|
|
1053
|
+
\u26A0 search call #${qr}/${ed} in this window. Results limited to ${d}/query. ${v} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:x+=`
|
|
1051
1054
|
|
|
1052
|
-
> Throttle: call #${qr}/${
|
|
1053
|
-
Indexed sources: ${C.map(k=>`"${k.label}" (${k.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${
|
|
1055
|
+
> Throttle: call #${qr}/${ed} in this window. ${E} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,x.trim().length===0){let C=e.listSources(),b=C.length>0?`
|
|
1056
|
+
Indexed sources: ${C.map(k=>`"${k.label}" (${k.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${b}`}]})}return W("ctx_search",{content:[{type:"text",text:x}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});D_=null,M_=null;vZ=1440*60*1e3,AP=3072;Fe.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
|
|
1054
1057
|
|
|
1055
1058
|
Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
|
|
1056
1059
|
|
|
@@ -1070,14 +1073,14 @@ RETURNS:
|
|
|
1070
1073
|
EXAMPLE: ctx_fetch_and_index(
|
|
1071
1074
|
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1072
1075
|
concurrency: 5
|
|
1073
|
-
)`,inputSchema:M.object({url:M.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:M.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:M.preprocess(
|
|
1076
|
+
)`,inputSchema:M.object({url:M.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:M.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:M.preprocess(G_,M.array(M.object({url:M.string().describe("URL to fetch"),source:M.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:M.preprocess(J_,M.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:M.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return W("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(R=>({run:()=>wZ(R.url,R.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:p}=await E_(u,{concurrency:c,capByCpuCount:!a&&c>1}),h=[];for(let R=0;R<l.length;R++){let O=l[R];if(O.status==="rejected"){let K=O.reason instanceof Error?O.reason.message:String(O.reason);h.push({kind:"job_error",url:i[R].url,error:K});continue}let F=O.value;if(F.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=F.estimatedBytes;let K=F.estimatedBytes,ge=F.label;setImmediate(()=>GT({sessionDbPath:Qa(),source:ge,bytesAvoided:K})),h.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?h.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):(ie.cacheMisses++,h.push({kind:"fetched",indexed:EZ(F)}))}if(a){let R=h[0];if(R.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: ${R.ttlStr}).
|
|
1074
1077
|
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
1075
1078
|
|
|
1076
1079
|
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1077
1080
|
Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let O=(R.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${O}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,"","---","",R.indexed.preview].join(`
|
|
1078
|
-
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(R.kind==="fetch_error"){let O=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:O}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let
|
|
1081
|
+
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(R.kind==="fetch_error"){let O=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:O}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let m=384,f=[],g=0,y=0,_=0,x=0,v=0,E=[];for(let R of h)if(R.kind==="cached")_++,f.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr}, TTL: ${R.ttlStr})`);else if(R.kind==="fetched"){x++,g+=R.indexed.totalChunks,y+=R.indexed.totalBytes;let O=(R.indexed.totalBytes/1024).toFixed(1);f.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${O}KB)`);let F=R.indexed.preview.length>m?R.indexed.preview.slice(0,m).trimEnd()+"\u2026":R.indexed.preview;E.push(`### ${R.indexed.label}
|
|
1079
1082
|
|
|
1080
|
-
${F}`)}else v++,f.push(`- [err] ${R.url}: ${R.error}`);let C=(y/1024).toFixed(1),
|
|
1083
|
+
${F}`)}else v++,f.push(`- [err] ${R.url}: ${R.error}`);let C=(y/1024).toFixed(1),b=p?` cap=${d}/${DB().length}cpu`:"",k=(R,O,F)=>`${R} ${R===1?O:F}`,N=[`fetched ${i.length} c=${d}${b}. ok=${x} cache=${_} err=${v}. ${k(g,"section","sections")} ${C}KB.`,"",...f,"",'ctx_search(queries: [...], source: "<label>") for full content.',...E.length>0?["","---","",...E]:[]].join(`
|
|
1081
1084
|
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:N}],isError:v===i.length})});Fe.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
|
|
1082
1085
|
|
|
1083
1086
|
Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
|
|
@@ -1103,12 +1106,12 @@ EXAMPLE: ctx_batch_execute(
|
|
|
1103
1106
|
],
|
|
1104
1107
|
queries: ["root cause", "proposed fix"],
|
|
1105
1108
|
concurrency: 2
|
|
1106
|
-
)`,inputSchema:M.object({commands:M.preprocess(
|
|
1109
|
+
)`,inputSchema:M.object({commands:M.preprocess(_Z,M.array(M.object({label:M.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:M.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:M.preprocess(G_,M.array(M.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip."),query_scope:M.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:r,concurrency:n,query_scope:o})=>{for(let s of t){let i=V_(s.command,"batch_execute");if(i)return i}try{let s=JP(Ko.shell,cd),{outputs:i,timedOut:a}=await QP(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:E=>{ie.bytesSandboxed+=E}},rc),c=i.join(`
|
|
1107
1110
|
`),u=Buffer.byteLength(c),l=c.split(`
|
|
1108
|
-
`).length;if(a&&i.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});Tr(u);let d=Vr(),
|
|
1109
|
-
Searchable terms for follow-up: ${
|
|
1110
|
-
`);return W("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${i}`}],isError:!0})}});Fe.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:M.object({})},async()=>{let t;try{let e=Lt(),r=nt(e),n=cs({projectDir:e,sessionsDir:Be()});if(ke(n)){let o=rt(),s=new o(n,{readonly:!0});try{let i=new pi(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=Ga({sessionsDir:Be()}),l;try{l=
|
|
1111
|
-
`)}]})});Fe.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:M.object({})},async()=>{let t=ke(Ve(qt,"package.json"))?qt:Zt(qt),e=Ve(t,"cli.bundle.mjs"),r=Ve(t,"build","cli.js");try{let a=Be(),c=Ce(Zt(a),"insight-cache");ke(c)&&(
|
|
1111
|
+
`).length;if(a&&i.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});Tr(u);let d=Vr(),p=`batch:${t.map(E=>E.label).join(",").slice(0,80)}`,h=d.index({content:c,source:p,attribution:Gn()}),m=["## Commands",""];for(let E of t)m.push(`- ${E.label}: \`${XP(E.command)}\``);let f=d.getChunksBySource(h.sourceId),g=["## Indexed Sections",""],y=[];for(let E of f){let C=Buffer.byteLength(E.content);g.push(`- ${E.title} (${(C/1024).toFixed(1)}KB)`),y.push(E.title)}let _=GP(d,e,p,void 0,o),x=d.getDistinctiveTerms?d.getDistinctiveTerms(h.sourceId):[],v=[`Executed ${t.length} commands (${l} lines, ${(u/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...m,"",...g,"",..._,x.length>0?`
|
|
1112
|
+
Searchable terms for follow-up: ${x.join(", ")}`:""].join(`
|
|
1113
|
+
`);return W("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${i}`}],isError:!0})}});Fe.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:M.object({})},async()=>{let t;try{let e=Lt(),r=nt(e),n=cs({projectDir:e,sessionsDir:Be()});if(ke(n)){let o=rt(),s=new o(n,{readonly:!0});try{let i=new pi(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=Ga({sessionsDir:Be()}),l;try{l=Gl()}catch{}let d,p;try{let m=process.env.CLAUDE_SESSION_ID;if(m||(m=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),m){d=vP({sessionId:m,sessionsDir:Be(),worktreeHash:r});let f=od(),g;try{let v=rt(),E=(await import("node:fs")).readdirSync(Be()).filter(b=>b.endsWith(".db")&&(!r||b.startsWith(r))),C;for(let b of E)try{let k=new v((await import("node:path")).join(Be(),b),{readonly:!0});try{let P=k.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(m);if(P?.project_dir){C=P.project_dir;break}}finally{k.close()}}catch{}g=C?Ja({projectDir:C,sessionsDir:Be(),worktreeHash:r,contentDbPath:f}):Ja({sessionId:m,sessionsDir:Be(),worktreeHash:r,contentDbPath:f})}catch{g=Ja({sessionId:m,sessionsDir:Be(),worktreeHash:r,contentDbPath:f})}let y=Ja({sessionsDir:Be()}),_=SP(f),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};p={conversation:g,lifetime:x}}}catch{}$r?.name==="Pi"&&j_(u,Be());let h;try{h=Vr().getIndexState()}catch{}t=Jl(a,fn,hn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:p,indexState:h,cwd:e})}finally{s.close()}}else{let s=new pi(NP()).queryAll(ie),i=Ga({sessionsDir:Be()});$r?.name==="Pi"&&j_(i,Be());let a;try{a=Gl()}catch{}let c;try{c=Vr().getIndexState()}catch{}t=Jl(s,fn,hn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let r=new pi(NP()).queryAll(ie),n;try{n=Ga({sessionsDir:Be()})}catch{}$r?.name==="Pi"&&n&&j_(n,Be());let o;try{o=Gl()}catch{}t=Jl(r,fn,hn,n||o?{lifetime:n,multiAdapter:o}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Fe.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:M.object({})},async()=>{let t=["context-mode doctor",""],e=ke(Ve(qt,"package.json"))?qt:Zt(qt),r=11,n=(td.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${td.length}/${r} (${n}%) \u2014 ${td.join(", ")}`),_n()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=Jr(mi),s=Sn(mi),i=ss(mi);t.push(`[OK] Storage sessions: ${o.path} (${Ri(o)})`),t.push(`[OK] Storage content: ${s.path} (${Ri(s)})`),t.push(`[OK] Storage stats: ${i.path} (${Ri(i)})`);{let c=new ci({runtimes:Ko});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let l=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${l}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=rt();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let l=c.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();l&&l.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await WB();if(a){for(let u of a.validateHooks(e)){let l=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",d=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${l} ${u.check}: ${u.message}${d}`)}let c=_c(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let l=Ve(e,u);ke(l)?t.push(`[OK] Hook script: PASS \u2014 ${l}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${l}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${fn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1114
|
+
`)}]})});Fe.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:M.object({})},async()=>{let t=ke(Ve(qt,"package.json"))?qt:Zt(qt),e=Ve(t,"cli.bundle.mjs"),r=Ve(t,"build","cli.js");try{let a=Be(),c=Ce(Zt(a),"insight-cache");ke(c)&&(X_(4747),rd(c,{recursive:!0,force:!0}))}catch{}let n="",o;try{let{detectPlatform:a}=await Promise.resolve().then(()=>(Tn(),zc)),c=Fe.server.getClientVersion(),u=a(c??void 0);n=` --platform ${u.platform}`,o=Yn(u.platform)&&Ko.javascript?{platform:u.platform,jsRuntime:Ko.javascript}:void 0}catch{}let s;if(ke(e))s=`${Si(e,o)} upgrade${n}`;else if(ke(r))s=`${Si(r,o)} upgrade${n}`;else{let c=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
|
|
1112
1115
|
`),u=Ve(t,".ctx-upgrade-inline.mjs"),{writeFileSync:l}=await import("node:fs");l(u,c),s=Si(u,o)}let i=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",s,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
|
|
1113
1116
|
`);return W("ctx_upgrade",{content:[{type:"text",text:i}]})});Fe.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
|
|
1114
1117
|
|
|
@@ -1134,85 +1137,85 @@ RETURNS:
|
|
|
1134
1137
|
A summary of removed rows + the resolved scope.
|
|
1135
1138
|
|
|
1136
1139
|
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1137
|
-
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:M.object({confirm:M.preprocess(
|
|
1140
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:M.object({confirm:M.preprocess(J_,M.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:M.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:M.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return W("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=od()}catch{}if(Er){try{Er.cleanup()}catch{}Er=null}let s=o?Zt(o):void 0,{deleted:i}=qT({projectDir:Lt(),sessionsDir:Be(),storePath:o,contentDir:s,legacyContentDir:Ce(gi(),".context-mode","content"),contentHash:Ar(Lt()),scope:n,sessionId:e});if(n==="project"){ie.calls={},ie.bytesReturned={},ie.bytesIndexed=0,ie.bytesSandboxed=0,ie.cacheHits=0,ie.cacheBytesSaved=0,ie.sessionStart=Date.now(),i.push("session stats");try{let c=VP();ke(c)&&hi(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return W("ctx_purge",{content:[{type:"text",text:a}]})});Ya=5e3;Fe.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser \u2014 a dashboard launcher for session analytics; for natural-language queries over indexed content, use ctx_search. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:M.object({port:M.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:M.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:M.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:M.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:M.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=ke(Ve(qt,"package.json"))?qt:Zt(qt),u=Ve(c,"insight"),l=i?Ve(i):Be(),d=a?Ve(a):Ce(Zt(l),"content"),p=Ce(Zt(l),"insight-cache");if(i||a){let h=Be(),m=Zt(Zt(h)),f=Ve(m)+L_,g=y=>(Ve(y)+L_).startsWith(f);if(i&&!g(l))return W("ctx_insight",{content:[{type:"text",text:`Error: sessionDir must resolve under ${m} (got ${l}).`}]});if(a&&!g(d))return W("ctx_insight",{content:[{type:"text",text:`Error: contentDir must resolve under ${m} (got ${d}).`}]})}if(!ke(Ce(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let h=[],m=!1;jP(p,{recursive:!0});let f=nd(Ce(u,"server.mjs")).mtimeMs,g=ke(Ce(p,"server.mjs"))?nd(Ce(p,"server.mjs")).mtimeMs:0;if(f>g&&(h.push("Copying source files..."),CB(u,p,{recursive:!0,force:!0}),h.push("Source files copied."),m=!0),!ke(Ce(p,"node_modules"))||m){h.push("Installing dependencies (first run, ~30s)...");try{EP(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:p,stdio:"pipe",timeout:3e5})}catch{try{rd(Ce(p,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ke(Ce(p,"node_modules","vite"))||!ke(Ce(p,"node_modules","better-sqlite3")))throw rd(Ce(p,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");h.push("Dependencies installed.")}h.push("Building dashboard..."),EP("npx vite build",{cwd:p,stdio:"pipe",timeout:6e4}),h.push("Build complete.");let _=!1;try{let{request:k}=await import("node:http");await new Promise((P,N)=>{let R=k(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},O=>{O.resume(),P()});R.on("error",()=>N()),R.on("timeout",()=>{R.destroy(),N()}),R.end()}),_=!0}catch{}if(_&&m){h.push("Killing stale dashboard server (source updated)...");let k=X_(s);if(k.attemptedPids.length>0&&k.killedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${k.attemptedPids.join(", ")}: ${k.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(k.errors.length>0&&k.attemptedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${k.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(P=>setTimeout(P,500)),h.push(`Stale server killed (${k.killedPids.length} pid${k.killedPids.length===1?"":"s"}).`)}else if(_){h.push("Dashboard already running.");let k=`http://localhost:${s}`,P=U_(k),N=P.ok?"":` (auto-open failed: ${P.reason}; navigate manually)`;return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${k}${N}`}]})}if(mn&&mn.pid&&!mn.killed)try{mn.kill("SIGTERM")}catch{}let{spawn:x}=await import("node:child_process"),v=x("node",[Ce(p,"server.mjs")],{cwd:p,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:l,INSIGHT_CONTENT_DIR:d,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});v.on("error",()=>{}),v.unref(),mn=v,await new Promise(k=>setTimeout(k,1500));try{let{request:k}=await import("node:http");await new Promise((P,N)=>{let R=k(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},O=>{P(),O.resume()});R.on("error",N),R.on("timeout",()=>{R.destroy(),N(new Error("timeout"))}),R.end()})}catch{return W("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
|
|
1138
1141
|
|
|
1139
1142
|
To fix:
|
|
1140
1143
|
- Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${s}`:`lsof -ti:${s} | xargs kill`}
|
|
1141
|
-
- Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let E=`http://localhost:${s}`,C=
|
|
1144
|
+
- Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let E=`http://localhost:${s}`,C=U_(E),b=C.ok?"":` (auto-open failed: ${C.reason}; navigate manually)`;return h.push(`Dashboard running at ${E}${b}`),W("ctx_insight",{content:[{type:"text",text:h.map(k=>`- ${k}`).join(`
|
|
1142
1145
|
`)+`
|
|
1143
1146
|
|
|
1144
1147
|
Open: ${E}
|
|
1145
|
-
PID: ${v.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${v.pid} /F`:`kill ${v.pid}`}`}]})}catch(h){let
|
|
1146
|
-
`,"utf-8")}catch{return"noop"}return"healed"}function
|
|
1147
|
-
${e}`,"utf-8"),(
|
|
1148
|
-
`),l=!1;for(let d=0;d<u.length;d++){let
|
|
1149
|
-
`){s&&(n+=
|
|
1150
|
-
`&&(o&&
|
|
1151
|
-
`)}var xi
|
|
1152
|
-
`);if(d.length>0){let[
|
|
1148
|
+
PID: ${v.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${v.pid} /F`:`kill ${v.pid}`}`}]})}catch(h){let m=h instanceof Error?h.message:String(h);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${m}`}]})}});process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&$Z().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var pR={};we(pR,{needsHookNormalization:()=>oc,normalizeHooksJson:()=>uR,normalizeHooksJsonOnly:()=>dR,normalizeHooksOnStartup:()=>TZ,normalizePluginJson:()=>lR});import{existsSync as sR,readFileSync as iR,writeFileSync as aR}from"node:fs";import{resolve as cR}from"node:path";function Jn(t){return String(t).replace(/\\/g,"/")}function Y_(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Jn(t));return e?e[1]:null}function Q_(t,e){if(!e||!t||typeof t!="string")return!1;let r=Jn(t);ud.lastIndex=0;let n;for(;(n=ud.exec(r))!==null;)if(n[1]!==e)return!0;return!1}function oc(t,e){return!t||typeof t!="string"?!1:t.includes(nc)?!0:Q_(t,Y_(e))}function uR(t,e,r){if(!oc(t,r))return t;let n=Jn(e),o=Jn(r),s=Y_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(Array.isArray(l))for(let d of l){let p=d?.hooks;if(Array.isArray(p))for(let h of p){if(typeof h?.command!="string")continue;let m=h.command.includes(nc),f=Q_(h.command,s);if(!m&&!f)continue;let g=h.command;m&&(g=g.replaceAll(nc,o),g=g.replace(/^\s*node\s+/,`"${n}" `)),f&&(g=Jn(g).replace(ud,`context-mode/context-mode/${s}`)),h.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function lR(t,e,r){if(!oc(t,r))return t;let n=Jn(e),o=Jn(r),s=Y_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(!(!l||typeof l!="object")){if(Array.isArray(l.args)){let d=l.args,p=d.map(h=>{if(typeof h!="string")return h;let m=h;return m.includes(nc)&&(m=m.replaceAll(nc,o)),Q_(m,s)&&(m=Jn(m).replace(ud,`context-mode/context-mode/${s}`)),m});p.some((h,m)=>h!==d[m])&&(l.args=p,c=!0)}l.command==="node"&&c&&(l.command=n)}}return c?JSON.stringify(i,null,2):t}function dR({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}){let o=r||e;if(!(n!=="win32"&&n!=="linux"&&!(r&&r!==e))&&!(!t||!o))try{let a=cR(t,"hooks","hooks.json");if(sR(a)){let c=iR(a,"utf-8");if(oc(c,t)){let u=uR(c,o,t);u!==c&&aR(a,u,"utf-8")}}}catch{}}function TZ({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}){if(dR({pluginRoot:t,nodePath:e,jsRuntimePath:r,platform:n}),!(n!=="win32"&&n!=="linux")&&!(!t||!e))try{let o=cR(t,".claude-plugin","plugin.json");if(sR(o)){let s=iR(o,"utf-8");if(oc(s,t)){let i=lR(s,e,t);i!==s&&aR(o,i,"utf-8")}}}catch{}}var nc,ud,mR=S(()=>{"use strict";nc="${CLAUDE_PLUGIN_ROOT}",ud=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});var vR={};we(vR,{buildHookCommand:()=>_R,ensureShebangAndExecBit:()=>bR,extractNodePath:()=>gR,isStaleNodePath:()=>yR,rewriteShellSnapshots:()=>xR,selfHealCacheHealHook:()=>AZ,selfHealShellSnapshots:()=>NZ});import{existsSync as sc,readFileSync as ex,writeFileSync as tx,chmodSync as PZ,statSync as hR,readdirSync as RZ,renameSync as CZ,unlinkSync as OZ}from"node:fs";import{join as IZ}from"node:path";function fR(t){return String(t).replace(/\\/g,"/")}function gR(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let r;if(e.startsWith('"')){let o=e.indexOf('"',1);if(o===-1)return null;r=e.slice(1,o)}else{let o=e.search(/\s/);r=o===-1?e:e.slice(0,o)}if(!r)return null;let n=r.split(/[\\/]/).pop()??"";return/^node(\.exe)?$/i.test(n)?r:null}function yR(t){let e=gR(t);if(!e)return!1;try{return!sc(e)}catch{return!1}}function _R({scriptPath:t,platform:e,nodePath:r}){if(!t||typeof t!="string")throw new TypeError("buildHookCommand: scriptPath is required");let n=fR(t);if(e==="win32"){if(!r||typeof r!="string")throw new TypeError("buildHookCommand: nodePath is required on win32");return`"${fR(r)}" "${n}"`}return`"${n}"`}function AZ({settingsPath:t,scriptPath:e,platform:r,nodePath:n}){if(!t||!sc(t))return"missing-settings";let o;try{o=ex(t,"utf-8")}catch{return"noop"}let s;try{s=JSON.parse(o)}catch{return"noop"}let i=s?.hooks;if(!i||typeof i!="object")return"noop";let a=Array.isArray(i.SessionStart)?i.SessionStart:null;if(!a)return"noop";let c=!1;for(let u of a){let l=u?.hooks;if(Array.isArray(l))for(let d of l)typeof d?.command=="string"&&d.command.includes("context-mode-cache-heal")&&yR(d.command)&&(d.command=_R({scriptPath:e,platform:r,nodePath:n}),c=!0)}if(!c)return"noop";if(r!=="win32"&&e&&sc(e))try{bR(e)}catch{}try{tx(t,JSON.stringify(s,null,2)+`
|
|
1149
|
+
`,"utf-8")}catch{return"noop"}return"healed"}function xR({snapshotsDir:t,currentVersion:e}){let r={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return r;let n;try{if(!sc(t))return r;n=RZ(t)}catch{return r}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of n){if(!s.endsWith(".sh"))continue;let i=IZ(t,s),a;try{if(!hR(i).isFile())continue;a=ex(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,p,h,m)=>h===e?d:(c=!0,`${p}${e}${m}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{tx(l,u,"utf-8"),CZ(l,i),r.rewritten.push(i)}catch{try{OZ(l)}catch{}}}return r}function NZ({snapshotsDir:t,pluginCacheRoot:e,currentVersion:r}){return xR({snapshotsDir:t,currentVersion:r})}function bR(t){if(!(!t||!sc(t)))try{let e=ex(t,"utf-8");e.startsWith("#!")||tx(t,`#!/usr/bin/env node
|
|
1150
|
+
${e}`,"utf-8"),(hR(t).mode&511)!==493&&PZ(t,493)}catch{}}var SR=S(()=>{"use strict"});import{stdout as nC,stdin as oC}from"node:process";import*as gn from"node:readline";var cx=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,ux=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,lx=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var xd=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,cc=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,uc=/\t{1,1000}/y,bd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),lc=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,VR=new RegExp("\\p{M}+","gu"),WR={limit:1/0,ellipsis:""},dx=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?dx(o,WR,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,l=r.emojiWidth??2,d=r.fullWidthWidth??2,p=r.regularWidth??1,h=r.wideWidth??2,m=0,f=0,g=t.length,y=0,_=!1,x=g,v=Math.max(0,n-s),E=0,C=0,b=0,k=0;e:for(;;){if(C>E||f>=g&&f>m){let P=t.slice(E,C)||t.slice(m,f);y=0;for(let N of P.replaceAll(VR,"")){let R=N.codePointAt(0)||0;if(ux(R)?k=d:lx(R)?k=h:u!==p&&cx(R)?k=u:k=p,b+k>v&&(x=Math.min(x,Math.max(E,m)+y)),b+k>n){_=!0;break e}y+=N.length,b+=k}E=C=0}if(f>=g)break;if(lc.lastIndex=f,lc.test(t)){if(y=lc.lastIndex-f,k=y*p,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/p))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=lc.lastIndex;continue}if(xd.lastIndex=f,xd.test(t)){if(b+i>v&&(x=Math.min(x,f)),b+i>n){_=!0;break}b+=i,E=m,C=f,f=m=xd.lastIndex;continue}if(cc.lastIndex=f,cc.test(t)){if(y=cc.lastIndex-f,k=y*a,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/a))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=cc.lastIndex;continue}if(uc.lastIndex=f,uc.test(t)){if(y=uc.lastIndex-f,k=y*c,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/c))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=uc.lastIndex;continue}if(bd.lastIndex=f,bd.test(t)){if(b+l>v&&(x=Math.min(x,f)),b+l>n){_=!0;break}b+=l,E=m,C=f,f=m=bd.lastIndex;continue}f+=1}return{width:_?v:b,index:_?x:g,truncated:_,ellipsed:_&&n>=s}},px=dx;var KR={limit:1/0,ellipsis:"",ellipsisWidth:0},GR=(t,e={})=>px(t,KR,e).width,xt=GR;var dc="\x1B",yx="\x9B",JR=39,Sd="\x07",_x="[",XR="]",xx="m",kd=`${XR}8;;`,mx=new RegExp(`(?:\\${_x}(?<code>\\d+)m|\\${kd}(?<uri>.*)${Sd})`,"y"),fx=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},hx=t=>`${dc}${_x}${t}${xx}`,gx=t=>`${dc}${kd}${t}${Sd}`,vd=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:xt(i),c=n.next(),u=n.next(),l=0;for(;!c.done;){let d=c.value,p=xt(d);a+p<=r?t[t.length-1]+=d:(t.push(d),a=0),(d===dc||d===yx)&&(o=!0,s=e.startsWith(kd,l+1)),o?s?d===Sd&&(o=!1,s=!1):d===xx&&(o=!1):(a+=p,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},YR=t=>{let e=t.split(" "),r=e.length;for(;r&&!xt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},QR=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(r.trim!==!1){let m=a.at(-1)??"",f=m.trimStart();m.length!==f.length&&(a[a.length-1]=f,c=xt(f))}d!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let h=xt(p);if(r.hard&&h>e){let m=e-c,f=1+Math.floor((h-m-1)/e);Math.floor((h-1)/e)<f&&a.push(""),vd(a,p,e),c=xt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(r.wordWrap===!1&&c<e){vd(a,p,e),c=xt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&r.wordWrap===!1){vd(a,p,e),c=xt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=h}r.trim!==!1&&(a=a.map(d=>YR(d)));let u=a.join(`
|
|
1151
|
+
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(n+=p,!l)l=p>="\uD800"&&p<="\uDBFF";else continue;if(p===dc||p===yx){mx.lastIndex=d+1;let m=mx.exec(u)?.groups;if(m?.code!==void 0){let f=Number.parseFloat(m.code);o=f===JR?void 0:f}else m?.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}if(u[d+1]===`
|
|
1152
|
+
`){s&&(n+=gx(""));let h=o?fx(o):void 0;o&&h&&(n+=hx(h))}else p===`
|
|
1153
|
+
`&&(o&&fx(o)&&(n+=hx(o)),s&&(n+=gx(s)))}return n},eC=/\r?\n/;function Jo(t,e,r){return String(t).normalize().split(eC).map(n=>QR(n,e,r)).join(`
|
|
1154
|
+
`)}var bi=xi(Ed(),1);import{ReadStream as vx}from"node:tty";var sC=["up","down","left","right","space","enter","cancel"],iC=["January","February","March","April","May","June","July","August","September","October","November","December"],Rr={actions:new Set(sC),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...iC],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Sx(t,e){if(typeof t=="string")return Rr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Sx(r,e))return!0;return!1}var aC=globalThis.process.platform.startsWith("win");function kx({input:t=oC,output:e=nC,overwrite:r=!0,hideCursor:n=!0}={}){let o=gn.createInterface({input:t,output:e,prompt:"",tabSize:1});gn.emitKeypressEvents(t,o),t instanceof vx&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(Sx([u,a,c],"cancel")){n&&e.write(bi.cursor.show),process.exit(0);return}if(!r)return;gn.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{gn.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(bi.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(bi.cursor.show),t instanceof vx&&t.isTTY&&!aC&&t.setRawMode(!1),o.terminal=!1,o.close()}}var $d=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as De,stripVTControlCharacters as Fq}from"node:util";import Vt from"node:process";var vi=xi(Ed(),1);function uC(){return Vt.platform!=="win32"?Vt.env.TERM!=="linux":!!Vt.env.CI||!!Vt.env.WT_SESSION||!!Vt.env.TERMINUS_SUBLIME||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Td=uC(),lC=()=>process.env.CI==="true";var _e=(t,e)=>Td?t:e,Zq=_e("\u25C6","*"),dC=_e("\u25A0","x"),pC=_e("\u25B2","x"),Pd=_e("\u25C7","o"),mC=_e("\u250C","T"),yn=_e("\u2502","|"),fC=_e("\u2514","\u2014"),qq=_e("\u2510","T"),Vq=_e("\u2518","\u2014"),Wq=_e("\u25CF",">"),Kq=_e("\u25CB"," "),Gq=_e("\u25FB","[\u2022]"),Jq=_e("\u25FC","[+]"),Xq=_e("\u25FB","[ ]"),Yq=_e("\u25AA","\u2022"),wx=_e("\u2500","-"),hC=_e("\u256E","+"),gC=_e("\u251C","+"),yC=_e("\u256F","+"),_C=_e("\u2570","+"),Qq=_e("\u256D","+"),xC=_e("\u25CF","\u2022"),bC=_e("\u25C6","*"),vC=_e("\u25B2","!"),SC=_e("\u25A0","x");var I={message:(t=[],{symbol:e=De("gray",yn),secondarySymbol:r=De("gray",yn),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Rr.withGuide,c=a?r:"",u=a?`${e} `:"",l=a?`${r} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
1155
|
+
`);if(d.length>0){let[p,...h]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of h)m.length>0?i.push(`${l}${m}`):i.push(a?r:"")}n.write(`${i.join(`
|
|
1153
1156
|
`)}
|
|
1154
|
-
`)},info:(t,e)=>{I.message(t,{...e,symbol:De("blue",
|
|
1155
|
-
`)},pc=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Rr.withGuide?`${De("gray",
|
|
1156
|
-
${De("gray",
|
|
1157
|
-
|
|
1158
|
-
`)};var
|
|
1159
|
-
`),s=o.reduce((c,u)=>Math.max(
|
|
1160
|
-
`).map(s),""],a=
|
|
1161
|
-
`),l=o?`${De("gray",
|
|
1162
|
-
`:"",d=o?
|
|
1157
|
+
`)},info:(t,e)=>{I.message(t,{...e,symbol:De("blue",xC)})},success:(t,e)=>{I.message(t,{...e,symbol:De("green",bC)})},step:(t,e)=>{I.message(t,{...e,symbol:De("green",Pd)})},warn:(t,e)=>{I.message(t,{...e,symbol:De("yellow",vC)})},warning:(t,e)=>{I.warn(t,e)},error:(t,e)=>{I.message(t,{...e,symbol:De("red",SC)})}};var Rd=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Rr.withGuide?`${De("gray",mC)} `:"";r.write(`${n}${t}
|
|
1158
|
+
`)},pc=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Rr.withGuide?`${De("gray",yn)}
|
|
1159
|
+
${De("gray",fC)} `:"";r.write(`${n}${t}
|
|
1160
|
+
|
|
1161
|
+
`)};var kC=t=>De("dim",t),wC=(t,e,r)=>{let n={hard:!0,trim:!1},o=Jo(t,e,n).split(`
|
|
1162
|
+
`),s=o.reduce((c,u)=>Math.max(xt(u),c),0),i=o.map(r).reduce((c,u)=>Math.max(xt(u),c),0),a=e-(i-s);return Jo(t,a,n)},mc=(t="",e="",r)=>{let n=r?.output??Vt.stdout,o=r?.withGuide??Rr.withGuide,s=r?.format??kC,i=["",...wC(t,$d(n)-6,s).split(`
|
|
1163
|
+
`).map(s),""],a=xt(e),c=Math.max(i.reduce((p,h)=>{let m=xt(h);return m>p?m:p},0),a)+2,u=i.map(p=>`${De("gray",yn)} ${p}${" ".repeat(c-xt(p))}${De("gray",yn)}`).join(`
|
|
1164
|
+
`),l=o?`${De("gray",yn)}
|
|
1165
|
+
`:"",d=o?gC:_C;n.write(`${l}${De("green",Pd)} ${De("reset",e)} ${De("gray",wx.repeat(Math.max(c-a-1,1))+hC)}
|
|
1163
1166
|
${u}
|
|
1164
|
-
${De("gray",d+
|
|
1165
|
-
`)};var
|
|
1167
|
+
${De("gray",d+wx.repeat(c+2)+yC)}
|
|
1168
|
+
`)};var EC=t=>De("magenta",t),Cd=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:o,frames:s=Td?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Td?80:120,signal:a,...c}={})=>{let u=lC(),l,d,p=!1,h=!1,m="",f,g=performance.now(),y=$d(r),_=c?.styleFrame??EC,x=K=>{let ge=K>1?o??Rr.messages.error:n??Rr.messages.cancel;h=K===1,p&&(F(ge,K),h&&typeof e=="function"&&e())},v=()=>x(2),E=()=>x(1),C=()=>{process.on("uncaughtExceptionMonitor",v),process.on("unhandledRejection",v),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",x),a&&a.addEventListener("abort",E)},b=()=>{process.removeListener("uncaughtExceptionMonitor",v),process.removeListener("unhandledRejection",v),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",x),a&&a.removeEventListener("abort",E)},k=()=>{if(f===void 0)return;u&&r.write(`
|
|
1166
1169
|
`);let K=Jo(f,y,{hard:!0,trim:!1}).split(`
|
|
1167
|
-
`);K.length>1&&r.write(vi.cursor.up(K.length-1)),r.write(vi.cursor.to(0)),r.write(vi.erase.down())},P=K=>K.replace(/\.+$/,""),N=K=>{let ge=(performance.now()-K)/1e3,We=Math.floor(ge/60),_t=Math.floor(ge%60);return We>0?`[${We}m ${_t}s]`:`[${_t}s]`},R=c.withGuide??Rr.withGuide,O=(K="")=>{
|
|
1168
|
-
`);let ge=0,We=0;C(),d=setInterval(()=>{if(u&&
|
|
1169
|
-
`):r.write(`${_t} ${
|
|
1170
|
-
`)),
|
|
1171
|
-
`)}catch{}return null}return i[1]}catch{return null}}
|
|
1172
|
-
`))}if(et[0]==="--help"||et[0]==="-h"||et[0]==="help")
|
|
1173
|
-
Could not auto-open browser. Open manually: ${t}`),s=
|
|
1174
|
-
`),"Storage paths"),r+=
|
|
1170
|
+
`);K.length>1&&r.write(vi.cursor.up(K.length-1)),r.write(vi.cursor.to(0)),r.write(vi.erase.down())},P=K=>K.replace(/\.+$/,""),N=K=>{let ge=(performance.now()-K)/1e3,We=Math.floor(ge/60),_t=Math.floor(ge%60);return We>0?`[${We}m ${_t}s]`:`[${_t}s]`},R=c.withGuide??Rr.withGuide,O=(K="")=>{p=!0,l=kx({output:r}),m=P(K),g=performance.now(),R&&r.write(`${De("gray",yn)}
|
|
1171
|
+
`);let ge=0,We=0;C(),d=setInterval(()=>{if(u&&m===f)return;k(),f=m;let _t=_(s[ge]),Pr;if(u)Pr=`${_t} ${m}...`;else if(t==="timer")Pr=`${_t} ${m} ${N(g)}`;else{let ac=".".repeat(Math.floor(We)).slice(0,3);Pr=`${_t} ${m}${ac}`}let ic=Jo(Pr,y,{hard:!0,trim:!1});r.write(ic),ge=ge+1<s.length?ge+1:0,We=We<4?We+.125:0},i)},F=(K="",ge=0,We=!1)=>{if(!p)return;p=!1,clearInterval(d),k();let _t=ge===0?De("green",Pd):ge===1?De("red",dC):De("red",pC);m=K??m,We||(t==="timer"?r.write(`${_t} ${m} ${N(g)}
|
|
1172
|
+
`):r.write(`${_t} ${m}
|
|
1173
|
+
`)),b(),l()};return{start:O,stop:(K="")=>F(K,0),message:(K="")=>{m=P(K??m)},cancel:(K="")=>F(K,1),error:(K="")=>F(K,2),clear:()=>F("",0,!0),get isCancelled(){return h}}},e4={light:_e("\u2500","-"),heavy:_e("\u2501","="),block:_e("\u2588","#")};var t4=`${De("gray",yn)} `;var w=xi(Tx(),1);Xo();zd();wn();Jt();Xp();tm();import{execFileSync as yi,execSync as DZ,execFile as MZ}from"node:child_process";import{readFileSync as Wr,cpSync as kR,accessSync as $R,existsSync as $e,readdirSync as jZ,rmSync as _i,closeSync as LZ,openSync as zZ,chmodSync as FZ,lstatSync as HZ,realpathSync as pd,statSync as TR,constants as PR}from"node:fs";import{request as UZ}from"node:https";import{resolve as Q,dirname as ox,join as yt,sep as Kr,basename as BZ,isAbsolute as ZZ}from"node:path";import{tmpdir as qZ,devNull as VZ,homedir as md}from"node:os";import{fileURLToPath as WZ,pathToFileURL as fd}from"node:url";import{execFileSync as RA}from"node:child_process";var CA="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",OA=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,IA=(t,e)=>RA(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),AA=t=>{try{return process.kill(t,0),!0}catch{return!1}},NA=(t,e)=>{process.kill(t,e)};function DA(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let o=Number.parseInt(n,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Jv(t){let e=t.platform??process.platform,r=t.runCommand??IA,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",OA]):n=r("pgrep",["-f",CA])}catch{return[]}return DA(n).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function MA(t){return new Promise(e=>{setTimeout(e,t)})}async function Xv(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??AA,o=t.sendSignal??NA,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let d of t.pids){n(d)&&(i.add(d),a.add(d));try{o(d,"SIGTERM")}catch(p){p?.code!=="ESRCH"&&a.delete(d)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await MA(r);for(let d of[...a])n(d)||(a.delete(d),u++)}let l=0;for(let d of a){try{o(d,"SIGKILL")}catch(p){if(p?.code==="ESRCH"){u++;continue}continue}i.has(d)&&l++}return{terminatedBySigterm:u,terminatedBySigkill:l,totalKilled:u+l}}rm();import{existsSync as ZA}from"node:fs";import{execSync as qA,execFileSync as S3,spawnSync as k3}from"node:child_process";function Qv({platform:t=process.platform,existsSync:e=ZA,exec:r=qA,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=r(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
|
|
1174
|
+
`)}catch{}return null}return i[1]}catch{return null}}Tn();Cr();function KZ(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var GZ={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},kimi:{pretooluse:"hooks/kimi/pretooluse.mjs",posttooluse:"hooks/kimi/posttooluse.mjs",precompact:"hooks/kimi/precompact.mjs",sessionstart:"hooks/kimi/sessionstart.mjs",sessionend:"hooks/kimi/sessionend.mjs",userpromptsubmit:"hooks/kimi/userpromptsubmit.mjs",stop:"hooks/kimi/stop.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function JZ(t,e){try{LZ(2),zZ(VZ,"w")}catch{process.stderr.write=(()=>!0)}let r=GZ[t]?.[e];r||process.exit(1);let n=Go();await import(fd(yt(n,r)).href)}var et=process.argv.slice(2);function XZ(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," context-mode index <path> Index a file or directory into the FTS5 knowledge base"," context-mode search <query...> Search the current project's FTS5 knowledge base"," context-mode doctor Diagnose runtime issues, hooks, FTS5, version"," context-mode upgrade Fix hooks, permissions, and settings"," context-mode hook <platform> <event> Dispatch a configured hook script"," context-mode statusline Print Claude Code status line","","Index options:"," --source <label> Source label (default: project:<directory-name> or path)"," --project <path> Project identity for the content DB (default: indexed dir or cwd)"," --max-depth <n> Directory recursion depth (default: 5)"," --max-files <n> Directory file cap (default: 200)"," --ext <.ts,.md> Comma-separated extension allowlist"," --include <glob> Directory include pattern (repeatable)"," --exclude <glob> Directory exclude pattern (repeatable)"," --no-gitignore Do not apply .gitignore during directory walks"," --follow-symlinks Follow directory symlinks inside the root","","Search options:"," --project <path> Project identity for the content DB (default: cwd)"," --source <label> Filter to a source label (partial match)"," --limit <n> Results to show (default: 3)"," --type <code|prose> Filter by content type","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
|
|
1175
|
+
`))}if(et[0]==="--help"||et[0]==="-h"||et[0]==="help")XZ();else if(et[0]==="index")iq(et.slice(1)).then(t=>process.exit(t));else if(et[0]==="search")aq(et.slice(1)).then(t=>process.exit(t));else if(et[0]==="doctor")cq().then(t=>process.exit(t));else if(et[0]==="upgrade"){let t=et.indexOf("--platform"),e=t>=0&&et[t+1]?et[t+1]:void 0;lq(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);I.error(w.default.red(n)),process.exit(1)})}else et[0]==="hook"?JZ(et[1],et[2]):et[0]==="insight"?uq(et[1]?Number(et[1]):4747):et[0]==="statusline"?dq():Promise.resolve().then(()=>(oR(),nR));function bY(t){return t.replace(/\\/g,"/")}var hd=process.platform==="win32";function ld(t,e={}){yi(hd?"npm.cmd":"npm",t,{...e,...hd?{shell:!0}:{}})}function YZ(t,e={}){let r={...e,...hd?{shell:!0}:{}};DZ(hd?t.replace(/^npm /,"npm.cmd "):t,r)}function QZ(t,e=process.platform,r=MZ){let n={stdio:"ignore"},o=()=>console.error(`
|
|
1176
|
+
Could not auto-open browser. Open manually: ${t}`),s=KZ(t,e),i=!1;for(let{cmd:a,args:c}of s)try{r(a,c,n),i=!0;break}catch{}i||o()}function eq(){let t=WZ(import.meta.url),e=ox(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?Q(e,".."):e}function tq(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?Q(r,t,...e):Q(md(),"AppData","Local",t,...e)}return Q(md(),".cache",t,...e)}function Go(){let t=vt().platform;return Yn(t)?tq(t):eq()}function RR(){try{return JSON.parse(Wr(Q(Go(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function rq(){return new Promise(t=>{let e=UZ("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function dd(t){return t.envVar?t.envVar:"adapter default"}function CR(t){let e=[],r={};for(let n=0;n<t.length;n++){let o=t[n];if(!o.startsWith("--")||o==="--"){e.push(o);continue}let s=o.slice(2),i=s.indexOf("="),a=i>=0?s.slice(0,i):s,c=i>=0?s.slice(i+1):void 0,u=t[n+1],l=c!==void 0?c:u&&!u.startsWith("--")?(n++,u):!0;if(a==="include"||a==="exclude"){let d=r[a];r[a]=Array.isArray(d)?[...d,String(l)]:[String(l)]}else r[a]=l}return{positional:e,flags:r}}function Xn(t,e){let r=t[e];if(typeof r=="string"&&r.length>0)return r}function wR(t,e){return t[e]===!0||t[e]==="true"}function ER(t,e){let r=t[e];if(Array.isArray(r))return r.filter(Boolean);if(typeof r=="string"&&r.length>0)return[r]}function nx(t,e,r={}){let n=Xn(t,e);if(!n)return;let o=Number(n),s=r.min??1;if(!Number.isInteger(o)||o<s)throw new Error(`--${e} must be an integer >= ${s}`);return o}function nq(t){let e=Xn(t,"ext")??Xn(t,"extensions");if(!e)return;let r=e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.startsWith(".")?n:`.${n}`);return r.length>0?r:void 0}function OR(t,e){return t?Q(t):Q(e)}async function IR(t){let e=await xs(vt().platform),r=Sn(()=>e.getSessionDir()),n=Ir(r),{resolveContentStorePath:o}=await Promise.resolve().then(()=>(Jt(),Qx)),s=o({projectDir:t,contentDir:n});return{store:new vs(s),dbPath:s,contentDir:n}}function oq(t){try{if(TR(t).isDirectory())return`project:${BZ(t)||t}`}catch{}return t}function sq(t,e){let r=lo("Read",e);if(po(t,r,process.platform==="win32",e).denied)throw new Error(`Read denied by policy: ${t}`)}async function iq(t){try{let e=CR(t),r=e.positional[0];if(!r||r==="-h"||r==="--help")return console.log("Usage: context-mode index <path> [--source label] [--project path] [--max-files n] [--max-depth n] [--ext .ts,.md]"),r?0:1;let n=ZZ(r)?Q(r):Q(process.cwd(),r);if(!$e(n))throw new Error(`Path does not exist: ${n}`);let o=TR(n),s=OR(Xn(e.flags,"project"),o.isDirectory()?n:ox(n)),i=Xn(e.flags,"source")??oq(n),{store:a,dbPath:c}=await IR(s);try{if(sq(n,s),o.isDirectory()){let u=lo("Read",s),l=a.indexDirectory({path:n,source:i,include:ER(e.flags,"include"),exclude:ER(e.flags,"exclude"),maxDepth:nx(e.flags,"max-depth",{min:0}),maxFiles:nx(e.flags,"max-files"),extensions:nq(e.flags),respectGitignore:!wR(e.flags,"no-gitignore"),followSymlinks:wR(e.flags,"follow-symlinks"),perFileDeny:m=>{try{return po(m,u,process.platform==="win32",s).denied}catch{return!1}}}),d=l.capped?` (cap reached at ${l.filesIndexed} files)`:"",p=l.denied>0?`; ${l.denied} denied`:"",h=l.failed>0?`; ${l.failed} failed`:"";console.log(`Indexed ${l.filesIndexed} files (${l.totalChunks} sections) from ${n}${d}${p}${h}`)}else{let u=a.index({path:n,source:i});console.log(`Indexed ${u.totalChunks} sections (${u.codeChunks} with code) from ${n}`)}return console.log(`Source: ${i}`),console.log(`Project: ${s}`),console.log(`DB: ${c}`),0}finally{a.close()}}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`context-mode index: ${r}`),1}}async function aq(t){try{let e=CR(t),r=e.positional.join(" ").trim();if(!r||r==="-h"||r==="--help")return console.log("Usage: context-mode search <query...> [--source label] [--project path] [--limit n] [--type code|prose]"),r?0:1;let n=OR(Xn(e.flags,"project"),process.cwd()),{store:o,dbPath:s}=await IR(n);try{let i=nx(e.flags,"limit")??3,a=Xn(e.flags,"type");if(a&&a!=="code"&&a!=="prose")throw new Error("--type must be code or prose");let c=o.searchWithFallback(r,i,Xn(e.flags,"source"),a);if(c.length===0)return console.log(`No matches for: ${r}`),console.log(`Project: ${n}`),console.log(`DB: ${s}`),0;for(let[u,l]of c.entries()){let d=l.content.replace(/\s+/g," ").trim(),p=d.length>500?`${d.slice(0,500)}...`:d;console.log(`## ${u+1}. ${l.title}`),console.log(`Source: ${l.source}`),console.log(`Type: ${l.contentType}`),console.log(p),console.log("")}return 0}finally{o.close()}}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`context-mode search: ${r}`),1}}function rx(t){try{return Ir(t),I.success(w.default.green(`Storage ${t.kind}: PASS`)+w.default.dim(` \u2014 ${t.path} (${dd(t)})`)),0}catch(e){if(e instanceof Kt)return I.error(w.default.red(`Storage ${t.kind}: FAIL`)+w.default.dim(` \u2014 ${is(e)}`)),1;throw e}}async function cq(){process.stdout.isTTY&&console.clear();let t=vt(),e=await xs(t.platform);Rd(w.default.bgMagenta(w.default.white(" context-mode doctor "))),I.info(`Platform: ${w.default.cyan(e.name)}`+w.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0;try{let y=Jr(()=>e.getSessionDir()),_=Sn(()=>y.path),x=ss(()=>y.path);mc([`sessions: ${y.path} (${dd(y)})`,`content: ${_.path} (${dd(_)})`,`stats: ${x.path} (${dd(x)})`].join(`
|
|
1177
|
+
`),"Storage paths"),r+=rx(y),r+=rx(_),r+=rx(x)}catch(y){if(y instanceof Kt)r++,I.error(w.default.red(`Storage ${y.kind}: FAIL`)+w.default.dim(` \u2014 ${is(y)}`));else throw y}let n=Cd();n.start("Running diagnostics");let o,s;try{o=Qn(),s=Ei(o)}catch{return n.stop("Diagnostics partial"),I.warn(w.default.yellow("Could not detect runtimes")+w.default.dim(" \u2014 module may be missing, restart session after upgrade")),pc(w.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),mc(wi(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(bn(),Ud));process.platform==="linux"&&!y()&&!_n()&&(r++,I.error(w.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+w.default.dim(`
|
|
1175
1178
|
context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
|
|
1176
1179
|
V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
|
|
1177
1180
|
Refs: https://github.com/nodejs/node/issues/62515
|
|
1178
1181
|
https://github.com/mksglu/context-mode/issues/564
|
|
1179
1182
|
Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
|
|
1180
|
-
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}
|
|
1183
|
+
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}_n()?I.success(w.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):I.warn(w.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(r++,I.error(w.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+w.default.dim(` \u2014 ${s.join(", ")||"none"}`))):I.info(`Language coverage: ${s.length}/${i} (${a}%)`+w.default.dim(` \u2014 ${s.join(", ")}`)),I.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(w_(),jT)),x=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(x.exitCode===0&&x.stdout.trim()==="ok")I.success(w.default.green("Server test: PASS"));else{r++;let v=x.stderr?.trim()?` (${x.stderr.trim().slice(0,200)})`:"";I.error(w.default.red("Server test: FAIL")+` \u2014 exit ${x.exitCode}${v}`)}}catch(y){let _=y instanceof Error?y.message:String(y);_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("Server test: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,I.error(w.default.red("Server test: FAIL")+` \u2014 ${_}`))}I.step(`Checking ${e.name} hooks configuration...`);let c=Go(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?I.success(w.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?I.warn(w.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?w.default.dim(`
|
|
1181
1184
|
Run: ${y.fix}`):"")):I.error(w.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?w.default.dim(`
|
|
1182
|
-
Run: ${y.fix}`):""));I.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?I.success(w.default.green(`${y.name}: PASS`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):"")):I.error(w.default.red(`${y.name}: FAIL`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):""))}else{let y=_c(e,c);if(y.length===0)I.success(w.default.green("Hook scripts: PASS")+w.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let
|
|
1185
|
+
Run: ${y.fix}`):""));I.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?I.success(w.default.green(`${y.name}: PASS`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):"")):I.error(w.default.red(`${y.name}: FAIL`)+(_.detail?w.default.dim(` \u2014 ${_.detail}`):""))}else{let y=_c(e,c);if(y.length===0)I.success(w.default.green("Hook scripts: PASS")+w.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let x=Q(c,_);try{$R(x,PR.R_OK),I.success(w.default.green("Hook script exists: PASS")+w.default.dim(` \u2014 ${x}`))}catch{I.error(w.default.red("Hook script exists: FAIL")+w.default.dim(` \u2014 not found at ${x}`))}}}I.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?I.success(w.default.green("Plugin enabled: PASS")+w.default.dim(` \u2014 ${d.message}`)):I.warn(w.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),I.step("Checking team-shared hook configs in your workspace...");{let E=function(b){return!!(b.startsWith("/")||/^[A-Za-z]:[/\\]/.test(b)||b.includes("\\\\")||b.includes("fnm_multishells")||b.includes("process.execPath"))},C=function(b,k){if(typeof b=="string")k(b);else if(Array.isArray(b))for(let P of b)C(P,k);else if(b&&typeof b=="object")for(let P of Object.values(b))C(P,k)};var f=E,g=C;let y=process.cwd(),_=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],x=0,v=0;for(let b of _){let k=Q(y,b);if($e(k)){v++;try{let P=JSON.parse(Wr(k,"utf-8")),N=[];if(C(P,R=>{E(R)&&N.push(R)}),N.length>0){r++,x++;let R=N[0].length>100?N[0].slice(0,97)+"...":N[0];I.error(w.default.red("Hook config: FAIL")+` \u2014 ${b} has your machine's local paths baked in`+w.default.dim(`
|
|
1183
1186
|
This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
|
|
1184
1187
|
Found ${N.length} hard-coded path(s), e.g.: ${R}
|
|
1185
1188
|
Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
|
|
1186
|
-
Details: https://github.com/mksglu/context-mode/issues/613`))}else I.success(w.default.green("Hook config: PASS")+w.default.dim(` \u2014 ${
|
|
1189
|
+
Details: https://github.com/mksglu/context-mode/issues/613`))}else I.success(w.default.green("Hook config: PASS")+w.default.dim(` \u2014 ${b} is portable (no hard-coded paths)`))}catch(P){let N=P instanceof Error?P.message:String(P);I.warn(w.default.yellow("Hook config: WARN")+` \u2014 ${b} is not valid JSON`+w.default.dim(`
|
|
1187
1190
|
Doctor cannot scan it for portability issues until the file parses.
|
|
1188
1191
|
Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
|
|
1189
|
-
Parser said: ${N.slice(0,160)}`))}}}v===0&&I.info(w.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}I.step("Checking for leftover .mcp.json files from older versions...");{let y=yt(
|
|
1192
|
+
Parser said: ${N.slice(0,160)}`))}}}v===0&&I.info(w.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}I.step("Checking for leftover .mcp.json files from older versions...");{let y=yt(md(),".claude","plugins","cache","context-mode","context-mode");if(!$e(y))I.info(w.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let _=0,x=[];try{let v=jZ(y);for(let E of v){let C=yt(y,E,".mcp.json");$e(C)&&(_++,x.length<5&&x.push(E))}}catch(v){let E=v instanceof Error?v.message:String(v);I.warn(w.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+w.default.dim(`
|
|
1190
1193
|
Path: ${y}
|
|
1191
1194
|
Reason: ${E.slice(0,160)}
|
|
1192
1195
|
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?I.success(w.default.green("Leftover .mcp.json check: PASS")+w.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):I.warn(w.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${_} old .mcp.json file(s) left over from previous context-mode versions`+w.default.dim(`
|
|
1193
1196
|
These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
|
|
1194
|
-
Versions affected: ${
|
|
1197
|
+
Versions affected: ${x.join(", ")}${_>x.length?", ...":""}
|
|
1195
1198
|
Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
|
|
1196
|
-
Details: https://github.com/mksglu/context-mode/issues/609`))}}I.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(bn(),
|
|
1199
|
+
Details: https://github.com/mksglu/context-mode/issues/609`))}}I.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(bn(),Ud))).loadDatabase(),_=new y(":memory:");_.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),_.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let x=_.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();_.close(),x&&x.content==="hello world"?I.success(w.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,I.error(w.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let _=y instanceof Error?y.message:String(y),x=Go(),v=Q(x,"node_modules","better-sqlite3");!$e(v)?(r++,I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+w.default.dim(" \u2014 package-missing")+w.default.dim(`
|
|
1197
1200
|
Path: ${v}
|
|
1198
1201
|
Root cause: npm silently skipped better-sqlite3 because the package's \`engines\` field excluded the running Node (issue #514, e.g. Node 26 vs better-sqlite3@12.x).
|
|
1199
|
-
Try (primary): cd "${
|
|
1202
|
+
Try (primary): cd "${x}" && npm install better-sqlite3 --no-optional
|
|
1200
1203
|
Try (fallback): /context-mode:ctx-upgrade`))):_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("FTS5 / better-sqlite3: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(_)||/bindings\.node/i.test(_)||/\bbindings\b/i.test(_))&&process.platform==="win32"?I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+w.default.dim(`
|
|
1201
1204
|
Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
|
|
1202
1205
|
Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
|
|
1203
1206
|
Try (fallback): npm rebuild better-sqlite3`)):I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+w.default.dim(`
|
|
1204
|
-
Try: npm rebuild better-sqlite3`)))}I.step("Checking versions...");let
|
|
1205
|
-
Run: /context-mode:ctx-upgrade`)),
|
|
1206
|
-
Run: /context-mode:ctx-upgrade`)):I.info(`${e.name}: v${
|
|
1207
|
+
Try: npm rebuild better-sqlite3`)))}I.step("Checking versions...");let p=RR(),h=await rq(),m=e.getInstalledVersion();return h==="unknown"?I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===h?I.success(w.default.green("npm (MCP): PASS")+` \u2014 v${p}`):I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${h}`+w.default.dim(`
|
|
1208
|
+
Run: /context-mode:ctx-upgrade`)),m==="standalone"?I.info(w.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):m==="not installed"?I.info(w.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):h!=="unknown"&&m===h?I.success(w.default.green(`${e.name}: PASS`)+` \u2014 v${m}`):h!=="unknown"?I.warn(w.default.yellow(`${e.name}: WARN`)+` \u2014 v${m}, latest v${h}`+w.default.dim(`
|
|
1209
|
+
Run: /context-mode:ctx-upgrade`)):I.info(`${e.name}: v${m}`+w.default.dim(" \u2014 could not verify against npm registry")),r>0?(pc(w.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(pc(s.length>=4?w.default.green("Diagnostics complete!"):w.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function uq(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:o,cpSync:s}=await import("node:fs"),i=Q(Go(),"insight"),a=vt(),c=await xs(a.platform),u=Ir(Jr(()=>c.getSessionDir())),l=Ir(Sn(()=>u)),d=yt(ox(u),"insight-cache");$e(yt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),o(d,{recursive:!0});let p=n(yt(i,"server.mjs")).mtimeMs,h=$e(yt(d,"server.mjs"))?n(yt(d,"server.mjs")).mtimeMs:0;if(p>h&&(console.log("Copying Insight source..."),s(i,d,{recursive:!0,force:!0})),!$e(yt(d,"node_modules"))){console.log("Installing dependencies (first run)...");try{YZ("npm install --production=false",{cwd:d,stdio:"inherit",timeout:3e5})}catch{try{_i(yt(d,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!$e(yt(d,"node_modules","vite"))||!$e(yt(d,"node_modules","better-sqlite3")))throw _i(yt(d,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:d,stdio:"pipe",timeout:6e4});let m=`http://localhost:${t}`;console.log(`
|
|
1207
1210
|
context-mode Insight
|
|
1208
|
-
${
|
|
1209
|
-
`);let f=r("node",[yt(d,"server.mjs")],{cwd:d,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:l},stdio:"inherit"});f.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,_)=>{let
|
|
1211
|
+
${m}
|
|
1212
|
+
`);let f=r("node",[yt(d,"server.mjs")],{cwd:d,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:l},stdio:"inherit"});f.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,_)=>{let x=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},v=>{y(),v.resume()});x.on("error",_),x.on("timeout",()=>{x.destroy(),_(new Error("timeout"))}),x.end()})}catch{console.error(`
|
|
1210
1213
|
Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
|
|
1211
|
-
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),f.kill(),process.exit(1)}
|
|
1212
|
-
Insight error: ${r}`),process.exit(1)}}async function
|
|
1213
|
-
Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let k=Q(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!$e(k))try{let P=Q(n,"scripts","heal-better-sqlite3.mjs");if($e(P)){let N=await import(`${
|
|
1214
|
+
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),f.kill(),process.exit(1)}QZ(m),process.on("SIGINT",()=>{f.kill(),process.exit(0)}),process.on("SIGTERM",()=>{f.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
|
|
1215
|
+
Insight error: ${r}`),process.exit(1)}}async function lq(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:vt(),r=await xs(e.platform);Rd(w.default.bgCyan(w.default.black(" context-mode upgrade "))),I.info(`Platform: ${w.default.cyan(r.name)}`+w.default.dim(` (${e.confidence} confidence)`));let n=Go(),o=[],s=Cd(),i=Q(qe(),"plugins","marketplaces","context-mode");if($e(yt(i,".git"))){s.start("Syncing marketplace clone");try{yi("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(w.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),I.info(w.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(yi("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),yi("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(w.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(w.default.yellow("Marketplace sync skipped")),I.warn(w.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),I.info(w.default.dim(" Continuing \u2014 cache dir update will still happen."))}}I.step("Pulling latest from GitHub...");let a=RR(),c=yt(qZ(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{yi("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let p=c,m=JSON.parse(Wr(Q(p,"package.json"),"utf-8")).version??"unknown";if(m===a)I.success(w.default.green("Already on latest")+` \u2014 v${a}`),_i(c,{recursive:!0,force:!0});else{I.info(`Update available: ${w.default.yellow("v"+a)} \u2192 ${w.default.green("v"+m)}`);try{let b=Jv({ownPid:process.pid,ownPpid:process.ppid});if(b.length>0){let k=await Xv({pids:b});if(k.totalKilled>0){let P=k.totalKilled===1?"sibling MCP server":"sibling MCP servers";I.info(w.default.dim(`Stopped ${k.totalKilled} ${P} (SIGTERM: ${k.terminatedBySigterm}, SIGKILL: ${k.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let f=Qv();ld(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),ld(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(Wr(Q(p,"package.json"),"utf-8")).files||[],"src","package.json"],_=Q(n)+Kr,x=Q(p)+Kr,v=b=>{try{return!HZ(b).isSymbolicLink()}catch{return!1}};for(let b of y){let k=Q(p,b),P=Q(n,b);if((P+Kr).startsWith(_)&&(k+Kr).startsWith(x)&&v(k)&&$e(k))try{_i(P,{recursive:!0,force:!0}),kR(k,P,{recursive:!0,filter:v})}catch{}}try{let b;try{let{resolveHookRuntime:P}=await Promise.resolve().then(()=>(Xo(),Ax)),N=P();N.isBun&&(b=N.path)}catch{}(await Promise.resolve().then(()=>(mR(),pR))).normalizeHooksJsonOnly({pluginRoot:n,nodePath:process.execPath,jsRuntimePath:b,platform:process.platform})}catch{}try{if(e.platform==="claude-code"){let{rewriteShellSnapshots:b}=await Promise.resolve().then(()=>(SR(),vR)),k=Q(qe(),"shell-snapshots"),P=b({snapshotsDir:k,currentVersion:m});P.rewritten.length>0&&I.info(w.default.dim(` Healed ${P.rewritten.length} stale shell snapshot(s) \u2014 Bash tool calls in the active session will pick up v${m} immediately`))}}catch{}s.stop(w.default.green(`Updated in-place to v${m}`));let E=Q(n,".claude-plugin","plugin.json"),C=null;try{let b=JSON.parse(Wr(E,"utf-8"));b&&typeof b.version=="string"&&(C=b.version)}catch{}if(C!==m)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${C??"<missing>"}" but newVersion is "${m}". Refusing to bump registry.`);r.updatePluginRegistry(n,m),I.info(w.default.dim(" Registry synced to "+n));try{let b=Q(qe(),"plugins","installed_plugins.json");if($e(b)){let P=JSON.parse(Wr(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let N of P){let R=N?.installPath;if(typeof R!="string"||!R)continue;if(!$e(R))throw new Error(`installPath does not exist on disk: ${R}`);let O=Q(R,".claude-plugin","plugin.json");if(!$e(O))throw new Error(`missing plugin.json manifest at ${O}`);let F=JSON.parse(Wr(O,"utf-8"));if(F?.version!==N.version)throw new Error(`version mismatch \u2014 registry says "${N.version}" but ${O} says "${F?.version}"`)}}}catch(b){let k=b instanceof Error?b.message:String(b);throw new Error(`Registry consistency check failed: ${k}`)}try{let b=Q(qe(),"plugins","cache"),k="context-mode@context-mode",P=Hc({pluginRoot:n,pluginCacheRoot:b,pluginKey:k});if(P&&P.error)throw new Error(P.error);let N=Hc({pluginRoot:n,pluginCacheRoot:b,pluginKey:k});if(N&&Array.isArray(N.healed)&&N.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${N.healed.join(",")})`)}catch(b){let k=b instanceof Error?b.message:String(b);throw new Error(`plugin.json drift check failed: ${k}`)}try{let b=Q(qe(),"plugins","cache"),k="context-mode@context-mode",P=Uc({pluginCacheRoot:b,pluginKey:k});P&&P.removed&&P.removed.length>0&&I.info(w.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let N=Uc({pluginCacheRoot:b,pluginKey:k});if(N&&Array.isArray(N.removed)&&N.removed.length>0)throw new Error(`.mcp.json sweep drift: ${N.removed.length} file(s) still present after first pass`)}catch(b){let k=b instanceof Error?b.message:String(b);throw new Error(`.mcp.json sweep check failed: ${k}`)}try{let{healClaudeJsonMcpArgs:b}=await Promise.resolve().then(()=>(rm(),Yv)),k=Q(md(),".claude.json"),P=Q(qe(),"plugins","cache","context-mode","context-mode"),N=b({dotClaudeJsonPath:k,pluginCacheParent:P,newPluginRoot:n});N.healed&&N.healed.length>0&&I.info(w.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+m))}catch{}try{let b=Q(i,".claude-plugin","plugin.json");if($e(b)){let k=JSON.parse(Wr(b,"utf-8"));k?.version!==m&&(I.warn(w.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${k?.version}" but expected "${m}"`),I.info(w.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),ld(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!Yn(e.platform)){s.start("Verifying native addon ABI");let b=Q(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=Q(n,"hooks","ensure-deps.mjs");if(!$e(P))throw new Error(`missing ${P}`);await import(`${fd(P).href}?upgrade=${Date.now()}`),$e(b)?(s.stop(w.default.green("Native addons OK")+w.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(w.default.yellow("Native addon ABI cache missing")),I.warn(w.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(P){let N=P instanceof Error?P.message:String(P);s.stop(w.default.yellow("Native addon ABI bootstrap unavailable")),I.warn(w.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${N}`+w.default.dim(`
|
|
1216
|
+
Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let k=Q(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!$e(k))try{let P=Q(n,"scripts","heal-better-sqlite3.mjs");if($e(P)){let N=await import(`${fd(P).href}?upgrade=${Date.now()}`);typeof N.healBetterSqlite3Binding=="function"&&N.healBetterSqlite3Binding(n)}}catch{}$e(k)||(process.exitCode=1,I.error(w.default.red("better-sqlite3 native binding: MISSING")+w.default.dim(`
|
|
1214
1217
|
Path: ${k}`)+w.default.dim(`
|
|
1215
1218
|
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+w.default.dim(`
|
|
1216
1219
|
Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+w.default.dim(`
|
|
1217
|
-
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{
|
|
1218
|
-
`),"Changes Applied"):I.info(w.default.dim("No changes were needed."));let d=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";I.warn(w.default.yellow("Restart for new MCP tools to take effect.")+w.default.dim(` (${d})`)),I.step("Running doctor to verify..."),console.log();try{let
|
|
1220
|
+
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{ld(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(w.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(w.default.yellow("npm global update skipped")),I.info(w.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}_i(c,{recursive:!0,force:!0});try{let b=qe(),k=Q(b,"plugins","installed_plugins.json");if($e(k)){let P=Q(b,"plugins","cache"),N;try{N=pd(P)}catch{N=P}let R=N+Kr,F=JSON.parse(Wr(k,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(F))for(let K of F){let ge=K?.installPath;if(typeof ge!="string"||!ge||ge===n)continue;let We=Q(ge);if(!(We+Kr).startsWith(R)||!$e(We))continue;let _t;try{_t=pd(We)}catch{continue}if(!(_t+Kr).startsWith(R))continue;let Pr=Q(p,"skills");$e(Pr)&&(kR(Pr,Q(_t,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${m}`),I.success(w.default.green("Plugin reinstalled from GitHub!")+w.default.dim(` \u2014 v${m}`))}}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(w.default.red("Update failed")),I.error(w.default.red("GitHub pull failed")+` \u2014 ${h}`),process.exitCode=1,I.warn(w.default.yellow("In-place files were NOT updated")+w.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),I.info(w.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{_i(c,{recursive:!0,force:!0})}catch{}}I.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(I.success(w.default.green("Backup created")+w.default.dim(" -> "+u)),o.push("Backed up settings")):u?I.success(w.default.green("Backup skipped")+w.default.dim(" \u2014 no changes needed")):I.warn(w.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),I.step(`Configuring ${r.name} hooks...`);try{let p=r.configureAllHooks(n);for(let h of p)I.info(w.default.dim(` ${h}`)),o.push(h);I.success(w.default.green("Hooks configured")+w.default.dim(` \u2014 ${r.name}`))}catch(p){let h=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${h}`)}I.step("Setting hook script permissions...");let l=r.setHookPermissions(n);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let h=Q(n,p);try{$R(h,PR.F_OK),FZ(h,493),l.push(h)}catch{}}l.length>0?(I.success(w.default.green("Permissions set")+w.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):I.error(w.default.red("No hook scripts found")+w.default.dim(" \u2014 expected in "+Q(n,"hooks"))),o.length>0?mc(o.map(p=>w.default.green(" + ")+p).join(`
|
|
1221
|
+
`),"Changes Applied"):I.info(w.default.dim("No changes were needed."));let d=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";I.warn(w.default.yellow("Restart for new MCP tools to take effect.")+w.default.dim(` (${d})`)),I.step("Running doctor to verify..."),console.log();try{let p=Q(n,"cli.bundle.mjs"),h=Q(n,"build","cli.js"),m=$e(p)?p:h;yi("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{I.warn(w.default.yellow("Doctor had warnings")+w.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function dq(){let t=qe(),e=[Q(Go(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=Q(t,"plugins","installed_plugins.json");if($e(n)){let o=Q(t,"plugins","cache"),s;try{s=pd(o)}catch{s=o}let i=s+Kr,c=JSON.parse(Wr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(c))for(let u of c){let l=u?.installPath;if(typeof l!="string"||!l)continue;let d=Q(l);if(!(d+Kr).startsWith(i))continue;let p;try{p=pd(d)}catch{continue}(p+Kr).startsWith(i)&&e.push(Q(p,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>$e(n));r||process.exit(0),import(fd(r).href).catch(()=>{process.exit(0)})}export{YZ as npmExec,ld as npmExecFile,QZ as openInBrowser,bY as toUnixPath};
|